EC2 Deep Dive Basics
Seven short examples that go past "launch an instance" into the operations you actually run every day: describing, filtering, paginating, and tagging.
Busque em todas as páginas da documentação
Seven short examples that go past "launch an instance" into the operations you actually run every day: describing, filtering, paginating, and tagging.
Each example shows the same operation in both Python (boto3) and TypeScript (AWS SDK for JavaScript v3), so the mechanics translate one to one.
pip install boto3 (boto3 1.43.x, Python 3.10+). TypeScript: npm install @aws-sdk/client-ec2 (Node.js 18+).aws configure, environment variables, or an IAM role with ec2:Describe* and ec2:CreateTags.DescribeInstances groups instances under Reservations, so you almost always flatten it.
# --- Python (boto3) ---
import boto3
ec2 = boto3.client("ec2", region_name="us-east-1")
resp = ec2.describe_instances()
for reservation in resp["Reservations"]:
for inst in reservation["Instances"]:
print(inst["InstanceId"], inst["State"]["Name"])// --- TypeScript (AWS SDK v3) ---
import { EC2Client, DescribeInstancesCommand } from "@aws-sdk/client-ec2";
const ec2 = new EC2Client({ region: "us-east-1" });
const resp = await ec2.send(new DescribeInstancesCommand({}));
for (const r of resp.Reservations ?? []) {
for (const inst of r.Instances ?? []) {
console.log(inst.InstanceId, inst.State?.Name);
}
}Reservations[].Instances[], not a flat list.RunInstances call.Push the filter to AWS with Filters instead of downloading everything and filtering locally.
# --- Python (boto3) ---
import boto3
ec2 = boto3.client("ec2", region_name="us-east-1")
resp = ec2.describe_instances(
Filters=[{"Name": "instance-state-name", "Values": ["running"]}],
)// --- TypeScript (AWS SDK v3) ---
import { EC2Client, DescribeInstancesCommand } from "@aws-sdk/client-ec2";
const ec2 = new EC2Client({ region: "us-east-1" });
const resp = await ec2.send(new DescribeInstancesCommand({
Filters: [{ Name: "instance-state-name", Values: ["running"] }],
}));Values is a list, so ["running", "stopped"] matches either.instance-state-name.Select a subset of your fleet using the special tag:Key filter name.
# --- Python (boto3) ---
import boto3
ec2 = boto3.client("ec2", region_name="us-east-1")
resp = ec2.describe_instances(
Filters=[{"Name": "tag:Environment", "Values": ["production"]}],
)// --- TypeScript (AWS SDK v3) ---
import { EC2Client, DescribeInstancesCommand } from "@aws-sdk/client-ec2";
const ec2 = new EC2Client({ region: "us-east-1" });
const resp = await ec2.send(new DescribeInstancesCommand({
Filters: [{ Name: "tag:Environment", Values: ["production"] }],
}));tag:<Key> matches instances whose tag Key has one of the given values.tag-key to match on the presence of a key regardless of value.Environment and environment are different.Related: EC2 via SDK Best Practices - a consistent tagging scheme to filter against.
The instance object carries far more than an id; here are the fields you reach for most.
# --- Python (boto3) ---
inst = resp["Reservations"][0]["Instances"][0]
print(inst["InstanceType"]) # e.g. t3.micro
print(inst["PrivateIpAddress"])
print(inst.get("PublicIpAddress")) # may be absent
print(inst["Placement"]["AvailabilityZone"])// --- TypeScript (AWS SDK v3) ---
const inst = resp.Reservations?.[0].Instances?.[0];
console.log(inst?.InstanceType); // e.g. t3.micro
console.log(inst?.PrivateIpAddress);
console.log(inst?.PublicIpAddress); // may be undefined
console.log(inst?.Placement?.AvailabilityZone);PublicIpAddress is absent for instances without a public IP, so guard for it.Placement.AvailabilityZone tells you which AZ the instance runs in.Tags is a list of {Key, Value} objects, not a map, so convert it if you want lookups.LaunchTime is a timezone-aware timestamp useful for age-based cleanup.Beyond a page size, results are paged; use a paginator or a NextToken loop.
# --- Python (boto3) ---
import boto3
ec2 = boto3.client("ec2", region_name="us-east-1")
paginator = ec2.get_paginator("describe_instances")
for page in paginator.paginate():
for r in page["Reservations"]:
for inst in r["Instances"]:
print(inst["InstanceId"])// --- TypeScript (AWS SDK v3) ---
import { EC2Client, DescribeInstancesCommand } from "@aws-sdk/client-ec2";
const ec2 = new EC2Client({ region: "us-east-1" });
let token: string | undefined;
do {
const page = await ec2.send(new DescribeInstancesCommand({ NextToken: token }));
for (const r of page.Reservations ?? []) {
for (const inst of r.Instances ?? []) console.log(inst.InstanceId);
}
token = page.NextToken;
} while (token);paginateDescribeInstances if you want the same convenience.MaxResults ceiling.CreateTags attaches or overwrites tags on one or more resources.
# --- Python (boto3) ---
import boto3
ec2 = boto3.client("ec2", region_name="us-east-1")
ec2.create_tags(
Resources=["i-0abc123"],
Tags=[{"Key": "Environment", "Value": "production"},
{"Key": "Owner", "Value": "checkout-team"}],
)// --- TypeScript (AWS SDK v3) ---
import { EC2Client, CreateTagsCommand } from "@aws-sdk/client-ec2";
const ec2 = new EC2Client({ region: "us-east-1" });
await ec2.send(new CreateTagsCommand({
Resources: ["i-0abc123"],
Tags: [{ Key: "Environment", Value: "production" },
{ Key: "Owner", Value: "checkout-team" }],
}));CreateTags is idempotent per key: setting an existing key overwrites its value.Resources accepts many ids, so you can tag a batch in one call.TagSpecifications on RunInstances) so no instance is ever untagged.DeleteTags removes tags; omit Value to delete a key regardless of its value.
# --- Python (boto3) ---
import boto3
ec2 = boto3.client("ec2", region_name="us-east-1")
ec2.delete_tags(
Resources=["i-0abc123"],
Tags=[{"Key": "Owner"}], # no Value: delete regardless of value
)// --- TypeScript (AWS SDK v3) ---
import { EC2Client, DeleteTagsCommand } from "@aws-sdk/client-ec2";
const ec2 = new EC2Client({ region: "us-east-1" });
await ec2.send(new DeleteTagsCommand({
Resources: ["i-0abc123"],
Tags: [{ Key: "Owner" }], // no Value: delete regardless of value
}));Value deletes the key whatever its value; supplying Value deletes only if it matches.DeleteTags is safe on a key that does not exist - it simply does nothing.CreateTags, it accepts multiple resource ids at once.Stack versions: This page was written for boto3 1.43.x (Python 3.10+) and the AWS SDK for JavaScript v3 (Node.js 18+).
Revisado por Chris St. John·Última atualização: 23 de jul. de 2026