Search code examples
ansibleansible-template

How can I copy files using the ansible.builtin.copy module and avoid conflicting file names?


I want files in the src directory to copy to the dest directory but I don't want the files with the same name to copy over. Does anyone know how I can do that?

- name: Copy files but not the ones that have the same name
  copy:
    src:  <src_dir>
    dest: <dest_dir>

Solution

  • Q: "Don't copy the files with the same name."

    A: Set the parameter force to false. Quoting

    If false, the file will only be transferred if the destination does not exist.

        - copy:
            src: /tmp/test/src/
            dest: /tmp/test/dest/
            force: false
    

    Example.

    Given the files

    shell> tree /tmp/test/
    /tmp/test/
    ├── dest
    │   └── a
    └── src
        ├── a
        ├── b
        └── c
    
    2 directories, 4 files
    
    shell> cat /tmp/test/src/*
    src
    src
    src
    
    shell> cat /tmp/test/dest/*
    dest
    

    The playbook

    - hosts: localhost
      tasks:
        - copy:
            src: /tmp/test/src/
            dest: /tmp/test/dest/
            force: false
    

    will copy the files b and c only because the file a exists

    shell> tree /tmp/test/
    /tmp/test/
    ├── dest
    │   ├── a
    │   ├── b
    │   └── c
    └── src
        ├── a
        ├── b
        └── c
    
    2 directories, 6 files
    
    shell> cat /tmp/test/dest/*
    dest
    src
    src