From d2bab25d638e7af177765a786bbf00cc8b2af19e Mon Sep 17 00:00:00 2001
From: Jesse Keating <omgjlk@us.ibm.com>
Date: Tue, 22 Aug 2017 13:48:27 -0700
Subject: [PATCH] Role to copy the build ssh key to other users

This role also sets up authorized_keys so that inter-node ssh works
between the hosts for alternative users.

This role will be useful for things like devstack, which require an
additional user be able to ssh around for things like nova's migrations.

The role can be called multiple times, with a different target user each
time. It is assumed that the user already exists.

Change-Id: I5972d66a48802fce0c1ebb885be00c5803ff0e9a
---
 roles/copy-build-sshkey/README.rst      | 17 +++++++++++++++++
 roles/copy-build-sshkey/tasks/main.yaml | 25 +++++++++++++++++++++++++
 roles/copy-build-sshkey/vars/main.yml   |  2 ++
 3 files changed, 44 insertions(+)
 create mode 100644 roles/copy-build-sshkey/README.rst
 create mode 100644 roles/copy-build-sshkey/tasks/main.yaml
 create mode 100644 roles/copy-build-sshkey/vars/main.yml

diff --git a/roles/copy-build-sshkey/README.rst b/roles/copy-build-sshkey/README.rst
new file mode 100644
index 000000000..05619727a
--- /dev/null
+++ b/roles/copy-build-sshkey/README.rst
@@ -0,0 +1,17 @@
+Copy a build-local SSH key to a defined user on all hosts
+
+This role is intended to be run on the Zuul Executor.  It copies a generated
+build specific ssh key to a user and adds it to the authorized_keys file of
+every host in the inventory.
+
+**Role Variables**
+
+.. zuul:rolevar:: zuul_temp_ssh_key
+   :default: "{{ zuul.executor.work_root }}/{{ zuul.build }}_id_rsa"
+
+   Where to source the build private key
+
+.. zuul:rolevar:: copy_sshkey_target_user
+   :default: root
+
+   The user to copy the sshkey to.
diff --git a/roles/copy-build-sshkey/tasks/main.yaml b/roles/copy-build-sshkey/tasks/main.yaml
new file mode 100644
index 000000000..227d3bccf
--- /dev/null
+++ b/roles/copy-build-sshkey/tasks/main.yaml
@@ -0,0 +1,25 @@
+---
+# Add the authorization first, to take advantage of manage_dir
+- name: Authorize build key
+  authorized_key:
+    user: "{{ copy_sshkey_target_user }}"
+    manage_dir: yes
+    key: "{{ lookup('file', zuul_temp_ssh_key ~ '.pub') }}"
+
+# Use a block to add become to a set of tasks
+- block:
+  - name: Install the build private key
+    copy:
+      src: "{{ zuul_temp_ssh_key }}"
+      dest: "~/.ssh/id_rsa"
+      mode: 0600
+      force: no
+
+  - name: Install the build public key
+    copy:
+      src: "{{ zuul_temp_ssh_key }}.pub"
+      dest: "~/.ssh/id_rsa.pub"
+      mode: 0644
+      force: no
+  become: true
+  become_user: "{{ copy_sshkey_target_user }}"
diff --git a/roles/copy-build-sshkey/vars/main.yml b/roles/copy-build-sshkey/vars/main.yml
new file mode 100644
index 000000000..2a4cb456d
--- /dev/null
+++ b/roles/copy-build-sshkey/vars/main.yml
@@ -0,0 +1,2 @@
+zuul_temp_ssh_key: "{{ zuul.executor.work_root }}/{{ zuul.build }}_id_rsa"
+copy_sshkey_target_user: root