From 974b5d7dac51b8046b6422724e0d428c7c339153 Mon Sep 17 00:00:00 2001
From: David Moreau-Simard <dms@redhat.com>
Date: Fri, 15 Sep 2017 22:38:12 -0600
Subject: [PATCH] Multi-node: Set up hosts file

This allows nodes in a multi-node job to resolve each other through
their inventory hostname.

Change-Id: I19cc7690d6fea99461bc67a46a09a8037f9c3292
---
 playbooks/multinode/pre.yaml                | 17 ++++++++++++++---
 roles/multi-node-hosts-file/README.rst      |  2 ++
 roles/multi-node-hosts-file/tasks/main.yaml | 17 +++++++++++++++++
 3 files changed, 33 insertions(+), 3 deletions(-)
 create mode 100644 roles/multi-node-hosts-file/README.rst
 create mode 100644 roles/multi-node-hosts-file/tasks/main.yaml

diff --git a/playbooks/multinode/pre.yaml b/playbooks/multinode/pre.yaml
index 903c4c804..76c796815 100644
--- a/playbooks/multinode/pre.yaml
+++ b/playbooks/multinode/pre.yaml
@@ -1,3 +1,14 @@
-- hosts: all
-  roles:
-    - multi-node-known-hosts
+- name: Configure a multi node environment
+  hosts: all
+  tasks:
+    # TODO: Add groups['all'] | length > 1 conditional when the truncated JSON
+    # issue is resolved, see:
+    # - https://github.com/ansible/ansible/issues/30385
+    # - https://review.openstack.org/#/c/504238/
+    - name: Set up multi-node known hosts
+      include_role:
+        name: multi-node-known-hosts
+
+    - name: Set up multi-node hosts file
+      include_role:
+        name: multi-node-hosts-file
diff --git a/roles/multi-node-hosts-file/README.rst b/roles/multi-node-hosts-file/README.rst
new file mode 100644
index 000000000..26a5d7fc2
--- /dev/null
+++ b/roles/multi-node-hosts-file/README.rst
@@ -0,0 +1,2 @@
+Configures the inventory hostnames in a multi-node job resolve to their
+respective private ipv4 addresses through the /etc/hosts file on each node.
diff --git a/roles/multi-node-hosts-file/tasks/main.yaml b/roles/multi-node-hosts-file/tasks/main.yaml
new file mode 100644
index 000000000..dc05a9537
--- /dev/null
+++ b/roles/multi-node-hosts-file/tasks/main.yaml
@@ -0,0 +1,17 @@
+- name: Set up the list of hosts and addresses
+  set_fact:
+    host_addresses: >
+      {% set hosts = {} -%}
+      {% for host, vars in hostvars.items() -%}
+      {% set _ = hosts.update({host: vars['nodepool']['private_ipv4']}) -%}
+      {% endfor -%}
+      {{- hosts -}}
+
+- name: Add inventory hostnames to the hosts file
+  become: yes
+  lineinfile:
+    dest: /etc/hosts
+    state: present
+    insertafter: EOF
+    line: "{{ item.value }} {{ item.key }}"
+  with_dict: "{{ host_addresses }}"