Sub topic 8
Launching an Instance with the AWS CLI
This chapter assumes you can use a Linux shell and SSH. It also assumes you have configured the AWS CLI with credentials for an account and Region, and that you know what CIDR blocks and ports are. By the end you will have launched an instance from the command line and know how to diagnose the usual launch failures.
What a launch needs
aws ec2 run-instances creates one or more instances. Each earlier choice in this tutorial becomes an input to this one call.
| Input | CLI option | Where it comes from |
|---|---|---|
| Software image | `--image-id` | An AMI available in the same Region |
| Hardware size | `--instance-type` | An instance type offered in the chosen Availability Zone |
| Network placement | `--subnet-id` | A subnet in a VPC, which fixes the Availability Zone |
| Firewall | `--security-group-ids` | A security group in the same VPC as the subnet |
| SSH login | `--key-name` | A key pair in the same Region |
Only the image ID is strictly required. If you omit the others, EC2 uses defaults such as the default VPC. Setting every input explicitly makes a launch repeatable and easier to review.
Step 1: Create the security group
A security group denies all inbound traffic until a rule allows it. This example creates a group and permits SSH only from one example range. Replace the VPC ID with your own, and in practice use your own public address range.
aws ec2 create-security-group \
--group-name web-sg \
--description "Web server access" \
--vpc-id vpc-0123456789abcdef0
aws ec2 authorize-security-group-ingress \
--group-id sg-0123456789abcdef0 \
--protocol tcp \
--port 22 \
--cidr 203.0.113.0/24The first command prints a GroupId. Use that value, not the placeholder above, in the next steps.
Step 2: Find an AMI
AMI IDs differ by Region and change as images are updated, so hard-coding one in a script goes stale. AWS publishes the current Amazon Linux 2023 image ID as a public Systems Manager (SSM) parameter. The launch command below reads that parameter first.
Step 3: Run the instance
AMI_ID=$(aws ssm get-parameter \
--name /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 \
--query Parameter.Value --output text)
aws ec2 run-instances \
--image-id "$AMI_ID" \
--instance-type t3.micro \
--key-name my-key \
--security-group-ids sg-0123456789abcdef0 \
--subnet-id subnet-0123456789abcdef0 \
--metadata-options HttpTokens=required \
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=tutorial-web}]'The command does the following:
AMI_ID=$(...)stores the latest image ID in a shell variable. The--queryand--output textoptions strip the JSON so only the ID remains.--instance-type t3.microselects a small burstable type. Check that it is available in your Region and in the subnet's Availability Zone.--key-name my-keynames an existing key pair. EC2 installs its public key on the instance for the default user,ec2-useron Amazon Linux.--metadata-options HttpTokens=requiredmakes the instance accept only IMDSv2 requests. A later chapter covers this service.--tag-specificationsapplies theNametag at creation time. Tagging at launch means the instance is never briefly untagged, which matters if cost reports or IAM policies depend on tags.
The response is JSON. Note the InstanceId field. The instance starts in the pending state and normally reaches running within a minute or so.
Waiting for the instance
Scripts should not guess how long a launch takes. Use a waiter, which polls until the state is reached:
aws ec2 wait instance-running --instance-ids i-0123456789abcdef0instance-running only means the instance has started. The operating system may still be booting, so SSH can fail for a short time after this returns. To wait for both status checks to pass, use aws ec2 wait instance-status-ok instead.
Step 4: Add user data and a role
Two options extend the launch command.
--user-datapasses a script that cloud-init runs once, at first boot. This script installs and starts nginx on Amazon Linux 2023:
#!/bin/bash
dnf install -y nginx
systemctl enable --now nginxSave it as userdata.sh and add --user-data file://userdata.sh to the command. The CLI encodes the file for you.
--iam-instance-profile Name=my-profileattaches an instance profile, which is the container that delivers an IAM role to the instance. The role must already exist. Its permissions then reach your code through the metadata service, so you never store access keys on the instance.
Nginx will not be reachable from a browser yet, because the security group allows only port 22. Add an inbound rule for port 80 to test it.
Step 5: Confirm and connect
List the instance by tag to see its state and public address:
aws ec2 describe-instances \
--filters Name=tag:Name,Values=tutorial-web \
--query 'Reservations[].Instances[].[InstanceId,State.Name,PublicIpAddress]' \
--output tablePublicIpAddress is empty if the subnet does not assign public IPv4 addresses. In that case the instance is reachable only from inside the VPC unless you attach an Elastic IP or launch with --associate-public-ip-address. Then connect:
ssh -i my-key.pem ec2-user@<public-ip>If SSH refuses the key because its permissions are too open, run chmod 400 my-key.pem.
Common launch errors
| Error code | Typical cause | Fix |
|---|---|---|
| `InvalidAMIID.NotFound` | The AMI belongs to another Region | Look up the ID in the Region you are using |
| `InvalidKeyPair.NotFound` | The key pair is in a different Region or misspelled | Check with `aws ec2 describe-key-pairs` |
| `InvalidParameter` mentioning groups | The security group is in a different VPC than the subnet | Use a group created in the subnet's VPC |
| `InsufficientInstanceCapacity` | The Availability Zone cannot supply that type right now | Retry later, or pick another subnet or type |
| `VcpuLimitExceeded` | The account's vCPU quota for that instance family is reached | Terminate unused instances or request a quota increase |
| `UnauthorizedOperation` | Your IAM identity lacks `ec2:RunInstances` or a related permission | Add the permission and retry |
Adding --dry-run to run-instances tests permissions and parameters without creating anything. A successful check returns a DryRunOperation error, which means the call would have worked.
Exercise
Your launch fails with InvalidParameter because the security group and subnet do not match. What is the likely cause, and how can you check it from the CLI?
Show answer
The security group was created in a different VPC from the subnet. Run aws ec2 describe-subnets --subnet-ids <id> --query 'Subnets[].VpcId' and aws ec2 describe-security-groups --group-ids <id> --query 'SecurityGroups[].VpcId', then compare the two VPC IDs. Use a security group from the subnet's VPC.
Exercise
A script runs aws ec2 wait instance-running and then immediately tries to SSH, but the connection is sometimes refused. Why, and what would be a better wait?
Show answer
running means EC2 started the instance, not that the operating system finished booting and started sshd. Use aws ec2 wait instance-status-ok, which waits until the instance and system status checks pass, or retry the SSH connection with a timeout.