You can use the dig lookup in order to achieve this. Then add the lines in the hosts file with lineinefile.
Please mind that the module dig needs the Python library dnspython to operate. So you might want to install it as well with Ansible.
So, given the playbook:
- hosts: all
gather_facts: no
tasks:
- package:
name: py-dnspython
state: present
- lineinfile:
path: /etc/hosts
line: "{{ item }} ip-{{ item | replace('.', '-') }}"
loop: "{{ lookup('dig', 'stackoverflow.com.').split(',') }}"
This gives the recap:
PLAY [all] *********************************************************************************************
TASK [package] *****************************************************************************************
changed: [localhost]
TASK [lineinfile] **************************************************************************************
changed: [localhost] => (item=151.101.1.69)
changed: [localhost] => (item=151.101.65.69)
changed: [localhost] => (item=151.101.129.69)
changed: [localhost] => (item=151.101.193.69)
PLAY RECAP *********************************************************************************************
localhost : ok=2 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
And populate the hosts file accordingly:
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.3 21eef8264e0c
151.101.1.69 ip-151-101-1-69
151.101.65.69 ip-151-101-65-69
151.101.129.69 ip-151-101-129-69
151.101.193.69 ip-151-101-193-69
ip-?