feat(hostname): manage hostnames and hosts

This commit is contained in:
transcaffeine 2020-12-24 10:43:27 +01:00
parent cf282336b2
commit 2a93b06d71
No known key found for this signature in database
GPG key ID: 03624C433676E465
4 changed files with 61 additions and 0 deletions

23
roles/hostname/README.md Normal file
View file

@ -0,0 +1,23 @@
# Hostname management role
This role manages all hostnames of the target server,
both `/etc/hostname` and additional hostnames in
`/etc/hosts`.
## Usage
At the bare minimum, you need to specify `hostname_fqdn`,
this is the primary hostname of the target, which ends up
in `/etc/hostname`.
You can specify additional hostnames for `/etc/hosts` in
`hostname_extra_hosts` in the form of `{ip, fqdn, alias[] }`,
following conventions usual for `/etc/hosts` (single IP,
FQDN first and aliases as plain hostnames).
## Gotchas
This role uses the `hostnamectl` command installed by
default on debian-like distros in order to ensure the
new hostname is immediately set without needing to reboot.

View file

@ -0,0 +1,4 @@
---
hostname_extra_hosts: []

View file

@ -0,0 +1,27 @@
---
- name: Set /etc/hostname to FQDN of the server
copy:
dest: /etc/hostname
owner: root
group: root
mode: 0644
content: |
{{ hostname_fqdn }}
- name: Ensure /etc/hosts contains all hostnames and aliases of the server
blockinfile:
dest: /etc/hosts
owner: root
group: root
mode: 0644
content: |
{% for host in hostname_hosts %}
{{ host.ip }} {{ host.fqdn }} {{ host.alias | default([]) | join(" ") }}
{% endfor %}
marker: "# {MARK} ANSIBLE MANAGED BLOCK"
- name: Set hostname via hostnamectl to avoid a reboot
command:
cmd: "hostnamectl set-hostname {{ hostname_fqdn }}"

View file

@ -0,0 +1,7 @@
---
hostname_localhost:
ip: 127.0.0.1
fqdn: "localhost.localdomain"
alias: [ "localhost" ]
hostname_hosts: "{{ [ hostname_localhost ] + hostname_extra_hosts }}"