---
- name: Determine if DDNS key already exists
  become: false
  delegate_to: localhost
  ansible.builtin.stat:
    path: "{{ bind9_local_keydir }}/{{ item.update_keyfile }}.private"
  register: update_keyfile_tmp
  when: item.update_keyfile is defined

- name: Generate DDNS key
  ansible.builtin.shell: "tsig-keygen -a {{ item.update_key_algorithm | d('hmac-sha512') }} {{ item.name }}_{{ item.update_keyfile }}_update > /etc/bind/keys/{{ item.update_keyfile }}.private"
  args:
    chdir: "{{ bind9_zonedir }}"
  register: ddns_key
  changed_when: ddns_key.rc != 0
  when: item.update_keyfile is defined and not update_keyfile_tmp.stat.exists

- name: Copy DDNS key to control host
  ansible.builtin.fetch:
    src: "/etc/bind/keys/{{ item.update_keyfile }}.private"
    dest: "{{ bind9_local_keydir }}/{{ item.update_keyfile }}.private"
    mode: "0640"
    flat: true
  when: ddns_key.changed

- name: Create dummy DDNS public key file on control host
  become: false
  delegate_to: localhost
  ansible.builtin.file:
    path: "{{ bind9_local_keydir }}/{{ item.update_keyfile }}.key"
    mode: "0640"
    state: touch
  when: ddns_key.changed
