Overview

Changing your SSH keys is as important as changing your underpants daily, running this script on a frequent basis will ensure access to the servers are changed on a regular basis. Use Ansible to do ssh key rotation in your sleep!

Test Bed

  • Ansible control server running Ubuntu 18.04 LTS
  • Test server running Ubuntu 18.04 LTS

Requirements

  1. Ansible control server
  2. SSH keys established between Ansible control server and destination server(s)
  3. A folder called “pubkeys” where the script is running from

Break Down

  1. Creates a new directory on the remote server to generate the new keys on
  2. Generates the new key pair in the newly formed folder
  3. Copies the new public key to the local machine running the ansible script under /pubkeys/ and names it “id_rsa.%hostname%.pub
  4. Removes existing private key
  5. Removes existing public key
  6. Moves new private key to the users .ssh folder
  7. Moves new public key to the users .ssh folder
  8. Changes new private key to read only
  9. Invalidates existing keys and applies the public key copied to the local host to the server
  10. Copies the new private key local host and changes the file to “id_rsa.%hostname%
  11. Removes “newsshkey” folder on remote host as a clean up

ssh_key_rotation.yml

Note: You will need to change/remove the “- hosts:” entry

Key Management

To fully automate this I have mounted a cifs share and created a symbolic link on the Ansible server from the ~/.ssh folder to the cifs share. All my other clients are set up the same way so when you update the key it copies the key to a central repository which all other clients are symbolically linked to.

Conclusion

This can be greatly be improved on but is a good starting point in the rotation of your ssh keys. I’m happy to hear suggestions on how this could be improved.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.