Skip to content

Instantly share code, notes, and snippets.

@rgm3
Last active April 18, 2018 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rgm3/acff8fbb9c507f5f3c99cb4af947c695 to your computer and use it in GitHub Desktop.
Save rgm3/acff8fbb9c507f5f3c99cb4af947c695 to your computer and use it in GitHub Desktop.
Ansible tasks to authorize mutual SSH for hosts in a group
# Example inventory
# [cluster]
# node1
# node2
# node3
# Assume all users exist on all nodes
- set_fact:
user_list:
- name: foo
home: /home/foo
- name: bar
home: /home/bar
- name: root
home: /root
- name: generate ssh keys
user:
name: "{{item.name}}"
generate_ssh_key: yes
ssh_key_comment: "{{item.name}}@{{inventory_hostname}} ansible-generated on {{ansible_date_time.iso8601}}"
with_items: "{{ user_list }}"
- name: register keys
shell: cat {{item.home}}/.ssh/id_rsa.pub
changed_when: false
register: pubkeys
with_items: "{{ user_list }}"
- name: authorize keys
authorized_key:
user: "{{item[0].name}}"
key: "{{ hostvars[item.1].pubkeys.results|selectattr('item', 'equalto', item.0)|map(attribute='stdout')|first }}"
with_nested:
- "{{ user_list }}"
- "{{ groups['cluster'] }}"
- name: known hosts
known_hosts:
path: "{{item[0]}}/.ssh/known_hosts"
name: "{{item[1]}}"
key: >
{{hostvars[item.1]['ansible_hostname']}},{{hostvars[item.1]['ansible_fqdn']}},{{hostvars[item.1]['ansible_all_ipv4_addresses']|join(',')}}
ecdsa-sha2-nistp256 {{ hostvars[item.1].ansible_ssh_host_key_ecdsa_public}}
with_nested:
- "{{ user_list|map(attribute='home')|list }}"
- "{{ groups['cluster'] }}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment