DEV Community

Cover image for How to retrieve the private key file PEM content after Cloudformation or CDK Stack deployment
Kevin Lactio Kemta
Kevin Lactio Kemta

Posted on • Updated on

How to retrieve the private key file PEM content after Cloudformation or CDK Stack deployment

Day 002 of 100DaysAWSIaCDevopsChallenge

I recently worked on an insfractruture where I created an EC2 Instance with a keypair attached using CDK. After creating my instance, I wanted to connect to the instance using SSH. However, the problem I faced was that there was no way to store the private key generate by Cloudformation or CDK on my local machine during KeyPair creation.

Today, in the this article I'm going to show you how you can retrieve the private key content that was generated by Cloudformation or cdk during the stack deployment.
This task is fairly simple, because Amazon's documentation clearly explains where the private key content is stored, and you have the ability to retrieve it easily.

Prerequises

  • CDK
  • AWS CLI
  • Typescript

When you create a new key pair using AWS CloudFormation, the private key is saved to AWS Systems Manager Parameter Store service. The parameter name has the following format: ec2/keypair/{your_keypair_id}

Image description

Get the Key Pair ID

The key pair ID is the physical ID and there are many ways to get it.

Using CDK/Cloudformation output
const keypair = new ec2.CfnKeyPair(this, "MyKeyPair", {
    keyName: 'day2kp', // Remember this name for CLI option
    keyType: 'rsa', 
    keyFormat: 'pem'
});
// store in the output
new CfnOutput(this, "KeypairOutput", {
    key: "KeypairID",
    value: keypair.attrKeyPairId
});
Enter fullscreen mode Exit fullscreen mode

After running the deployment command cdk deploy --profile cdk-user, the KeypairOutput is displayed in the console like this:

Image description

Using AWS CLI

It is also possible to get the keypair ID using the command line (CLI). To do this:

aws ec2 describe-key-pairs --filters "Name=key-name,Values=day2kp" --query "KeyPairs[*].KeyPairId" --output json --profile cdk-user
Enter fullscreen mode Exit fullscreen mode

And the output

[
    "key-09da4060fcd68ec4f"
]
Enter fullscreen mode Exit fullscreen mode

Retrieve the Private Key Content

Now that we know our keypair ID, let's retrieve the content of the private key. We will store it in the file named prv-key.pem, the file is of type pem because the Keypair previously created had keyFormat=pem.

aws ssm get-parameter --name /ec2/keypair/key-09da4060fcd68ec4f --with-decryption --query Parameter.Value --output text --profile cdk-user > prv-key.pem
Enter fullscreen mode Exit fullscreen mode

And you can open your prv-key.pem.


Hope it can helps,
Thank you!

Top comments (0)