spacejunkie92
spacejunkie92

Reputation: 13

For each loop with multiple variables

I'm running a javaprogram with shell module to iterate over a list of users, for each user I want to loop through a number of groups to add to each user.

I'm not looking to add new users/groups to the OS but to a program that runs on the server.

All users in USER_LIST should be added to all groups in GROUP_LIST.

Non working example:

vars: 
GROUP_LIST:
- DATA
- ONE
- TWO

USER_LIST:
- USER1
- USER2
- USER3

- name: add all users to all groups
  shell:
  cmd: |
    java -jar /opt/alt/Manager.jar mod -g {{GROUP_LIST}} {{item}} 
  loop: {{USER_LIST}}

Upvotes: 1

Views: 5751

Answers (1)

Frenchy
Frenchy

Reputation: 17037

you should use filter product:

- name: add all users to all groups
  shell:
  cmd: |
    java -jar /opt/alt/Manager.jar mod -g {{item.1}} {{item.0}} 
  loop: {{USER_LIST | product(GROUP_LIST) | list}}

for example:

  tasks:
    - name: list to dict
      debug: 
        msg: "java -jar /opt/alt/Manager.jar mod -g {{item.1}} {{item.0}}"
      loop: "{{ USER_LIST | product(GROUP_LIST) | list }}"

gives:

ok: [localhost] => (item=['USER1', 'DATA']) => {
    "msg": "java -jar /opt/alt/Manager.jar mod -g DATA USER1"
}
ok: [localhost] => (item=['USER1', 'ONE']) => {
    "msg": "java -jar /opt/alt/Manager.jar mod -g ONE USER1"
}
ok: [localhost] => (item=['USER1', 'TWO']) => {
    "msg": "java -jar /opt/alt/Manager.jar mod -g TWO USER1"
}
ok: [localhost] => (item=['USER2', 'DATA']) => {
    "msg": "java -jar /opt/alt/Manager.jar mod -g DATA USER2"
}
ok: [localhost] => (item=['USER2', 'ONE']) => {
    "msg": "java -jar /opt/alt/Manager.jar mod -g ONE USER2"
}
ok: [localhost] => (item=['USER2', 'TWO']) => {
    "msg": "java -jar /opt/alt/Manager.jar mod -g TWO USER2"
}
ok: [localhost] => (item=['USER3', 'DATA']) => {
    "msg": "java -jar /opt/alt/Manager.jar mod -g DATA USER3"
}
ok: [localhost] => (item=['USER3', 'ONE']) => {
    "msg": "java -jar /opt/alt/Manager.jar mod -g ONE USER3"
}
ok: [localhost] => (item=['USER3', 'TWO']) => {
    "msg": "java -jar /opt/alt/Manager.jar mod -g TWO USER3"
}

following the ansible version, you have, no need to add | list

Upvotes: 4

Related Questions