Dns lookup record and fail if no record exists

I am struggling with a task to 1 look up the DNS name of a host and to if no dns record exists for the host fail. I have the first part of the task with the second task.
This is what I have so far

- name: Simple A record (IPV4 address) lookup for foreman.example.com
  ansible.builtin.debug:
    msg: "{{ lookup('community.general.dig', 'foreman.example.com.')}}"

- assert:
    that:
      - ansible_facts["foreman.example.com"] in dns_result.[0].values
    fail_msg: "Hostname does not match DNS record"
    quiet: yes

Hi, just as an idea, you can do that by this single task, for example.

- ansible.builtin.assert:
    that:
      - dig != ""
      - dig != "NXDOMAIN"
  vars:
    dig: "{{ lookup('community.general.dig', 'foreman.example.com.') }}"

As a side note, I’m curious about the intent of ansible_facts["foreman.example.com"] and dns_result.[0].values in your snippet. Perhaps there might be a slight misunderstanding about variables and ansible_facts.
You can refer to the official docs about facts and variables:

2 Likes

Thanks that’s just what I needed for the task. Appreciate it.

do note, however, that the vars specified for the assert task are local to the task, i.e. the variable dig is not available after the assert is evaluated.

3 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.