ansiblenetwork-programmingansible-2.x

How to pass a variable list to another play with different hosts


I want to append all the hostnames into a list and pass it to another play with different host-group (remote server) where it searches for a file with a pattern. I am trying an Ansible playbook -

- name: Begin
  hosts: cisco
  tasks:
    - name: Initializing an empty list where I will try to append the hostnames
      set_fact:
        my_string: []

- name: Append info
  hosts: cisco
  gather_facts: no
  tasks:
    - name: Append hostname to list (appending is not working, not sure how to pass inventory_hostnames recursively)
      set_fact:
        my_string: "{{ my_strings + [inventory_hostname] }}"

- hosts: remoteserver
  tasks:
    - name: Find stored configuration file on remote server by passing value item from loop (Ansible can not find this variable my_string)
      find:
        paths: /Config/ansible-backups/
        patterns: "{{ item }}-config-*.txt"
      register: stored_configs
      loop: "{{ hostvars['cisco']['my_string'] }}"

As can be seen, the list my_string is not working as intended and I am not able to pass the list to second part. I am using version 2.10.17. Any suggestions how to proceed?


Solution

  • For an inventory file example.ini with content of

    [inventory:children]
    switches
    servers
    
    [switches]
    one.example.com
    two.example.com
    
    [servers]
    three.example.com
    four.example.com
    

    a minimal example playbook

    ---
    - hosts: servers
      become: false
      gather_facts: false
    
      tasks:
    
        - name: On Remote Servers, passing value item from loop
          debug:
            msg: "{{ item }}-config-*.txt"
          loop: "{{ groups['switches'] }}"
    

    called via

    ansible-playbook --inventory example.ini inventory.yml
    

    will result into an output of

    TASK [On Remote Servers, pass value item from loop] *******
    ok: [three.example.com] => (item=one.example.com) =>
      msg: one.example.com-config-*.txt
    ok: [three.example.com] => (item=two.example.com) =>
      msg: two.example.com-config-*.txt
    ok: [four.example.com] => (item=one.example.com) =>
      msg: one.example.com-config-*.txt
    ok: [four.example.com] => (item=two.example.com) =>
      msg: two.example.com-config-*.txt