I'm working on a Python script to audit our cloud infrastructure and I need a way to list all AWS EC2 instances. I have tried using the standard describe_instances method but I am struggling with how to handle pagination and looping through different regions. Does anyone have a clean snippet that uses Boto3 to pull the instance ID, state, and type for everything in my account? I want to make sure I don't miss any instances that might be running in regions I don't normally use.
3 answers
To list all EC2 instances across all regions, you first need to fetch a list of all available regions using the describe_regions method from the EC2 client. Once you have the region names, you can iterate through them and create a new Boto3 resource or client for each specific region. Using ec2.instances.all() is often simpler than the client-side describe_instances because the resource interface handles the underlying pagination for you automatically. Just ensure your IAM role has the ec2:DescribeInstances and ec2:DescribeRegions permissions to avoid any 403 errors.
That is a great approach for a full audit, but have you considered how you'll handle the output format if you have hundreds of instances? Are you planning to export this data to a CSV or just print it to the console for a quick check?
You can use boto3.resource('ec2').instances.all() to get a collection. It's much more Pythonic than the low-level client.
I agree with this! Using the resource interface is definitely the way to go for simple listing tasks as it returns objects you can interact with directly.
I actually suggest using the Python csv module alongside your Boto3 loop. You can initialize a writer before the region loop and append rows for each instance found. This makes the audit much more professional and easier to share with stakeholders. I've found that including the "Name" tag specifically is helpful since IDs are hard to track.