Search code examples
fileansiblefetchclients

In Ansible, how can I fetch file from multiple nodes and store this in one file centralized?


All what I need is in title, for example I want to know how I can do somethings like that :

---
- hosts: ansible-clients

  tasks:
    - name: Fetch source list from clients
      fetch: src=/etc/apt/sources.list
             dest=/tmp/allnodes.sourcelist

OR in simply way

echo remote@/etc/apt/sources.list >> local@/tmp/allnodes.sourcelist

I can create and run script in local but the only condition I have is to do all actions in one playbook.


Solution

  • You can use this play:

    ---
    - hosts: ansible-clients
      tasks:
        - name: Fetch source list from clients
          fetch:
            src: /etc/apt/sources.list
            flat: yes
            dest: "/tmp/{{ inventory_hostname }}.sourcelist"
        - name: Merge files
          run_once: yes
          delegate_to: localhost
          shell: "cat /tmp/{{ item }}.sourcelist >> /tmp/allnodes.sourcelist"
          with_items: "{{ groups['ansible-clients'] }}"
    
    • First task is used to fetch all files from remotes and store them in /tmp. inventory_hostname is used in filename to be sure it is unique.

    • Second task is run once on any host, and append all files (get list of hosts linked to group ansible-clients) in final file