如何生成包含指定内容的自定义EC2利用率报告?
Absolutely! You can build an EC2 report that includes all 5 details you mentioned. Below are three practical approaches tailored to different workflows:
Method 1: AWS Management Console (No Code Needed)
This is great if you prefer a visual interface:
- Pull EC2 Instance Details
- Navigate to the EC2 Console, go to the Instances page, and select all instances you want to include.
- Click Actions > Export list to download a CSV with columns like
Instance ID,Instance Name(from tags),State,Availability Zone, andRegion.
- Add Monthly Cost Data
- Switch to the Cost Explorer console.
- Set the date range to "Current Month" (adjust if needed for partial months).
- Use Filters to select "Service" = "Amazon Elastic Compute Cloud (EC2)" to narrow down to instance-related costs.
- Click Export > Export to CSV to get cost data grouped by Instance ID.
- Combine the Two CSVs
- Use a spreadsheet tool (like Excel or Google Sheets) to merge the files using
Instance IDas the common key. You’ll now have all 5 fields in one unified report.
- Use a spreadsheet tool (like Excel or Google Sheets) to merge the files using
Method 2: AWS CLI (Command Line Automation)
If you prefer scripting or command-line work, use these commands to fetch and combine data:
Get EC2 Instance Metadata
Run this command to export instance details to a JSON file:aws ec2 describe-instances --query 'Reservations[*].Instances[*].{Name: Tags[?Key==`Name`].Value | [0], State: State.Name, AZ: Placement.AvailabilityZone, Region: Placement.Region, InstanceId: InstanceId}' --output json > ec2_instances.jsonNote: Add
--region us-east-1(replace with your target region) if you need to focus on a specific area.Fetch Monthly EC2 Costs
Use the Cost Explorer API to get costs per instance for the current month:START_DATE=$(date +%Y-%m-01) END_DATE=$(date +%Y-%m-%d) aws ce get-cost-and-usage --time-period Start=$START_DATE,End=$END_DATE --granularity DAILY --metrics "BLENDED_COST" --group-by Type=DIMENSION,Key=INSTANCE_ID --filter '{"Dimensions": {"Key": "SERVICE", "Values": ["Amazon Elastic Compute Cloud - Compute"]}}' --output json > ec2_costs.jsonCombine Data
Usejqto parse and merge the two JSON files into a CSV report:jq -r ' ($costs | .ResultsByTime[].Groups[] | {InstanceId: .Keys[0], Cost: .Metrics.BLENDED_COST.Amount}) as $costData | $instances[] | . + ($costData | select(.InstanceId == .InstanceId)) | [.Name, .State, .AZ, .Region, .Cost] | @csv ' --argjson instances "$(cat ec2_instances.json)" --argjson costs "$(cat ec2_costs.json)" > ec2_report.csv
Method 3: Python (Boto3) Script (Fully Customizable)
For full control over the report format, write a Python script using the Boto3 SDK:
import boto3 from datetime import datetime # Initialize AWS clients ec2 = boto3.client('ec2') ce = boto3.client('ce') # Define current month date range today = datetime.today() start_date = f"{today.year}-{today.month:02d}-01" end_date = f"{today.year}-{today.month:02d}-{today.day:02d}" # Fetch EC2 instance details response = ec2.describe_instances() instances = [] for reservation in response['Reservations']: for instance in reservation['Instances']: # Extract instance name from tags (fallback to "Unnamed" if no tag exists) instance_name = next((tag['Value'] for tag in instance.get('Tags', []) if tag['Key'] == 'Name'), 'Unnamed') instances.append({ 'InstanceId': instance['InstanceId'], 'Name': instance_name, 'State': instance['State']['Name'], 'AZ': instance['Placement']['AvailabilityZone'], 'Region': instance['Placement']['Region'] if 'Region' in instance['Placement'] else boto3.Session().region_name }) # Fetch monthly cost data per instance cost_response = ce.get_cost_and_usage( TimePeriod={'Start': start_date, 'End': end_date}, Granularity='MONTHLY', Metrics=['BLENDED_COST'], GroupBy=[{'Type': 'DIMENSION', 'Key': 'INSTANCE_ID'}], Filter={'Dimensions': {'Key': 'SERVICE', 'Values': ['Amazon Elastic Compute Cloud - Compute']}} ) # Map instance IDs to their respective costs cost_map = {} for group in cost_response['ResultsByTime'][0]['Groups']: instance_id = group['Keys'][0] cost = group['Metrics']['BLENDED_COST']['Amount'] cost_map[instance_id] = cost # Generate and print the final report print("Instance Name,State,Availability Zone,Region,Current Month Cost") for instance in instances: cost = cost_map.get(instance['InstanceId'], '0.00') print(f"{instance['Name']},{instance['State']},{instance['AZ']},{instance['Region']},{cost}")
Save this as ec2_report.py, install Boto3 with pip install boto3, configure your AWS credentials, and run it to get a CSV-formatted report.
All three methods will deliver the exact report you need—pick the one that fits your workflow best!
内容的提问来源于stack exchange,提问作者Harsha Vardhan

