Skip to content

Instantly share code, notes, and snippets.

@thommyhh
Created November 17, 2020 11:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thommyhh/e868cf5884ef5e2e911beb965fce22de to your computer and use it in GitHub Desktop.
Save thommyhh/e868cf5884ef5e2e911beb965fce22de to your computer and use it in GitHub Desktop.
Ansible + passwordstore: Create and save SSH key pair
# Copy this file into to playbook or your role's tasks directory
# and include it with
# - name: Generate SSH key pair for root {your-user-name-here}
# include_tasks: ./ssh_key_pair.yaml
# vars:
# user: {your-user-name-here}
# type: {ssh-key-type} # defaults to `rsa`
#
# Arguments:
# - user: The user name you want to generate a key pair for (required)
# - type: The type of SSH key pair, e.g. rsa,dsa,ed25519, ... (defaults to 'rsa')
#
- name: "Find SSH key pair for user {{ user }}"
set_fact:
ssh_private_key: "{{ lookup('passwordstore', '{{ password_sub_folder + \"/\" if password_sub_folder is defined else \"\" }}{{ inventory_hostname }}/{{ user }}/ssh/key returnall=true', errors='ignore') }}"
ssh_public_key: "{{ lookup('passwordstore', '{{ password_sub_folder + \"/\" if password_sub_folder is defined else \"\" }}{{ inventory_hostname }}/{{ user }}/ssh/pub returnall=true', errors='ignore') }}"
tags:
- ssh_keys
- name: Do we need to generate a new key pair?
set_fact:
generate_key_pair: "{{ ssh_private_key | length == 0 or ssh_public_key | length() == 0 }}"
tags:
- ssh_keys
- name: Create new SSH key pair
local_action:
module: shell
cmd: "ssh-keygen -t {{ type | default('rsa') }} -q -N '' -f '/tmp/ssh-{{ inventory_hostname }}-{{ user }}' <<< y"
when: generate_key_pair
tags:
- ssh_keys
- name: Save SSH key pair to password store
local_action:
module: shell
cmd: |
cat '/tmp/ssh-{{ inventory_hostname }}-{{ user }}' | pass insert -mf '{{ password_sub_folder + "/" if password_sub_folder is defined else "" }}{{ inventory_hostname }}/{{ user }}/ssh/key'
cat '/tmp/ssh-{{ inventory_hostname }}-{{ user }}.pub' | pass insert -mf '{{ password_sub_folder + "/" if password_sub_folder is defined else "" }}{{ inventory_hostname }}/{{ user }}/ssh/pub'
when: generate_key_pair
tags:
- ssh_keys
- name: Remove generated SSH key pair
local_action:
module: file
path: "{{ item }}"
state: absent
loop:
- "/tmp/ssh-{{ inventory_hostname }}-{{ user }}"
- "/tmp/ssh-{{ inventory_hostname }}-{{ user }}.pub"
when: generate_key_pair
tags:
- ssh_keys
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment