loopsansible

Iterate 2 unequal items using ansible loop


I'm trying to iterate 2 lists through Ansible. First is a static variable with 2 items, second is a register variable with 25 items.

static_variable :
  - 1 
  - 2

register variable (got from an output)

first_commmand_output:
 - one
 - two
 - .
 - .
 - twenty five

I'm expecting 1 (static variable) to iterate all 25 registered variables (one at a time) and 2 to do the same.

However, while using product filter, 1 instead of iterating 1 to 25 (one at a time), iterates it all at once. This is not desired as I need to pass this output as an argument to another command.

---
- name: To get the list of first command
  shell: ./mqcli.py -a {{ item }} "some command" | awk -F"[()]" '{print $2}' 
  loop: "{{ static_variable }}" 
  register: first_commmand_output

# first task runs as expected

- name: To run second command based on first's output
  shell: ./mqcli.py -a {{ item.0 }} "listcert -m "{{ item.1.stdout_lines }}"" 
  loop: "{{ static variable | product(first_command_output.results) | list }}"
  register: second_command_output
  
#  requiring assistance for the 2nd 

Solution

  • Given the variables

      svar: [1, 2]
      dvar: [one, two, three]
    

    declare the data

      data: "{{ dict(svar | product([{'dvar': dvar}])) }}"
    

    gives

      data:
        1:
          dvar: [one, two, three]
        2:
          dvar: [one, two, three]
    

    In the loop, convert the dictionary to list and iterate subelements

        - debug:
            msg: "{{ item.0.key }} {{ item.1 }}"
          loop: "{{ data | dict2items | subelements('value.dvar') }}"
    

    gives (abridged)

      msg: 1 one
      msg: 1 two
      msg: 1 three
      msg: 2 one
      msg: 2 two
      msg: 2 three
    

    Example of a complete playbook for testing

    - hosts: localhost
    
      vars:
    
        svar: [1, 2]
        dvar: [one, two, three]
        data: "{{ dict(svar | product([{'dvar': dvar}])) }}"
    
      tasks:
    
        - debug:
            var: data | to_yaml
    
        - debug:
            msg: "{{ item.0.key }} {{ item.1 }}"
          loop: "{{ data | dict2items | subelements('value.dvar') }}"