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.

All Real-World Interview questions Roadmap: Interview readiness

More on Python for DevOps