You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何生成包含指定内容的自定义EC2利用率报告?

Generating a Custom EC2 Utilization Report with Your Required Details

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:

  1. 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, and Region.
  2. 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.
  3. Combine the Two CSVs
    • Use a spreadsheet tool (like Excel or Google Sheets) to merge the files using Instance ID as the common key. You’ll now have all 5 fields in one unified report.

Method 2: AWS CLI (Command Line Automation)

If you prefer scripting or command-line work, use these commands to fetch and combine data:

  1. 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.json
    

    Note: Add --region us-east-1 (replace with your target region) if you need to focus on a specific area.

  2. 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.json
    
  3. Combine Data
    Use jq to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:54:06