2

I have a predefined ansible variables, and I want to create linux groups from these variables. The below task create only the groups in the first array g1,g2,g3 How can I loop over all lines to create other groups?

The predefined ansible vars:

user_details:
  - { name: "user1", groups: 'g1,g2,g3' }
  - { name: "user2", groups: 'g4,g5' }

The task as following:

- name: Create Group
  group:
    name: "{{ item }}"
    state: present
  loop: "{{ user_details.0.groups.split(',') }}"
franklinsijo
  • 17,784
  • 4
  • 45
  • 63

1 Answers1

2

Use jmespath and flattened to retrieve all the groups and then split them by the delimiter ,.

The loop would look like,

loop: "{{ lookup('flattened', (user_details | json_query(\"[*].groups\")) ).split(',') }}"

The outcome of this loop would be a list containing all the group names.

You might have to install the jmespath module to use the json_query

pip install jmespath
franklinsijo
  • 17,784
  • 4
  • 45
  • 63
  • 1
    For performance sake, especially if your origin user list is large, you might want to add the [`unique` filter](https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#set-theory-filters) after the split so that the loop does not go over the same group several times. – Zeitounator Apr 15 '20 at 23:22