1

How do you add an existing key to a live EC2 instance that has no key pair?

I have tried using Session Manager to vi /.ssh/authorized_keys and add in the public key of the pair, but I get this error:

"~/.ssh/authorized_keys"
"~/.ssh/authorized_keys" E212: Can't open file for writing

Is this something that has to be done using the console?

No associated key pair
This instance is not associated with a key pair. Without a key pair, you can't connect to the instance through SSH.
You can connect using EC2 Instance Connect with just a valid username. You can connect using Session Manager if you have been granted the necessary permissions.
inac
  • 519
  • 3
  • 10
  • 20
  • Does it have any ssh key installed? If you need to add additional SSH public key to destination .ssh/authorized_keys, I would just run ```ssh-copy-id -i /path/to/publicsshkey.pub $server ip``` There is also a way to add it through the AWS console: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html – Dmitriy Kupch Oct 21 '21 at 03:54
  • It doesn't seem to let me associate the key pair using the AWS console with EC2 instance. I have followed the directions for adding the authorized_keys using ssh using Session Manager (since it has no key pair) - but that does not let me shell in, and the console still indicates no key pair – inac Oct 21 '21 at 03:59
  • Here is what I mean: https://docs.aws.amazon.com/cli/latest/reference/ec2/import-key-pair.html#examples – Dmitriy Kupch Oct 21 '21 at 04:03

1 Answers1

0

Since you’ve got Systems Manager configured you’re half-way there. The only thing standing between you and success is the fact that Systems Manager Session opens the session as ssm-user and you’ll need to do sudo -u ec2-user -i first and once you're logged in as ec2-user do the subsequent steps.

Then you may have to create the ~ec2-user/.ssh directory if it doesn’t exist and chmod it to 700.

And finally you can add the public key to ~ec2-user/.ssh/authorized_keys and chmod that file to 600.

That should do the trick :)

MLu
  • 24,849
  • 5
  • 59
  • 86
  • That works temporarily - after the session or on restart/reboot, it seems it is wiped out maybe by some sort of AWS global daemon. – inac Oct 21 '21 at 22:03
  • If the key is in `~ec2-user/.ssh/authorized_keys` it will stay there. But it sounds like you put it to `~ssm-user/.ssh/…` - that home directory is wiped as soon as you log out from the SSM session. – MLu Oct 21 '21 at 22:07
  • ah, your directions did not indicate ~ec2-user/ being base directory... – inac Oct 21 '21 at 22:09
  • Yeah I said that you have to do `sudo -u ec2-user -i` first and once you're logged in as `ec2-user` do the subsequent steps. Sorry, should have been more explicit. I have updated the answer. – MLu Oct 21 '21 at 22:12