Search code examples
ansibleansible-templateansible-awx

I need the playbook to check if the path from the list exists, and if it exists, then it would copy the file using it


I need the playbook to check if the path from the list exists, and if it exists, then it would copy the file using it

vars:
   array_path:
     - /opt/1/1/data/123/
     - /opt/2/2/data/234/
     - /opt/3/3/data/345/
     - /opt/4/4/data/456/
     - /opt/5/5/data/567/
     - /opt/6/6/data/678/
 tasks:
  
  - name: Chek path opt
    stat: 
      path:  '{{ item }}'
    loop: '{{ array_path }}'
    register: path_is_true
    
  - name: Print path_is_true
    debug:  
      var: item.path
    loop: '{{ array_path }}'
    when:  

  - name:  Copy a file to array_path
    ansible.builtin.copy:
      src: myfile.txt
      dest: '{{ item }}'
      owner: lord
      group: lord
      mode: '0755'
      backup: yes
    loop: '{{ array_path }}'  
    when: 

idk how to correctly initiate 'when'. maybe there are some other errors in the playbook


Solution

  • i resolved

    ---
    - hosts: all
      tasks:
        - stat: path={{mypath}}
          loop:
            - /opt/1/1/data/123/
            - /opt/2/2/data/234/
            - /opt/3/3/data/345/
            - /opt/4/4/data/456/
            - /opt/5/5/data/567/
            - /opt/6/6/data/678/
          loop_control:
            loop_var: mypath
          register: foo
    
     - name:  Copy a file to array_path
        ansible.builtin.copy:
          src: myfile.txt
          dest: '{{ item.mypath}}'
          owner: lord
          group: lord
          mode: '0755'
          backup: yes
        loop: '{{ foo.results }}'
        when: item.stat.exists