Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

ansible control hosts entries

Somebody should make a module of this. In the meantime, here's a simple hosts entries task in ansible.

- name: hosts entries
  lineinfile:
    path: "{{ etc_hosts_file | default('/etc/hosts') }}"
    regexp: '^\s*{{ item.ip }}.*'
    line: "{{ item.ip }}   {{ item.hostnames | sort() | join(' ') }}"
    backup: yes
  with_items:
  - "{{ hosts_entries }}"

Use a list like so:

hosts_entries:
- { ip: '1.2.3.4', hostnames: ['example.com','www.example.com'] }
- { ip: '5.6.7.8', hostnames: ['ldap.example.com'] }

Comments