From eaed2952a1a49ef75cbd53b2e0934d0a19b7ecd4 Mon Sep 17 00:00:00 2001
From: Lars Beckers <lars.beckers@rwth-aachen.de>
Date: Tue, 3 Jul 2018 01:39:11 +0200
Subject: [PATCH] basic-system: add management of /etc/hosts

---
 basic-system/defaults/main.yml  |  2 ++
 basic-system/handlers/main.yml  |  4 ++++
 basic-system/tasks/network.yml  | 16 ++++++++++++++++
 basic-system/templates/hosts.j2 | 20 ++++++++++++++++++++
 4 files changed, 42 insertions(+)
 create mode 100644 basic-system/templates/hosts.j2

diff --git a/basic-system/defaults/main.yml b/basic-system/defaults/main.yml
index 831b31e..4e43757 100644
--- a/basic-system/defaults/main.yml
+++ b/basic-system/defaults/main.yml
@@ -1,3 +1,5 @@
 ---
 
 dns_hostname_fqdn: False
+hosts_alternates: []
+hosts_additionals: []
diff --git a/basic-system/handlers/main.yml b/basic-system/handlers/main.yml
index a27692f..612fa5b 100644
--- a/basic-system/handlers/main.yml
+++ b/basic-system/handlers/main.yml
@@ -9,3 +9,7 @@
 
 - name: update initramfs
   command: update-initramfs -u
+
+- name: gather network facts once again
+  setup: gather_subset=network
+
diff --git a/basic-system/tasks/network.yml b/basic-system/tasks/network.yml
index 875e40f..c2c7814 100644
--- a/basic-system/tasks/network.yml
+++ b/basic-system/tasks/network.yml
@@ -17,6 +17,8 @@
 - name: ensure the hostname is not a fqdn
   hostname: name="{{ inventory_hostname }}"
   when: not dns_hostname_fqdn
+  notify:
+    - gather network facts once again
   tags:
     - dns
     - network
@@ -25,11 +27,25 @@
 - name: ensure the hostname is a fqdn
   hostname: name="{{ ansible_fqdn }}"
   when: dns_hostname_fqdn
+  notify:
+    - gather network facts once again
   tags:
     - dns
     - network
     - config
 
+- meta: flush_handlers
+
+- name: ensure correct hosts file
+  template:
+    src: hosts.j2
+    dest: /etc/hosts
+  notify:
+    - gather network facts once again
+  tags:
+    - dns
+    - network
+
 - name: ensure deactivation of tcp_timestamps
   sysctl: name=net.ipv4.tcp_timestamps value=0 state=present sysctl_set=yes
   tags: 
diff --git a/basic-system/templates/hosts.j2 b/basic-system/templates/hosts.j2
new file mode 100644
index 0000000..9301e37
--- /dev/null
+++ b/basic-system/templates/hosts.j2
@@ -0,0 +1,20 @@
+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
+ff02::3 ip6-allhosts
+
+{%- for host in hosts_alternates %}
+{{ host }}	{{ ansible_host }} {{ inventory_hostname }}
+{% else %}
+{{ ansible_default_ipv4.address }}	{{ ansible_host }} {{ inventory_hostname }}
+{%- if address in ansible_default_ipv6 %}
+{{ ansible_default_ipv6.address }}	{{ ansible_host }} {{ inventory_hostname }}
+{% endif -%}
+{% endfor -%}
+
+{%- for host in hosts_additionals %}
+{{ host.address }}	{{ host.names|join(' ') }}
+{% endfor -%}
-- 
GitLab