---
# If you want to use API token to be authenticated by Zabbix Server
# https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens
- name: Set API token
  tags:
    - never
    - sync_users
  set_fact:
    ansible_zabbix_auth_key: "{{ (env == 'staging')|ternary(zabbix_stg_apikey, zabbix_apikey) }}"
    ansible_network_os: community.zabbix.zabbix
    ansible_connection: httpapi
    ansible_httpapi_port: 443
    ansible_httpapi_use_ssl: true
    ansible_httpapi_validate_certs: false
    ansible_host: "{{ (env == 'staging')|ternary(zabbix_stg_hostname, zabbix_hostname) }}"
    ansible_zabbix_url_path: ""  # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu

- name: Retrieve fasjson group membership
  tags:
    - never
    - sync_users
  zabbix_retrieve_sysadmin_noc_group_membership:
    keytab_path: "{{ (env == 'staging')|ternary(zabbix_stg_kerberos_keytab_path, zabbix_kerberos_keytab_path) }}"
    principal: "{{ (env == 'staging')|ternary(zabbix_stg_kerberos_principal, zabbix_kerberos_principal) }}"
    fasjson_host: "{{ (env == 'staging')|ternary(zabbix_stg_fasjson_host, zabbix_fasjson_host) }}"
    group_name: "{{ zabbix_fasjson_group_name }}"
  register: zabbix_fasjson_response

- name: Print fasjson response
  tags:
    - never
    - sync_users
  ansible.builtin.debug:
    msg: "{{ zabbix_fasjson_response['group'] }}"

- set_fact:
    zabbix_sysadmin_noc_members: "{{ zabbix_fasjson_response['group']|from_json }}"
  tags:
    - never
    - sync_users

- name: Create a the zabbix user for each sysadmin-noc member.
    # set task level variables as we change ansible_connection plugin here
  tags:
    - never
    - sync_users
  community.zabbix.zabbix_user:
    username: "{{ item }}"
    name: "{{ item }}"
    surname: "{{ item }}"
    role_name: Admin role
    usrgrps:
      - Zabbix administrators
    passwd: "{{ lookup('password', '/dev/null chars=ascii_lowercase,digits,ascii_uppercase,punctuation length=15') }}"
    state: present
  with_items: "{{ zabbix_sysadmin_noc_members['groupmembers'] }}"
