30 Jan 2018

Generate and exchange SSH keys among the servers using Ansible

4:47 PM Ubuntu/linux 0 Comment

In Ansible is quite easy add users, pubkeys and other stuff to any server. If the project or organization have multiple servers, ssh-keys are a swiss-knife, but they are kinda difficult to handle if you create/destroy multiple servers every week.

Without using Ansible (or any other config management), to add or revoke access you will need to login in all servers by hand (or by a script) and this is the time taking process to do in all servers.

With Ansible we can setup a playbook to do all these things.

Let’s see how to use this with small example playbook.yml:


– hosts: webservers
gather_facts: false
remote_user: root
tasks:
– name: generating SSH keys
command: ssh-keygen -t rsa -f /root/.ssh/id_rsa -N ”
args:
creates: /root/.ssh/id_rsa

– name: fetch all public ssh keys
shell: cat ~/.ssh/id_rsa.pub
register: ssh_keys
tags:
– ssh

– name: check keys
debug: msg=”{{ ssh_keys.stdout }}”
tags:
– ssh

– name: deploy keys on all servers
authorized_key: user=root key=”{{ item[0] }}”
delegate_to: “{{ item[1] }}”
with_nested:
– “{{ ssh_keys.stdout }}”
– “{{groups[‘webservers’]}}”
tags:
– ssh

 

 

Leave a Reply