This blog post is born out of user error. Whilst trying out some scripts and terraform code recently I created an SSH key pair in my personal AWS account via a cli command. Stupidly I didn’t pay attention to the output of the command beyond whether it was successful or not, and I didn’t take a copy of the private key that was generated. I then compounded the issue by continuing to create Linux based instances associated with the SSH Key Pair, meaning I would need the private key to be able to SSH into the instances. In the AWS console there is no method to retrieve the private key value or file name used during the key pair creation. Amazon has published an article describing how you can attempt to reset the key inside the instance by detaching its volume and adding it to another instance so you can edit the file system.
Luckily as part of the scripts I had run my SSH key pair was loaded into the AWS SSM for my account, meaning it should be possible to retrieve the value using the aws cli.
During creation the command used was aws ssm put-parameter suggesting that to retrieve the value the command should be aws ssm get-parameter. A quick google lead me to this issue logged on github. Following the command verbatim didn’t quite work for me. Although the value was extracted successfully my ssh client reported that it was an invalid format when I tried to use it.
The command that worked for me was:
aws --region=<aws region> ssm get-parameters --names "<name used with the put-parameter command>" --with-decryption --query "Parameters[*].{Value:Value}" --output text > aws_private_key
Credit to Adrian Nakon who wrote a blog post in 2018 that provided me with the query format to resolve my issue.
I now had a copy of the private key used within my AWS SSH key pair. A quick chmod 400 command to amend the permissions on the file and I was able to ssh into my AWS instance successfully.
Lesson learnt, pay more attention when running an automated process, you never know what information it is printing to the screen rather than saving to a file, and when you might need it!