Automation using AWS CLI contd..
Activity 9: Create an ec2 instance
-
For creating ec2 instance we have following needs
- AMI id: They differ from region to region for the same OS (ubuntu 22.04)
- Network
- VPC (Region): AWS CLI by default uses default vpc to launch ec2 instance.
- Subnet id: For choosing specific AZ.
- Security Group: Solved as part of activity 8
- Key-Pair:
- Use the current machines id_rsa.pub (i.e. import)
- Create a new key pair and store it some where in your system.
- Size:
- EC2: this can be a parameter
- EBS: this can be a parameter
-
Solution:
- Lets try to figure how to get ami id
bash
aws ec2 describe-images --filters "Name=owner-id,Values=099720109477" "Name=name,Values=ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-20221201" --query "Images[0].ImageId" --region us-west-2 --output text
- Exercise: Try to find AMI id of Redhat Linux 9 which works for all regions
- Hint: use Name and owner id for fetching images uniquely
- Solution:
aws ec2 describe-images --filters "Name=name,Values=RHEL-9.1.0_HVM-20221101-x86_64-2-Hourly2-GP2" "Name=owner-id,Values=309956199498" --query "Images[0].ImageId" --output text
- Refer Here for the script written so far.
- Get the default vpc id:
aws ec2 describe-vpcs --query "Vpcs[?IsDefault].VpcId | [0]" --output text --region "${region}
- Get the subnet id of a specific az in subnet
aws ec2 describe-subnets --filters "Name=availability-zone, Values=${az}" "Name=vpc-id, Values=${vpc_id}" --query "Subnets[].SubnetId | [0]" --output text
- Get the security group id with name openall
sg_id=$(aws ec2 describe-security-groups --filters "Name=vpc-id,Values=${vpc_id}" --group-names "${group_name}" --query "SecurityGroups[].GroupId | [0]" --output text --region "${region}")
echo "Found security group in Vpc: ${vpc_id} with id ${sg_id} with name ${group_name}"
- Import the id_rsa.pub as key pair into your aws region.
- Lets create an ec2 instance in the specified region , in specified vpc/subnet with security group and key pair with instance size, disk size as parameter
- Refer Here for the script for creating.
Like this:
Like Loading...