Search code examples
ansibleansible-2.xansible-inventory

Nested loop in Ansible


I am aware of the nested loops documentation here: http://docs.ansible.com/ansible/playbooks_loops.html#nested-loops I have 3 servers: say server1, server2, server3. I need to run a command in this fashion:

Run command on server1
Run command on server1, Run command on server2
Run command on server1, Run command on server2, Run command on server3

Any idea how I can do this using loops in ansible? I know how I can run nested loops using loop and product filter. But dont know how I can handle my particular case using Ansible.


Solution

  • It depends on the structure of the data. For example, the playbook would do the job

    - hosts: server1,server2,server3
      vars:
        batch001:
          - command: "foo"
            hosts: [server1]
          - command: "bar"
            hosts: [server1, server2]
          - command: "baz"
            hosts: [server1, server2, server3]
      tasks:
        - command: "{{ item.command }}"
          loop: "{{ batch001 }}"
          when: inventory_hostname in item.hosts
    

    Next option would be to create a dictionary of servers with nested lists of commands. For example,

    - hosts: server1,server2,server3
      vars:
        batch002:
          server1:
            commands: ["foo", "bar", "baz"]
          server2:
            commands: ["foo", "bar"]
          server3:
            commands: ["foo"]
      tasks:
        - command: "{{ item }}"
          loop: "{{ batch002[inventory_hostname]['commands'] }}"