create an ec2 instance with multiple key pairs

While creating an ec2 instance, we provide a key pair name.

But generally, I associate multiple ssh public/private keys with any remote server. I know that it's not possible to attach a key pair once the ec2 server has been created. So I would like to know whether it's possible or not to use multiple key pairs while creating an instance.


Solution 1:

Unfortunately, it's also not possible to import a key having two entries. Only the first entry is imported into the new key pair.

What you can do is:

Don't use the EC2 key pairs but instead use the user_data field to insert multiple SSH public keys in the /home/<user>/.ssh/authorized_keys file, where <user> is the standard user for your AMI (ubuntu, ec2_user etc.).

You can add user_data to every launching EC2 instance. Consider the following example:

#!/bin/bash
echo "ssh-rsa AAAA…" > /home/ubuntu/.ssh/authorized_keys
echo "ssh-rsa AAAA…" >> /home/ubuntu/.ssh/authorized_keys
chown ubuntu: /home/ubuntu/.ssh/authorized_keys
chmod 0600 /home/ubuntu/.ssh/authorized_keys

User data scripts run as root so you don't need to specify sudo.

That way, you could create personalized SSH access keys via tools like Terraform before managing the instances with Ansible or similar.

Note that you don't know what keys are being used by a simple look, though. You'd need access to the machine to check it.

Solution 2:

You can't... only way is to manually edit ~/.ssh/authorized_keys and add the public keys of the extra users you would like to give access. The disadvantage if this approach is that you'll have to re-do this operation over again, when your EC2 get's terminated. Not really convenient in a developer/testing environment... :(