# Ansible playbook to delete a CNAME record from IPAM
#
# Example usage: ansible-playbook delete-ipam-cname.yml --extra-vars \
#  '{"alias_fqdn":"ansibletestalias.sandbox.illinois.edu","target_fqdn":"ansibletest.sandbox.illinois.edu"}'
#
# Copyright (c) 2018 Board of Trustees University of Illinois
---
- import_playbook: ipam-provider.yml

- name: Delete IPAM CNAME record
  hosts: localhost
  gather_facts: false
  vars:

    view: default
    alias_fqdn:
    target_fqdn:

  tasks:

    - assert: { that: "ansible_version.full is version('2.8', '>=')", quiet: true }

    - name: check required variables
      fail: msg="Required variable '{{ item }}' not set"
      when: not lookup('vars', item)
      loop:
        - alias_fqdn
        - target_fqdn

    - name: get existing record if any
      set_fact:
        # may return list or single object
        existing_record: "{{ lookup('nios', 'record:cname', filter={'view': view, 'name': alias_fqdn},
                                    return_fields=['view', 'name', 'canonical', 'ttl', 'use_ttl', 'extattrs', 'comment'],
                                    provider=ipam_provider) }}"

    - debug: var=existing_record
      when: DEBUG is defined

    - when: existing_record
      block:

      - name: check existing CNAME target
        fail:
          msg: Not deleting mismatched CNAME '{{alias_fqdn}}' = '{{existing_record.canonical}}'
        when: existing_record.canonical != target_fqdn

    - name: delete CNAME record
      when: existing_record
      nios_cname_record:
        view: "{{ view }}"
        name: "{{ alias_fqdn }}"
        canonical: "{{ target_fqdn }}"
        state: absent
        provider: "{{ ipam_provider }}"
