In this post I will demonstrate how you can use ansible to automate the task of adding one or more ssh public keys to multiple servers authorized_keys file.
This will be focused in a scenario where you have 5 new ssh keys that we would want to copy to our bastion hosts authorized_keys file
The User Accounts
We have our bastion server named bastion.mydomain.com
where would like to create the following accounts: john, bob, sarah, sam, adam
and also upload their personal ssh public keys to those accounts so that they can logon with their ssh private keys.
On my local directory, I have their ssh public keys as:
1 2 3 4 5 |
|
They will be referenced in our playbook as key: ".pub') }}"
but if they were on github we can reference them as key: https://github.com/.keys
, more info on that can be found on the authorized_key_module documentation.
The Target Server
Our inventory for the target server only includes one host, but we can add as many as we want, but our inventory will look like this:
1 2 3 4 5 |
|
Test if the target server is reachable using the user ubuntu
using our admin accounts ssh key ansible.pem
:
1 2 3 4 5 |
|
Our Playbook
In this playbook, we will reference the users that we want to create and it will loop through those users, creating them on the target server and also use those names to match to the files on our laptop to match the ssh public keys:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
|
Deploy
Run the playbook:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
Now when we ask one of the users, adam for example, to authenticate with:
1
|
|
They should have access to the server.
Thank You
Thanks for reading, for more information on this module check out their documentation: