Create AWS Infrastructure With AWS CDK

Hello, I am Akshay Phadke I have 10 Yrs of Experience in various Technologies. Currently, I am learning a few DevOps tools. I am working on Microsoft Technologies and AWS
Prerequisites
VS Code
TypeScript
AWS CDK & AWS CLI Installed
AWS User Profile Configuration on Machine
For Prerequisites installation refer my AWS CDK MasterClass Video
Agenda:
So our goal is to Create AWS Infrastructure using AWS CDK . Here , is the diagram which we will try to achieve

So here we will import default VPC , 2 Public Subnets with a Security Group and Will create a EC2 instance in public Subnet with some predefined user data Script .
Let's Start with first Creating a Project we will name this project as AWSInfra. We will Create this project in VSCode.
So in the Terminal under your Project folder we will create a new CDK Project
Commad will be
cdk init app --language=typescript

This will create a new blank CDK Project . This will install all the node packages in our Project folder

After the installation is done we will have a Project structure ready as

Now here we have 2 folders bin and lib . Bin folder is the main folder that's the entry point of our application ( in this we have App the main parent Structure and Inside App we have Stack). lib folder we we actual create resources . For more details how the hierarchies and how the Level of Constructs are there in AWS CDK refer the video Below
Now inside our bin folder we have a file call "aws_infra.ts" inside this we will uncomment the line environment settings line . This line is responsible for deploying resources in our account.

Now we will add Actual user data . So once our EC2 is booted we will get a default page. Name that file as user-data.sh. Save that file inside /lib folder

user-data.sh
#!/bin/bash
sudo su
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
echo "<h1> Hello World from $(hostname -f)</h1>" > /var/www/html/index.html
These are commands we will run where we will update the server and start,enable httpd and will display hello world.
Now lets create stack . First we will important the libraries for ec2 as

So we are going to ssh to our EC2 instance so we need a KeyPair to ssh. For this we need to install node dependencies to ssh to our instance . So open your terminal and run the command
npm i cdk-ec2-key-pair

So once you install the keypair package our package-lock.json will be updated our key pair package are installed in our project

Now lets create a key pair object in our stack
const key = new KeyPair(this,'KeyPair',{
name:'cdk-ec2-key-pair',
description: 'Key Pair for CDk deploy'
});
key.grantReadOnPrivateKey
In this we have create a new KeyPair imported the necessary libraries invoke the KeyPair construct, give a name and description and allow that key to read so give the permission as grantRead as we will be creating a Private key (.pem file)
Now lets try to import default VPC
//import default vpc
const vpc = ec2.Vpc.fromLookup(this,'default-vpc',{
isDefault: true
});
Here we are importing a default VPC and specifying Properties as isDefault as true
Now lets create a SG for EC2 instance
//create a SG for EC2 Instance
const webSG = new ec2.SecurityGroup(this,"webCDKSG",{
vpc,
allowAllOutbound: true
});
We are creating a new SG for EC2 instance so for this the properties are vpc which we had created earlier and allowAllOutbound specifying as True .And this SG is attached to our ec2 instance so specifying construct as new ec2.SecurityGroup
Now lets create a Ingress rule to allow inbound traffic from everywhere where we specify port as 80 and for SSH port 22
webSG.addIngressRule(ec2.Peer.anyIpv4(),
ec2.Port.tcp(80),
'Allow Traffic from Anywhere');
webSG.addIngressRule(ec2.Peer.anyIpv4(),
ec2.Port.tcp(22),
'Allow SSH');
This will allow Traffic to port 80 and for SSH where we can connect to our ec2 instance we have added Inbound rules for port 22
Now lets create a new EC2 instance
//Create a new EC2 instance
const ec2Instance = new ec2.Instance(this,'cdk-webserver-Instance',{
keyName: key.keyPairName,
vpc,
vpcSubnets:{
subnetType: ec2.SubnetType.PUBLIC,
},
securityGroup: webSG,
instanceType: ec2.InstanceType.of(
ec2.InstanceClass.BURSTABLE2,
ec2.InstanceSize.MICRO
),
machineImage: new ec2.AmazonLinuxImage({
generation: ec2.AmazonLinuxGeneration.AMAZON_LINUX_2
})
});
So for Launching a Instance from Console you Click on Launch Instance and the Give a Name , Select Image(Linux,Ubuntu), select Key Value Pair , Select Instance Type and Then select VPC and SG ( Or select Existing SG)
Similarly for this we will create a new instance so we'll invoke ec2 construct as "new ec2.Instance" will give a desired name in our case it is 'cdk-webserver-Instance'.
Now we have to associate the KeyPair to SSH so in properties we will assign KeyValue Pair to the EC2 Instance.
Will select the default VPC and for Subnets we will assign the Public subnet for our EC2 instance . Now for Security groups to allow Inbound and outbound traffic we will assign the previous variables " webSG " which we created .
Specify the instance Type and Instance Image in our case its Amazon Linux.
Now lets load user data and add that user data to ec2 instance
//load our user data
const userData = readFileSync('./lib/user-data.sh','utf-8');
//add user data to ec2 instance
ec2Instance.addUserData(userData);
Now we have to do connection part for our Infrasctructure
//connection
new CfnOutput(this,'public dns name',{value:ec2Instance.instancePublicDnsName});
new CfnOutput(this,'IP address',{value:ec2Instance.instancePublicIp});
new CfnOutput(this,'Key Pair',{value:key.keyPairName});
new CfnOutput(this, 'Download Key Command', { value: 'aws secretsmanager get-secret-value --secret-id ec2-ssh-key/cdk-keypair/private --query SecretString --output text > cdk-key.pem && chmod 400 cdk-key.pem' })
new CfnOutput(this, 'ssh command', { value: 'ssh -i cdk-key.pem -o IdentitiesOnly=yes ec2-user@' + ec2Instance.instancePublicIp })
First we will bootstrap our project and it will create an cdk.out folder in our project
cdk bootstrap

Now lets do fir command cdk synth to synthesize our project and check if any syntax or errors are there in files
cdk synth

If there are no errors we deploy our app the command is
cdk deploy
As new resources are created in your account it will take couple of minutes to deploy
If it asked " Do you want to deploy those changes" ? Y/N - > Press Y
Deployment is in Progress

After Deployment is completed lets check the public IP DNS name and browse our index page


You can browse from your Public Ip address also
Now lets check our Infra is been created
Our EC2 instance is been created

Also of SG is Created and Inbound and outbound rules are created



Now we will do ssh to our server. Now we have something called as DownloadKeyCommand which we will fire in ssh and which will generate pem file for us. Copy the command and press enter a private key file will get generated inside our folder


Now lets try to do ssh to our server by copying the ssh command as

This way you can connect to your EC2 Instance.
So we have covered how we can create Infrastructure as code using AWS CDK,
We have a complete playlist on our Youtube channel for AWS CDK . Do visit channel for more updates .
AWS CDK Playlist
Do Subscribe to the Channel there will be more Videos coming on AWS



