This is an Ansible Role to add the static IP of a Samba server to the hosts file with the host name rather than using 127.0.1.1
Manual Process
Edit the host file and comment out the entry for 127.0.1.1 and replace with an entry using the actual static address for the host. This won't work if the host is assigned an address via DHCP.
Ansible Role: host-statichosts
The name should probably change. Originally it was also going to configure a static IP address and update DNS but it turned out that was much better done as part of VM build to that was split off into a new playbook and enhancement to another.
This was created for Building an additional Samba 4 Domain Controller 2
File Structure
This is a standard Ansible role with as single tasks .yaml file, a meta to keep Ansible happy and a README.md for my own notes.
host-statichosts
meta
main.yaml
tasks
main.yaml
README.md
tasks/main.yaml
--- # Ansible Role Tasks
# Role for preparing /etc/hosts samba-style
- name: Disable existing localhost entry
become: true
ansible.builtin.lineinfile:
path: /etc/hosts
regexp: '^(127\.0\.1\.1.*)'
line: '# \1'
backrefs: yes
- name: Add static IP with hostname
become: true
ansible.builtin.lineinfile:
path: /etc/hosts
search_string: '{{ network_address4 }}'
insertbefore: '# The following lines are desirable for IPv6 capable hosts'
line: '{{ network_address4 }} {{ inventory_hostname }} {{ inventory_hostname_short }}'
- name: Add blank line for style
become: true
ansible.builtin.lineinfile:
path: /etc/hosts
insertbefore: '# The following lines are desirable for IPv6 capable hosts'
line: ' '
...
AAAAll tasks operate against the /etc/hosts file and need to run as root.
The first task uses a regular expression to find the line that starts 127.0.1.1 and it remembers the entire line and replaces it with a # followed by the the entire line, effectively adding a # to the front of it so it comments it out.
The second task searches for the address network_address4 to update, or failing that adds it before the comment in the insertbefore: clause and then adds the address, fully-qualified and short hostname, e.g. 192.168.451.22 mydc1.example.com mydc1.
The thirst task adds a blank line just to keep the hosts file looking pretty.