---

- name: "Read DNS entry for <{{ record_to_remove }}.{{ domain }}> from digitalocean"
  uri:
    url: "https://api.digitalocean.com/v2/domains/{{ domain }}/records?name={{ record_to_remove }}.{{ domain }}"
    headers:
      accept: application/json
      authorization: "Bearer {{ digitalocean_authentication_token }}"
    return_content: yes
  register: domain_records_response
  delegate_to: 127.0.0.1
  become: false

- name: "Save DNS entry as variable (fact)"
  set_fact: 
    domain_records_response_json: "{{ domain_records_response.json }}"
  delegate_to: 127.0.0.1
  become: false

- name: "Parse DNS entry for <{{ record_to_remove }}.{{ domain }}>"
  set_fact:  
    domain_record: "{{ domain_records_response_json.domain_records | json_query(jmesquery) | first | default({'name': '-', 'ip': '-'}) }}"
  vars:
    jmesquery: '[*].{id: id, name: name, ip: data}'
  delegate_to: 127.0.0.1
  become: false

- name: "Print DNS entry for <{{ record_to_remove }}.{{ domain }}>"
  debug:
    msg: "{{ domain_record }}"
  delegate_to: 127.0.0.1
  become: false

- name: "Delete DNS entry <{{ record_to_remove }}> for <{{ domain }}>"
  uri:
    method: DELETE
    url: "https://api.digitalocean.com/v2/domains/{{ domain }}/records/{{ domain_record.id }}"
    headers:
      authorization: Bearer {{ digitalocean_authentication_token }}
    return_content: yes
    status_code: 204
  changed_when: true
  when:
        domain_record.ip != '-'
    and record_to_remove != domain_record.ip
  delegate_to: 127.0.0.1
  become: false
