Write a Python script using boto3 that lists all running EC2 instances with their Name tag.
BeginnerHands-onPython for DevOps
Answer
import boto3
ec2 = boto3.client("ec2", region_name="ap-south-1")
paginator = ec2.get_paginator("describe_instances")
filters = [{"Name": "instance-state-name", "Values": ["running"]}]
for page in paginator.paginate(Filters=filters):
for res in page["Reservations"]:
for inst in res["Instances"]:
tags = {t["Key"]: t["Value"] for t in inst.get("Tags", [])}
print(inst["InstanceId"], inst["InstanceType"], tags.get("Name", "-"))
Key trick → Always use a paginator. A plain describe_instances returns only the first page in large accounts. Use inst.get("Tags", []) because untagged instances have no Tags key at all.
More on Python for DevOps
Write a script that finds unattached EBS volumes and deletes them (with a dry-run flag).IntermediateCall a REST API with `requests`, handle timeouts and non-2xx responses properly.BeginnerAdd retry with exponential backoff to HTTP calls without writing the loop yourself.IntermediateWrite your own retry decorator with exponential backoff and jitter.AdvancedParse a YAML file and print every container image in a multi-document Kubernetes manifest.IntermediateRun a shell command from Python, capture output, and fail properly on error.Intermediate