# Ansible playbook to add an A record to IPAM
#
# Example usage: ansible-playbook add-ipam-a.yml --extra-vars \
#  '{"fqdn":"ansibletest.sandbox.illinois.edu","ipv4addr":"192.168.0.17","extattrs":{"TechSvcNetDevice":"N/A"}}'
#
# Copyright (c) 2018 Board of Trustees University of Illinois
---
- import_playbook: ipam-provider.yml

- name: Add IPAM A record
  hosts: localhost
  gather_facts: false
  vars:

    view: default
    fqdn:
    ipv4addr:
    ttl:
    extattrs: {}
    comment:

  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:
        - fqdn
        - ipv4addr

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

    - debug: var=existing_record
      when: DEBUG is defined

    - name: create A record
      when: not existing_record
      nios_a_record:
        view: "{{ view }}"
        name: "{{ fqdn }}"
        ipv4addr: "{{ ipv4addr }}"
        state: present
        ttl: "{{ ttl|default(omit, true) }}"
        extattrs: "{{ extattrs|default(omit, true) }}"
        comment: "{{ comment|default(omit, true) }}"
        provider: "{{ ipam_provider }}"
