Use ansible to insert into etc hosts file

Viewed 4797

I want to insert the following entry into the /etc/hosts file somehow using Ansible.

10.33.5.44 ip-10-33-5-44

Here, the schema is that the ip should have an alias corresponding to the IP, prefixed with ip- and where the dot . would be replaced by dash -.

But to get this IP, I can only think of doing the host command on a DNS name e.g.

host euwest2-test-box.company.com
> euwest2-test-box.company.com has address 10.33.5.44

Can anyone suggest how to get that to work? Is it possible?

1 Answers

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
Related