Okay, let's break down how to create an EC2 instance using the AWS CLI. I'll give you a comprehensive guide, covering the essential steps, options, and considerations.
Prerequisites:
- AWS Account: You need an active AWS account.
- AWS CLI Installed and Configured: Make sure you have the AWS CLI installed on your machine and configured with your AWS credentials (access key ID, secret access key, and default region). You can find instructions here: https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html and https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html
- IAM Role/User Permissions: The IAM user or role you're using needs permissions to launch EC2 instances (e.g.,
ec2:RunInstances, ec2:DescribeImages, ec2:DescribeKeyPairs, ec2:DescribeSecurityGroups, etc.).
- Key Pair: You'll need an EC2 key pair to SSH into the instance. If you don't have one, create it (see instructions below).
- Security Group: You'll need a security group that allows inbound traffic (e.g., SSH on port 22, HTTP on port 80, HTTPS on port 443) to your instance. If you don't have one, create it (see instructions below).
- AMI ID: You'll need the AMI (Amazon Machine Image) ID for the operating system you want to use. You can find AMI IDs in the AWS Management Console or using the AWS CLI.
1. Key Pair (If you don't have one)
aws ec2 create-key-pair --key-name my-key-pair --query 'KeyMaterial' --output text > my-key-pair.pem
chmod 400 my-key-pair.pem # Important: Restrict permissions on the private key file
my-key-pair: Replace with a name for your key pair.
my-key-pair.pem: This is the file where the private key will be saved. Keep this file secure! Never share it.
chmod 400: This command sets the file permissions so that only you can read the private key. This is crucial for security.
2. Security Group (If you don't have one)
aws ec2 create-security-group --group-name my-security-group --description "My Security Group"
This will output the GroupId. You'll need this in the next step.
Then, authorize inbound traffic (e.g., SSH):
aws ec2 authorize-security-group-ingress --group-id sg-xxxxxxxxxxxxxxxxx --protocol tcp --port 22 --cidr 0.0.0.0/0
sg-xxxxxxxxxxxxxxxxx: Replace with the actual GroupId from the previous command.
0.0.0.0/0: This allows SSH access from any IP address. For production environments, restrict this to your specific IP address or a trusted range. Consider using a bastion host for more secure access.
3. Launching the EC2 Instance
This is the main command. It's long, but we'll break it down.
aws ec2 run-instances \
--image-id ami-xxxxxxxxxxxxxxxxx \
--count 1 \
--instance-type t2.micro \
--key-name my-key-pair \
--security-group-ids sg-xxxxxxxxxxxxxxxxx \
--subnet-id subnet-xxxxxxxxxxxxxxxxx \
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=MyInstance}]'
Let's explain the options:
aws ec2 run-instances: The command to launch EC2 instances.
--image-id ami-xxxxxxxxxxxxxxxxx: The AMI ID. Replace this with the correct AMI ID for your desired operating system and region. You can find AMI IDs using the AWS Management Console or the aws ec2 describe-images command. (See "Finding AMI IDs" below).
--count 1: The number of instances to launch.
--instance-type t2.micro: The instance type. t2.micro is a good choice for testing and small workloads. Other options include t3.micro, t2.small, m5.large, etc. (See AWS documentation for available instance types).
--key-name my-key-pair: The name of the key pair you created earlier.
--security-group-ids sg-xxxxxxxxxxxxxxxxx: The ID of the security group you created earlier.
--subnet-id subnet-xxxxxxxxxxxxxxxxx: The ID of the subnet in which to launch the instance. You'll need to choose a subnet within a VPC. If you don't specify a subnet, AWS will launch the instance in your default VPC (if you have one) and a default subnet. You can find subnet IDs in the AWS Management Console or using the aws ec2 describe-subnets command.
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=MyInstance}]': Adds a tag to the instance. Tags are key-value pairs that help you organize and identify your resources. In this example, we're adding a tag with the key "Name" and the value "MyInstance". This will show up in the AWS Management Console.
Important: Replace all the placeholder values (ami-xxxxxxxxxxxxxxxxx, sg-xxxxxxxxxxxxxxxxx, subnet-xxxxxxxxxxxxxxxxx, my-key-pair, MyInstance) with your actual values.
4. Output and Instance ID
The run-instances command will output a JSON response containing information about the launched instance(s). The most important piece of information is the InstanceId. You'll need this to manage the instance later.
{
"Groups": [],
"Instances": [
{
"AmiLaunchIndex": 0,
"ImageId": "ami-xxxxxxxxxxxxxxxxx",
"InstanceId": "i-xxxxxxxxxxxxxxxxx",
"InstanceType": "t2.micro",
"KeyName": "my-key-pair",
"LaunchTime": "2023-10-27T14:30:00+00:00",
"Placement": {
"AvailabilityZone": "us-east-1a",
"GroupName": null,
"HostId": null,
"InstanceGroupId": null,
"Tenancy": "shared"
},
"PrivateDnsName": "ip-xxxxxxxxxxxxxxxxx.ec2.internal",
"PublicDnsName": "ec2-xxxxxxxxxxxxxxxxx.compute-1.amazonaws.com",
"State": {
"Code": 0,
"Name": "pending"
},
"VpcId": "vpc-xxxxxxxxxxxxxxxxx",
"SubnetId": "subnet-xxxxxxxxxxxxxxxxx"
}
],
"OwnerId": "123456789012",
"ReservationId": "r-xxxxxxxxxxxxxxxxx"
}
5. Getting the Public IP Address (After Instance is Running)
The instance will initially be in a "pending" state. It will take a few minutes to launch and reach the "running" state. Once it's running, you can get its public IP address using the following command:
aws ec2 describe-instances --instance-ids i-xxxxxxxxxxxxxxxxx --query 'Reservations[0].Instances[0].PublicIpAddress' --output text
i-xxxxxxxxxxxxxxxxx: Replace with the actual InstanceId from the previous step.
Finding AMI IDs
You can use the aws ec2 describe-images command to find AMI IDs. Here's an example to find the latest Amazon Linux 2 AMI in the us-east-1 region:
aws ec2 describe-images --owners amazon --filters "Name=name,Values=*Amazon Linux 2*" "Name=architecture,Values=x86_64" "Name=virtualization-type,Values=hvm" "Name=root-device-type,Values=ebs" --query 'Images[?SortBy(LaunchDate, "desc")].ImageId' --output text
This will output the AMI ID of the most recent Amazon Linux 2 AMI. You can adjust the filters to find other AMIs. You can also find AMI IDs in the AWS Management Console.
Important Considerations:
- Region: Make sure you're using the correct AWS region when running the CLI commands. You can set the default region using
aws configure.
- Cost: Be aware of the costs associated with running EC2 instances. Different instance types have different pricing. Monitor your AWS usage to avoid unexpected charges.
- Security: Always follow security best practices when configuring EC2 instances. Use strong passwords, restrict access to your instances, and keep your software up to date.
- IAM Roles: Consider using IAM roles instead of IAM users for granting permissions to EC2 instances. IAM roles are more secure and easier to manage.
- User Data: You can use the
--user-data option to pass a script to the instance that will be executed when it launches. This is useful for automating the installation of software and configuration of the instance.
This detailed guide should get you started with launching EC2 instances using the AWS CLI. Remember to replace the placeholder values with your actual values and to consult the AWS documentation for more information. Good luck!