ansible

How to run shell command for list with two strings


I would like to run a shell command with ansible that it formatted in this way:

command <item_1> <item_2>

and to loop for multiple items such as:

What would be the best way to achieve it?

Sincerely


Solution

  • A minimal example playbook

    ---
    - hosts: localhost
      become: false
      gather_facts: false
    
      tasks:
    
      - command:
          cmd: 'echo "cmd {{ item.p_1 }} {{ item.p_2 }}"'
        register: result
        loop_control:
          label: "{{ item.p_1 }} {{ item.p_2 }}"
        loop:
          - { p_1: 1_v1, p_2: 2_v1 }
          - { p_1: 1_v2, p_2: 2_v2 }
          - { p_1: 1_v3, p_2: 2_v3 }
    
      - debug:
          msg: "{{ item.stdout }}"
        loop_control:
          label: "{{ item.stdout }}"
        loop: "{{ result.results }}"
    

    will result into an output of

    TASK [command] ***************************
    changed: [localhost] => (item=1_v1 2_v1)
    changed: [localhost] => (item=1_v2 2_v2)
    changed: [localhost] => (item=1_v3 2_v3)
    
    TASK [debug] *****************************
    ok: [localhost] => (item=cmd 1_v1 2_v1) =>
      msg: cmd 1_v1 2_v1
    ok: [localhost] => (item=cmd 1_v2 2_v2) =>
      msg: cmd 1_v2 2_v2
    ok: [localhost] => (item=cmd 1_v3 2_v3) =>
      msg: cmd 1_v3 2_v3