Deploy ssh key as root for non-root users

The role to distribute the build ssh key to a user uses the "copy"
module in combination with become_user. When the target user is not
root, this does not work because the ansible user is not root
either and "copy" is not compatible with pipelining:
http://docs.ansible.com/ansible/latest/user_guide/become.html#becoming-an-unprivileged-user

To solve the issue run the copy as root and set the owner of the
target file. Use the "user" module to resolve "~" to the target user
home directory.

Change-Id: Ic66eb2b14bc55a412dfa73aa0722cd59887a4e83
This commit is contained in:
Andrea Frittoli 2018-04-23 12:39:39 +01:00
parent df364a46e0
commit 4ea02ec487

View File

@ -1,25 +1,36 @@
---
# 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') }}"
become: true
become_user: "{{ copy_sshkey_target_user }}"
# Use a block to add become to a set of tasks
- block:
# 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') }}"
- name: Get the {{ copy_sshkey_target_user }} user home folder
user:
name: "{{ copy_sshkey_target_user }}"
register: target_user_registered
# The copy module does not work with become_user even if pipelining is
# enabled when both ansible user and become_user are not root:
# http://docs.ansible.com/ansible/latest/user_guide/become.html#becoming-an-unprivileged-user
- name: Install the build private key
copy:
src: "{{ zuul_temp_ssh_key }}"
dest: "~/.ssh/id_rsa"
dest: "{{ target_user_registered.home }}/.ssh/id_rsa"
mode: 0600
owner: "{{ copy_sshkey_target_user }}"
force: no
- name: Install the build public key
copy:
src: "{{ zuul_temp_ssh_key }}.pub"
dest: "~/.ssh/id_rsa.pub"
dest: "{{ target_user_registered.home }}/.ssh/id_rsa.pub"
mode: 0644
owner: "{{ copy_sshkey_target_user }}"
force: no
become: true
become_user: "{{ copy_sshkey_target_user }}"