Search code examples
ansibleansible-2.x

Copy folder if it exists locally


I have a list of domains, and I want Ansible to check if a folder with the same name exists locally, then copy it over to the target server and skip if the folder doesn't exist locally.

I'm not sure on how to use when in copy custom files task.

I have this so far:

---
- hosts: all
  gather_facts: true
  vars:
    domains:
    - domain: domain1.com
    - domain: domain2.com
    - domain: domain3.com
  tasks:
  - name: check for website files
    local_action: stat path={{ playbook_dir }}/files/var/www/{{ item.domain }}
    register: files_check
    with_items: "{{ domains }}"

  - name: print variable facts
    debug:
      msg: "{{ files_check }}"

  - name: copy custom files
    copy:
      src: files/var/www/{{ item.domain }}
      dest: /var/www/{{ item.domain }}
      owner: root
      group: root
      force: true
    with_items: "{{ domains }}"
    when: ???

Solution

  • Testing the paths on the controller is simple. You don't need the stat module. When the variable src keeps the path use the condition below

        when: src is exists
    

    For example, given the tree

    shell> tree .
    .
    ├── ansible.cfg
    ├── files
    │   └── var
    │       └── www
    │           ├── domain1.com
    │           └── domain2.com
    ├── hosts
    └── pb.yml
    

    , the inventory

    shell> cat hosts
    test_11
    test_13
    

    , and the playbook

    shell> cat pb.yml
    - hosts: all
    
      vars:
    
        domains:
          - domain1.com
          - domain2.com
          - domain3.com
    
      tasks:
    
      - name: copy custom files
        copy:
          src: "{{ src }}"
          dest: "/var/www/{{ item }}"
          owner: root
          group: root
          force: true
        loop: "{{ domains }}"
        when: src is exists
        vars:
          src: "files/var/www/{{ item }}"
    

    give, running in --check --diff mode

    shell> ansible-playbook pb.yml -CD
    
    PLAY [all] ***********************************************************************************
    
    TASK [copy custom files] *********************************************************************
    ok: [test_11] => (item=domain1.com)
    ok: [test_13] => (item=domain1.com)
    ok: [test_11] => (item=domain2.com)
    skipping: [test_11] => (item=domain3.com) 
    ok: [test_13] => (item=domain2.com)
    skipping: [test_13] => (item=domain3.com) 
    
    PLAY RECAP ***********************************************************************************
    test_11: ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
    test_13: ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    

    Notes: