---
- name: "Reading users of realm {{ current_realm_name }}"
  uri:
    url: "{{ shared_service_url_keycloak }}/auth/admin/realms/{{ current_realm_name }}/users"
    method: GET
    headers:
      Authorization: "Bearer {{ access_token }} "
    status_code: [200]
  register: realm_users
  delegate_to: 127.0.0.1
  become: false

- name: "Printing realm users"
  debug:
    msg: "{{ realm_users }}"
  delegate_to: 127.0.0.1
  become: false
  when:
    - debug

- name: "Saving users of realm {{ current_realm_name }} as variable (fact)"
  set_fact: 
    realm_users_json: "{{ realm_users.json }}"
  delegate_to: 127.0.0.1
  become: false

- name: "Reading user ids of realm {{ current_realm_name }}"
  set_fact:  
    realm_user_usernames:  "{{ realm_users_json | json_query(jmesquery) }}"
  vars:
    jmesquery: '[*].username'
  delegate_to: 127.0.0.1
  become: false

- name: "Printing usernames of realm {{ current_realm_name }}"
  debug:
    msg: "{{ realm_user_usernames }}"
  delegate_to: 127.0.0.1
  become: false
  when:
   - debug

- name: "Printing usernames for realm {{ current_realm_name }}"
  debug:
    msg: "{{ current_realm_users }}"
  delegate_to: 127.0.0.1
  become: false
  when:
   - debug

- name: "Creating users for realm {{ current_realm_name }}"
  uri:
    url: "{{ shared_service_url_keycloak }}/auth/admin/realms/{{ current_realm_name }}/users"
    method: POST
    body_format: json
    body: "{{ lookup('template','keycloak-realm-create-user.json.j2') }}"
    headers:
      Content-Type: "application/json"
      Authorization: "Bearer {{ access_token }}"
    status_code: [201]
  with_items: "{{ current_realm_users }}"
  when: current_realm_user.username not in realm_user_usernames
  changed_when: True
  loop_control:
    loop_var: current_realm_user
  delegate_to: 127.0.0.1
  become: false
