user312307
user312307

Reputation: 140

Issues with multiple with_items in a task

I have a task which has multiple with_items and hence pick the latest defined item in the delegate which is not the expected result

- name: Add secondaries
  run_once: true
  delegate_to: "{{ item }}"
  with_items:
     - "{{ groups['mongodb-active'] }}"
  shell: /usr/bin/mongo --eval 'printjson(rs.add("{{ item }}:27017"))'
  with_items:
    - "{{ groups['mongodb-arbiter'] }}"

Upvotes: 1

Views: 560

Answers (2)

Vladimir Botka
Vladimir Botka

Reputation: 68034

Actually, this is a job for a simple play, I think.

- hosts: mongodb-active
  tasks:
    - shell: /usr/bin/mongo --eval 'printjson(rs.add("{{ item }}:27017"))'
      loop: "{{ groups['mongodb-arbiter'] }}"

Otherwise, it is possible to include task

$ cat mongo-eval.yml
- shell: /usr/bin/mongo --eval 'printjson(rs.add("{{ item }}:27017"))'
  loop: "{{ groups['mongodb-active'] }}"
  delegate_to: "{{ delegate_host }}"

and delegate from there

- name: Add secondaries
  run_once: true
  include_tasks: mongo-eval.yml
  loop: "{{ groups['mongodb-arbiter'] }}"
  loop_control:
    loop_var: delegate_host

For details see Execute an entire yaml task file one host after the other in ansible.

Upvotes: 1

ilias-sp
ilias-sp

Reputation: 6685

you cant have two with_items clauses. assuming you want to iterate the list groups['mongodb-active'] and execute the shell module for each item in the groups['mongodb-arbiter'] list, you could do it like that:

---
- hosts: localhost
  gather_facts: false
  vars:
    mongodb_active_list:
      - host1
      - host2
      - host3
    mongodb_arbiter_list:
      - json_a
      - json_b
      - json_c

  tasks:

    - name: print debug
      debug:
        msg: "running on host: {{ item.0 }}, shell module with argument: {{ item.1 }}"
      loop: "{{ query('nested', mongodb_active_list, mongodb_arbiter_list) }}"

UPDATE:

after understanding better the requirement, the task i would suggest is:

- name: Add secondaries
  delegate_to: "{{ groups['mongodb-active'][0] }}"
  shell: /usr/bin/mongo --eval 'printjson(rs.add("{{ item }}:27017"))'
  with_items:
    - "{{ groups['mongodb-arbiter'] }}"

it will delegate the task to the first host of the mongodb-active group (which is supposed to have only 1 host as clarification states), and iterate the task for all the hosts of the mongodb-arbiter group.

hope it helps

Upvotes: 1

Related Questions