Search code examples
ansibleansible-2.xansible-inventoryansible-factsansible-template

Ansible run shell module on multiple host's and redirect output to 1 file


I need to run shell module on all hosts group and copy the register variable to a file on any server.

NOTE : I don't want to copy the results in my local i need it on server

- name: date.
  shell: cat /ngs/app/user/test
  register: date_res
  changed_when: false
- debug:
    msg: "{{ ansible_play_hosts | map('extract', hostvars, 'date_res') | map(attribute='stdout') | list }}"
  run_once: yes
  
- name: copy bulk output
  copy:
    content: "{{ allhost_out.stdout }}"
    dest: "/ngs/app/{{ app_user }}/test"

Solution

  • Jinja2 loop can be helpful for your case.
    Tested on ansible [core 2.13.3]

    - name: date.
      shell: cat /ngs/app/user/test
      register: date_res
      changed_when: false
      
    - name: copy bulk output
      copy:
        content: |
            {% for host in vars['play_hosts'] %}
            {{ host }} {{ hostvars[host].date_res.stdout }}
            {% endfor %}
        dest: "/ngs/app/{{ app_user }}/bldall"
      when: inventory_hostname == host-001.example.com
    

    On host-001.example.com placed a file contains: host1 file content.
    On host-002.example.com placed a file contains: host2 file content.
    Output on host specified in the copy task:

    host-001.example.com host1 file content
    host-002.example.com host2 file content