Amazon EC2 & VPC
Core patterns for launching, managing, and configuring EC2 instances and VPC resources.
Search across all documentation pages
Core patterns for launching, managing, and configuring EC2 instances and VPC resources.
Launch a new EC2 instance with a specified AMI, instance type, and options.
# --- Python (boto3) ---
import boto3
ec2 = boto3.client("ec2")
r = ec2.run_instances(
ImageId="ami-0c55b159cbfafe1f0",
InstanceType="t2.micro",
MinCount=1,
MaxCount=1,
KeyName="my-key-pair"
)
instance_id = r["Instances"][0]["InstanceId"]// --- TypeScript (AWS SDK v3) ---
import { EC2Client, RunInstancesCommand } from "@aws-sdk/client-ec2";
const ec2 = new EC2Client({});
const r = await ec2.send(new RunInstancesCommand({
ImageId: "ami-0c55b159cbfafe1f0",
InstanceType: "t2.micro",
MinCount: 1,
MaxCount: 1,
KeyName: "my-key-pair"
}));
const instanceId = r.Instances?.[0]?.InstanceId;List instances matching tag or state filters.
# --- Python (boto3) ---
import boto3
ec2 = boto3.client("ec2")
r = ec2.describe_instances(
Filters=[{"Name": "instance-state-name", "Values": ["running"]}]
)
ids = [i["InstanceId"] for res in r["Reservations"] for i in res["Instances"]]// --- TypeScript (AWS SDK v3) ---
import { EC2Client, DescribeInstancesCommand } from "@aws-sdk/client-ec2";
const ec2 = new EC2Client({});
const r = await ec2.send(new DescribeInstancesCommand({
Filters: [{ Name: "instance-state-name", Values: ["running"] }]
}));
const ids = r.Reservations?.flatMap(res => res.Instances?.map(i => i.InstanceId));Control the lifecycle of running instances.
# --- Python (boto3) ---
import boto3
ec2 = boto3.client("ec2")
ec2.start_instances(InstanceIds=["i-1234567890abcdef0"])
ec2.stop_instances(InstanceIds=["i-1234567890abcdef0"])
ec2.terminate_instances(InstanceIds=["i-1234567890abcdef0"])// --- TypeScript (AWS SDK v3) ---
import { EC2Client, StartInstancesCommand, StopInstancesCommand, TerminateInstancesCommand } from "@aws-sdk/client-ec2";
const ec2 = new EC2Client({});
await ec2.send(new StartInstancesCommand({ InstanceIds: ["i-1234567890abcdef0"] }));
await ec2.send(new StopInstancesCommand({ InstanceIds: ["i-1234567890abcdef0"] }));
await ec2.send(new TerminateInstancesCommand({ InstanceIds: ["i-1234567890abcdef0"] }));Poll an instance until it reaches the running state.
# --- Python (boto3) ---
import boto3
ec2 = boto3.client("ec2")
waiter = ec2.get_waiter("instance_running")
waiter.wait(InstanceIds=["i-1234567890abcdef0"])
print("Instance is running")// --- TypeScript (AWS SDK v3) ---
import { EC2Client, DescribeInstancesCommand, waitUntilInstanceRunning } from "@aws-sdk/client-ec2";
const ec2 = new EC2Client({});
await waitUntilInstanceRunning(
{ client: ec2, maxWaitTime: 300 },
{ InstanceIds: ["i-1234567890abcdef0"] }
);Attach metadata tags to instances, volumes, snapshots, and other resources.
# --- Python (boto3) ---
import boto3
ec2 = boto3.client("ec2")
ec2.create_tags(
Resources=["i-1234567890abcdef0"],
Tags=[{"Key": "Name", "Value": "my-instance"}, {"Key": "Env", "Value": "prod"}]
)// --- TypeScript (AWS SDK v3) ---
import { EC2Client, CreateTagsCommand } from "@aws-sdk/client-ec2";
const ec2 = new EC2Client({});
await ec2.send(new CreateTagsCommand({
Resources: ["i-1234567890abcdef0"],
Tags: [{ Key: "Name", Value: "my-instance" }, { Key: "Env", Value: "prod" }]
}));Query Systems Manager Parameter Store to retrieve the current recommended AMI ID.
# --- Python (boto3) ---
import boto3
ssm = boto3.client("ssm")
r = ssm.get_parameter(
Name="/aws/service/ami-amazon-linux-latest/amzn2/ami-hvm-x86_64-gp2"
)
ami_id = r["Parameter"]["Value"]// --- TypeScript (AWS SDK v3) ---
import { SSMClient, GetParameterCommand } from "@aws-sdk/client-ssm";
const ssm = new SSMClient({});
const r = await ssm.send(new GetParameterCommand({
Name: "/aws/service/ami-amazon-linux-latest/amzn2/ami-hvm-x86_64-gp2"
}));
const amiId = r.Parameter?.Value;Define a security group for managing inbound and outbound traffic rules.
# --- Python (boto3) ---
import boto3
ec2 = boto3.client("ec2")
r = ec2.create_security_group(
GroupName="my-sg",
Description="My security group",
VpcId="vpc-12345678"
)
sg_id = r["GroupId"]// --- TypeScript (AWS SDK v3) ---
import { EC2Client, CreateSecurityGroupCommand } from "@aws-sdk/client-ec2";
const ec2 = new EC2Client({});
const r = await ec2.send(new CreateSecurityGroupCommand({
GroupName: "my-sg",
Description: "My security group",
VpcId: "vpc-12345678"
}));
const sgId = r.GroupId;Add an inbound traffic rule to allow a protocol, port, and source.
# --- Python (boto3) ---
import boto3
ec2 = boto3.client("ec2")
ec2.authorize_security_group_ingress(
GroupId="sg-12345678",
IpPermissions=[{
"IpProtocol": "tcp",
"FromPort": 80,
"ToPort": 80,
"IpRanges": [{"CidrIp": "0.0.0.0/0"}]
}]
)// --- TypeScript (AWS SDK v3) ---
import { EC2Client, AuthorizeSecurityGroupIngressCommand } from "@aws-sdk/client-ec2";
const ec2 = new EC2Client({});
await ec2.send(new AuthorizeSecurityGroupIngressCommand({
GroupId: "sg-12345678",
IpPermissions: [{
IpProtocol: "tcp",
FromPort: 80,
ToPort: 80,
IpRanges: [{ CidrIp: "0.0.0.0/0" }]
}]
}));Generate or import an SSH key pair for instance access.
# --- Python (boto3) ---
import boto3
ec2 = boto3.client("ec2")
r = ec2.create_key_pair(KeyName="my-key-pair")
private_key = r["KeyMaterial"]
# Save to file: open("my-key-pair.pem", "w").write(private_key)// --- TypeScript (AWS SDK v3) ---
import { EC2Client, CreateKeyPairCommand } from "@aws-sdk/client-ec2";
const ec2 = new EC2Client({});
const r = await ec2.send(new CreateKeyPairCommand({ KeyName: "my-key-pair" }));
const privateKey = r.KeyMaterial;
// Save: fs.writeFileSync("my-key-pair.pem", privateKey);Set up a VPC and attach a subnet for instance deployment.
# --- Python (boto3) ---
import boto3
ec2 = boto3.client("ec2")
vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")
vpc_id = vpc["Vpc"]["VpcId"]
subnet = ec2.create_subnet(VpcId=vpc_id, CidrBlock="10.0.1.0/24")
subnet_id = subnet["Subnet"]["SubnetId"]// --- TypeScript (AWS SDK v3) ---
import { EC2Client, CreateVpcCommand, CreateSubnetCommand } from "@aws-sdk/client-ec2";
const ec2 = new EC2Client({});
const vpc = await ec2.send(new CreateVpcCommand({ CidrBlock: "10.0.0.0/16" }));
const vpcId = vpc.Vpc?.VpcId;
const subnet = await ec2.send(new CreateSubnetCommand({ VpcId: vpcId, CidrBlock: "10.0.1.0/24" }));
const subnetId = subnet.Subnet?.SubnetId;Create a static public IP and attach it to an instance.
# --- Python (boto3) ---
import boto3
ec2 = boto3.client("ec2")
eip = ec2.allocate_address(Domain="vpc")
alloc_id = eip["AllocationId"]
ec2.associate_address(InstanceId="i-1234567890abcdef0", AllocationId=alloc_id)// --- TypeScript (AWS SDK v3) ---
import { EC2Client, AllocateAddressCommand, AssociateAddressCommand } from "@aws-sdk/client-ec2";
const ec2 = new EC2Client({});
const eip = await ec2.send(new AllocateAddressCommand({ Domain: "vpc" }));
const allocId = eip.AllocationId;
await ec2.send(new AssociateAddressCommand({ InstanceId: "i-1234567890abcdef0", AllocationId: allocId }));Check the system and instance status checks for one or more instances.
# --- Python (boto3) ---
import boto3
ec2 = boto3.client("ec2")
r = ec2.describe_instance_status(InstanceIds=["i-1234567890abcdef0"])
for status in r["InstanceStatuses"]:
print(f"System: {status['SystemStatus']['Status']}, Instance: {status['InstanceStatus']['Status']}")// --- TypeScript (AWS SDK v3) ---
import { EC2Client, DescribeInstanceStatusCommand } from "@aws-sdk/client-ec2";
const ec2 = new EC2Client({});
const r = await ec2.send(new DescribeInstanceStatusCommand({ InstanceIds: ["i-1234567890abcdef0"] }));
r.InstanceStatuses?.forEach(status => {
console.log(`System: ${status.SystemStatus?.Status}, Instance: ${status.InstanceStatus?.Status}`);
});Change instance properties such as security groups or monitoring settings.
# --- Python (boto3) ---
import boto3
ec2 = boto3.client("ec2")
ec2.modify_instance_attribute(
InstanceId="i-1234567890abcdef0",
Groups=["sg-12345678", "sg-87654321"]
)// --- TypeScript (AWS SDK v3) ---
import { EC2Client, ModifyInstanceAttributeCommand } from "@aws-sdk/client-ec2";
const ec2 = new EC2Client({});
await ec2.send(new ModifyInstanceAttributeCommand({
InstanceId: "i-1234567890abcdef0",
Groups: ["sg-12345678", "sg-87654321"]
}));Provision a new block storage volume and create a point-in-time snapshot.
# --- Python (boto3) ---
import boto3
ec2 = boto3.client("ec2")
vol = ec2.create_volume(AvailabilityZone="us-east-1a", Size=100)
vol_id = vol["VolumeId"]
snap = ec2.create_snapshot(VolumeId=vol_id, Description="My snapshot")
snap_id = snap["SnapshotId"]// --- TypeScript (AWS SDK v3) ---
import { EC2Client, CreateVolumeCommand, CreateSnapshotCommand } from "@aws-sdk/client-ec2";
const ec2 = new EC2Client({});
const vol = await ec2.send(new CreateVolumeCommand({ AvailabilityZone: "us-east-1a", Size: 100 }));
const volId = vol.VolumeId;
const snap = await ec2.send(new CreateSnapshotCommand({ VolumeId: volId, Description: "My snapshot" }));
const snapId = snap.SnapshotId;Retrieve instance metadata (instance ID, region, security groups) from within the instance.
# --- Python (boto3) ---
import requests
# Get IMDSv2 token
token = requests.put(
"http://169.254.169.254/latest/api/token",
headers={"X-aws-ec2-metadata-token-ttl-seconds": "21600"}
).text
# Fetch metadata
instance_id = requests.get(
"http://169.254.169.254/latest/meta-data/instance-id",
headers={"X-aws-ec2-metadata-token": token}
).text// --- TypeScript (AWS SDK v3) ---
import http from "http";
// Get IMDSv2 token
const token = await new Promise((resolve) => {
const req = http.request("http://169.254.169.254/latest/api/token",
{ method: "PUT", headers: { "X-aws-ec2-metadata-token-ttl-seconds": "21600" } },
res => res.on("data", d => resolve(d.toString()))
);
req.end();
});
// Fetch metadata
const instanceId = await new Promise((resolve) => {
const req = http.get("http://169.254.169.254/latest/meta-data/instance-id",
{ headers: { "X-aws-ec2-metadata-token": token } },
res => res.on("data", d => resolve(d.toString()))
);
req.end();
});Stack versions: This page was written for boto3 1.43.x (Python 3.10+) and the AWS SDK for JavaScript v3 (Node.js 18+).
Reviewed by Chris St. John·Last updated Jul 23, 2026