---
- name: Read groups of realm {{ current_realm_name }}
  uri:
    url: "{{ shared_service_url_keycloak }}/auth/admin/realms/{{ current_realm_name }}/groups"
    method: GET
    headers:
      Authorization: "Bearer {{ access_token }} "
    status_code: [200]
  register: realm_groups
  tags:
    - create_groups
    - update_realms

- name: Print realm groups
  debug:
    msg: "{{ realm_groups }}"
  tags:
    - always
  when:
    - debug

- name: Save realm groups as variable (fact)
  set_fact: 
    realm_groups_json: "{{ realm_groups.json }}"
  tags:
    - create_groups
    - update_realms

- name: Read realm group names
  set_fact:  
    realm_groupnames:  "{{ realm_groups_json | json_query(jmesquery) }}"
  vars:
    jmesquery: '[*].name'
  tags:
    - create_groups
    - update_realms

- name: Print realm groupnames
  debug:
    msg: "{{ realm_groupnames }}"
  tags:
    - always
  when:
    - debug

- name: "Create groups for realm {{ current_realm_name }}"
  uri:
    url: "{{ shared_service_url_keycloak }}/auth/admin/realms/{{ current_realm_name }}/groups"
    method: POST
    body_format: json
    body: "{{ lookup('template','keycloak-realm-create-group.json.j2') }}"
    headers:
      Content-Type: "application/json"
      Authorization: "Bearer {{ access_token }}"
    status_code: [201]
  with_items: "{{ current_realm_groups | default([]) }}"
  when: current_realm_group.name not in realm_groupnames
  loop_control:
    loop_var: current_realm_group
  tags:
    - create_groups
    - update_realms
