Create EC2 using AWS CLI

Launching and Managing EC2 Instances

  1. From the network infrastructure created using CLI, we will create EC2. First, create an AWS Key pair:
aws ec2 create-key-pair --key-name MyKeyPair --query "KeyMaterial" --output text > MyKeyPair.pem

AWS CLI

  1. Check on the console, confirm the Key pair has been created successfully.

AWS CLI

  1. Set permissions for the Key pair file:
chmod 400 MyKeyPair.pem

AWS CLI

  1. Create a Security group for EC2:
aws ec2 create-security-group --group-name SSHAccess --description "Security group for SSH access" --vpc-id <VPC ID>

AWS CLI

  1. Check the newly created Security group.

AWS CLI

  1. Grant permission for SSH:
aws ec2 authorize-security-group-ingress --group-id <SG ID> --protocol tcp --port 22 --cidr 0.0.0.0/0

AWS CLI

  1. Launch EC2:

You can get the AMI ID by accessing EC2, selecting AMI Catalog. Here we will get the AMI ID of Amazon Linux 2023 kernel-6.1 AMI.

AWS CLI

aws ec2 run-instances --image-id <AMI ID> --count 1 --instance-type t2.micro --key-name MyKeyPair --security-group-ids <SG ID> --subnet-id <Subnet ID>

AWS CLI

  1. Wait about 2 minutes, check the status of the EC2 instance:
aws ec2 describe-instances --instance-id <Instance ID> --query "Reservations[*].Instances[*].{State:State.Name,Address:PublicIpAddress}"

AWS CLI

  1. When the instance is in running state, connect to it, remember to replace the IP of the newly created EC2 instance:
ssh -i "MyKeyPair.pem" ec2-user@<IP Public>

AWS CLI

  1. After completion, terminate the instance:
aws ec2 terminate-instances --instance-ids <Instance ID>

AWS CLI

  1. After 2-3 minutes, check the instance status again:
aws ec2 describe-instances --instance-id <Instance ID> --query "Reservations[*].Instances[*].State.Name"

AWS CLI

Note: Secure your key pair carefully and delete it when not in use.