Search code examples
ansibleansible-templatejmespath

Ansible task - how can I loop over all predefined vars to create linux groups in this format?


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(',') }}"

Solution

  • 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