When using the AWS Cloud Development Kit (CDK) to build EC2 instances, it’s essential to create an SSH key pair to enable secure SSH access to the instances. In this post, we will explore how to generate an SSH key pair using AWS CLI and integrate the key pair into your CDK code.

Generating an SSH Key Pair:
To create an SSH key pair using the AWS CLI. Execute the following command:

aws ec2 create-key-pair --key-name <your_key_name> --query 'KeyMaterial' --output text > <anyfilename>.pem

Make a note of the key name you choose, and ensure that you have the .pem file generated in your working directory. We will use this file to establish an SSH connection to the EC2 instance.

Generating an SSH Key Pair:
Since new ssh pem file we just created is publicly readable, it is time to change permission so that only we can read it

chmod 400 <yourpemfilename>.pem

Adding the SSH Key Pair into CDK Code:
Now, let’s head over to your CDK code and add the key name as shown below:

const ec2Instance = new ec2.Instance(this, 'ec2-instance', {
  // ...
  keyName: '<your_key_name>',
  // ...
});

By specifying the keyName property with your chosen key name, you enable SSH access to the EC2 instance using the associated key pair.

Establishing an SSH Connection:
After deploying your CDK stack, you can connect to the EC2 instance via SSH using the following command:

ssh -i <.pem file name> <ec2Instance ssh url>

Replace <.pem file name> with the name of the .pem file generated earlier, and with the SSH URL or IP address of your EC2 instance. This command establishes a secure SSH connection, allowing you to access and manage your EC2 instance remotely.