---
- name: "Generate Traefik labels for custom admin access to specific realm(s)"
  ansible.builtin.set_fact:
    labels:
      - '"traefik.http.routers.{{ keycloak_id }}-admin-{{ keycloak_accessible_realm.name }}.service={{ keycloak_id }}"'
      - '"traefik.http.routers.{{ keycloak_id }}-admin-{{ keycloak_accessible_realm.name }}.rule=Host(`{{ stage_server_domain }}`) && Method(`POST`,`PUT`,`DELETE`,`PATCH`) && (PathPrefix(`/auth/realms/{{ keycloak_accessible_realm.name }}`) || PathPrefix(`/auth/admin/{{ keycloak_accessible_realm.name }}`) || PathPrefix(`/auth/admin/realms/{{ keycloak_accessible_realm.name }}`))"'
      - '"traefik.http.routers.{{ keycloak_id }}-admin-{{ keycloak_accessible_realm.name }}.entrypoints=websecure"'
      - '"traefik.http.routers.{{ keycloak_id }}-admin-{{ keycloak_accessible_realm.name }}.tls=true"'
      - '"traefik.http.routers.{{ keycloak_id }}-admin-{{ keycloak_accessible_realm.name }}.tls.certresolver=letsencrypt-http"'
      - '"traefik.http.routers.{{ keycloak_id }}-admin-{{ keycloak_accessible_realm.name }}.middlewares={{ keycloak_id }}-admin-{{ keycloak_accessible_realm.name }}-ipwhitelist"'
      - '"traefik.http.middlewares.{{ keycloak_id }}-admin-{{ keycloak_accessible_realm.name }}-ipwhitelist.ipwhitelist.sourcerange={{ (ip_whitelist + (keycloak_accessible_realm.admin_ips) | default([])) | join(",") }}"'
  loop: "{{ keycloak_admin_realm_acls }}"
  register: keycloak_accessible_realms
  loop_control:
    loop_var: keycloak_accessible_realm
  tags:
    - update_deployment

- name: "Extract keycloak_accessible_realms"
  ansible.builtin.set_fact:
    keycloak_labels_additional: "{{ keycloak_labels_additional | default([]) + keycloak_accessible_realm.ansible_facts.labels }}"
  loop: "{{ keycloak_accessible_realms.results }}"
  loop_control:
    loop_var: keycloak_accessible_realm
  tags:
    - update_deployment

# Neccessary for Trafik labels to allow POST method from AWX on k8s
- name: "Get k8s_worker_node_ips"
  block:
    - name: "Lookup hetzner servers - smaradigo k8s worker nodes"
      become: false
      delegate_to: localhost
      hcloud_server_info:
        api_token: "{{ hetzner_authentication_ansible_vault }}"
        label_selector: "service=kube_node,stage={{ stage }}"
      register: found_servers
    - name: "Initial VAR(s)"
      set_fact:
        k8s_worker_node_ips: []
    - name: "Get IPs from k8s worker nodes"
      set_fact:
        k8s_worker_node_ips: '{{ k8s_worker_node_ips + [ item + "/32" ] }}'
      loop: '{{ found_servers.hcloud_server_info | selectattr("ipv4_address","defined") | map(attribute="ipv4_address") }}'
  tags:
    - update_deployment
