Ansible - Copy Same File to Many Different Paths

32 Views Asked by At

I would like copy a file stored in the Ansible Controller to about 50 nodes that each contain 3 - 5 different webapps that each have a different file path.

Ex: source file /home/user/file
    destination: /home/user/webapps/webapp_name/file
                 /home/user/webapps/webapp_name2/file 
                 /home/user/webapps/webapp_name3/file

The file is hidden

The only difference in the path is the webapp name.

How can I do this?

I have tried storing the file paths with this play:

- name: Replace file
  hosts: webservers
  tasks:
    - name: Find File Path
      ansible.builtin.find:
        paths: /home/user/webapps/*
        patterns: '*.file'
        recurse: yes
        file_type: file
        hidden: true
        register: file_paths
    
    - name: Create Path Dictionary
      set_fact:
        path: "{{ dict(path|zip(paths)) }}"
      vars:
        paths: "{{ file_paths.results| map(attribute='files')|list }}"

and then using the copy module but I have not been able to store any path to use as a variable

1

There are 1 best solutions below

0
larsks On

The description of what you want to do differs a bit from what you are apparently trying to do in your playbook. Ignoring the playbook and focusing on the description, something like this might do what you want:

- name: Distribute file
  hosts: all
  gather_facts: false
  tasks:
    - name: Find webapp directories
      ansible.builtin.find:
        paths: /home/user/webapps/
        file_type: directory
        depth: 1
      register: file_paths

    - name: Copy file into webapps
      copy:
        src: myfile
        dest: "{{ item.path }}/myfile"
      loop: "{{ file_paths.files }}"

This builds a list of directories inside the /home/user/webapp directory, and then copies local file myfile into each webapp directory.