Copying ansible keypair public key to existing AWS instances

Justin asked:

We have around 10 instances already running on AWS using my personal AWS keypair justin.pem.

I am setting up an Ansible box, and generated a new AWS keypair called ansible.pem. I copied ansible.pem to the Ansible instance into .ssh and have it ready to use.

The problem is how do I inject the ansible.pem public key into .ssh/authorized_keys on each of our existing AWS instances?

When we create new instances, I want to assign the justin.pem key pair, but this means that Ansible won’t be able to ssh into newly created instances as well.

What is the solution to this? Seems like a chicken and egg problem.

My answer:

Create new instances with the ansible.pem public key, and then use Ansible’s authorized_keys module to distribute any additional public keys you want to access your instance with, such as the corresponding public key for justin.pem.

- name: Install justin's ssh key
  authorized_key: user=ec2-user
                  key="{{lookup('file', '/home/justin/.ssh/')}}"

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.