Creating Key Pair using AWS CFN

Create key pairs - Amazon Elastic Compute Cloud

Objective

  • To create AWS Key Pair using Cloudformation. (Using the default profile)

Create a CloudFormation Template:

Start by creating a CloudFormation template in YAML format.**`AWS::EC2::KeyPair`** is defined with the name “wynhkeypair". You can change the **`KeyName`** property to your desired key pair name.
AWSTemplateFormatVersion: "2010-09-09"
Resources:
  wynhkeypair: #edit here 

    Type: AWS::EC2::KeyPair
    Properties:
      KeyName: wynhkeypair

Deploy the Template:

aws cloudformation create-stack --stack-name wynhkeypair --template-body file://keypair-wynh.yaml

Untitled

Untitled

Untitled

Describe the Key Pair:

Use the [describe-key-pairs](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-key-pairs.html) command as follows to get the ID of the key pair.
aws ec2 describe-key-pairs --filters Name=key-name,Values=wynhkeypair --query KeyPairs[*].KeyPairId --output text

output:

Untitled

key-0bcddbd87e48513eb

Retrieve the Key Pair:

Use the [get-parameter](https://docs.aws.amazon.com/cli/latest/reference/ssm/get-parameter.html) command as follows to get the parameter for your key and save the key material in a `.pem` file.
aws ssm get-parameter --name /ec2/keypair/key-0bcddbd87e48513eb --with-decryption --query Parameter.Value --output text > wynhkeypair.pem

Untitled

   Change permission of the key.
chmod 400 wynhkeypair.pem

By this way , we can create a keypair using Cloudformation.

If you want to delete the stack after testing, you can go through with the below steps:

aws cloudformation delete-stack --stack-name wynhkeypair

!wq