EC2 + Keypair creation
Create key pairs - Amazon Elastic Compute Cloud
AWS::EC2::Instance - AWS CloudFormation
Objective
- To create AWS KeyPair + EC2 using Cloudformation. (Using the default profile)
Create a CloudFormation Template:
Make a yaml file named ec2cfn.yaml. Added the below template.
AWSTemplateFormatVersion: "2010-09-09"
Description: CFN+EC2+KeyPair
Resources:
wynhkeypair:
Type: 'AWS::EC2::KeyPair'
Properties:
KeyName: wynhkeypair
Ec2Instance:
Type: 'AWS::EC2::Instance'
Properties:
InstanceType: 't2.micro'
AvailabilityZone: 'ap-southeast-1a'
ImageId: 'ami-002843b0a9e09324a'
KeyName: !Ref wynhkeypair
Run the code:
aws cloudformation create-stack --stack-name ec2nkeypair --template-body file://ec2cfn.yaml
Output:
The keypair(wynhkeypair) is attached.
Describe the key pair:
aws ec2 describe-key-pairs --filters Name=key-name,Values=wynhkeypair --query KeyPairs[*].KeyPairId --output text
output:
key-052c483ed5bb4bf0d
Generate the **.pem
file.**
aws ssm get-parameter --name /ec2/keypair/key-052c483ed5bb4bf0d --with-decryption --query Parameter.Value --output text > wynhpub.pem
Output:
change the permission of the **.pem**
key.
chmod 400 wynhpub.pem
Connecting the EC2 with created public key.
ssh -i wynhpub.pem ubuntu@13.212.216.237
After the testing, we can clean up the testing stacks by running the following command:
aws cloudformation delete-stack --stack-name ec2nkeypair
!wq