Introduction
Amazon Web Services (AWS) provides a powerful command-line interface (CLI) that allows users to manage and automate cloud resources efficiently. One of the most common tasks is launching an Amazon Elastic Compute Cloud (EC2) instance. This guide outlines the step-by-step process to create an EC2 instance using AWS CLI.
Prerequisites
Before launching an EC2 instance, ensure the following prerequisites are met:
- AWS CLI Installed: Install the latest AWS CLI version from the AWS official website.
- AWS IAM User with Necessary Permissions: Ensure an IAM user with appropriate permissions is configured.
- AWS CLI Configured: Run aws configure to set up access credentials.
- Key Pair Created: Generate a key pair using aws ec2 create-key-pair –key-name MyKeyPair.
- Security Group Setup: Create a security group and open necessary ports using aws ec2 create-security-group.
Step-by-Step Guide to Launch an EC2 Instance
1. Choose an Amazon Machine Image (AMI)
To find a suitable AMI, use the following command:
aws ec2 describe-images –owners amazon –query ‘Images[*].[ImageId,Description]’
Select an AMI ID from the output, such as ami-12345678.
2. Select an Instance Type
To list available instance types, execute:
aws ec2 describe-instance-types –query ‘InstanceTypes[*].[InstanceType, VCpuInfo.DefaultVCpus, MemoryInfo.SizeInMiB]’
Choose a suitable instance type, e.g., t2.micro.
3. Create a Security Group
If not already created, a security group can be established with:
aws ec2 create-security-group –group-name MySecurityGroup –description “My security group”
Retrieve the security group ID with:
aws ec2 describe-security-groups –query ‘SecurityGroups[*].[GroupId,GroupName]’
4. Launch the EC2 Instance
Run the following command to create an EC2 instance:
aws ec2 run-instances \
–image-id ami-12345678 \
–instance-type t2.micro \
–key-name MyKeyPair \
–security-groups MySecurityGroup \
–count 1
5. Retrieve the Instance ID and Public IP Address
To get instance details, use:
aws ec2 describe-instances –query ‘Reservations[*].Instances[*].[InstanceId, PublicIpAddress]’
Take note of the public IP address to connect to the instance.
6. Connect to the EC2 Instance
Access the instance using SSH:
ssh -i MyKeyPair.pem ec2-user@public-ip-address
Replace public-ip-address with the actual IP obtained in the previous step.
Conclusion
By following these steps, an EC2 instance can be successfully launched using AWS CLI. Automating infrastructure deployment with CLI commands enhances efficiency and scalability.