I am currently working on a cloud automation project and I need to extract a clean list of all my Amazon EC2 instance IDs along with their operational status (like running or stopped) using Python. I’ve started exploring the boto3 SDK but I'm getting lost in the nested dictionaries returned by the describe_instances method. Does anyone have a straightforward script or a snippet that simplifies this process for a beginner?
3 answers
To get a clean list of EC2 instance IDs and states, you should use the describe_instances() method from the boto3 client. This returns a response containing 'Reservations', and each reservation holds a list of 'Instances'. You need to iterate through both to access the data. A simple loop like for res in response['Reservations']: for ins in res['Instances']: print(ins['InstanceId'], ins['State']['Name']) works perfectly. It’s essential to handle the nested structure correctly to avoid KeyError exceptions. This approach is highly efficient for auditing your cloud environment.
That makes sense for a general list, but what if I only want to target instances that are currently in a 'running' state to save on processing time? Is there a way to filter the results directly within the API call rather than sorting through the entire dictionary in Python?
Using the boto3.resource('ec2') interface is often more "Pythonic" than the client. You can just do ec2.instances.all() and access .id and .state['Name'] directly on the objects.
I totally agree with David here. The resource interface in boto3 is way more intuitive for beginners because it treats AWS components as objects rather than just raw JSON responses from a client.
Hi Michael, you can definitely do that! You should use the 'Filters' parameter inside the describe_instances method. Set the Name to 'instance-state-name' and the Values to a list containing 'running'. This way, AWS only sends back the data for active servers, which is much better for performance and cleaner code.