如何用Boto3将运行中EC2实例信息转换为Pandas DataFrame表格
Complete Solution to Generate EC2 Running Instances DataFrame with Boto3
Let's get your code working smoothly—there are a couple of small tweaks needed, like fixing the iterator exhaustion issue and implementing the missing get_name_tag method. Here's the full, functional version:
import boto3 import pandas as pd # Initialize EC2 resource (or client, depending on your setup) ec2 = boto3.resource('ec2') def get_name_tag(instance): """Helper function to extract the 'Name' tag from an EC2 instance""" for tag in instance.tags or []: if tag['Key'] == 'Name': return tag['Value'] # Return a default if no Name tag exists return 'Unnamed Instance' # Get all running instances, store as a list to avoid iterator exhaustion running_instances = list(ec2.instances.filter( Filters=[{'Name': 'instance-state-name', 'Values': ['running']}] )) # Count instances (now we can use the list length) instance_count = len(running_instances) print(f"Total running EC2 instances: {instance_count}") # Build our list of instance data instance_data = [] for instance in running_instances: instance_info = { "name": get_name_tag(instance), "id": instance.id, "type": instance.instance_type, "launch_time": instance.launch_time.strftime('%Y-%m-%d %H:%M:%S'), # Add extra useful field "availability_zone": instance.placement['AvailabilityZone'] } instance_data.append(instance_info) # Convert to Pandas DataFrame ec2_df = pd.DataFrame(instance_data) # Optional: Display the DataFrame (for Jupyter/console) print(ec2_df)
Key Fixes & Improvements:
- Iterator Exhaustion Fix: Originally, you called
instances.all()twice—once for counting, once for looping. Sinceinstancesis an iterator, it gets emptied after the first use. By converting it to a list upfront (list(ec2.instances.filter(...))), we can reuse the data safely. get_name_tagImplementation: Added the missing helper function to pull the instance'sNametag (returns a default if no tag exists).- Extra Useful Fields: Added
launch_timeandavailability_zoneto make the table more informative—feel free to add/remove fields based on your needs (like private IP, security groups, etc.). - Cleaner Structure: Renamed variables to follow Python's snake_case convention for readability.
Once you run this, you'll get a nicely structured DataFrame with all your running EC2 instance details, ready for analysis, exporting to CSV, or further processing.
内容的提问来源于stack exchange,提问作者Ken J
相关产品推荐
相关产品推荐

