Skip to content

Config Costs for each AWS account | Boto3 script

  • by

AWS Config is a service that continuously monitors and records your AWS resource configurations and changes over time. It helps you:

  • πŸ“‹ Track configuration history: See how resources like EC2, S3, IAM roles, and security groups have changed.
  • βœ… Audit and compliance: Evaluate resource configurations against custom or managed rules to ensure compliance.
  • πŸ” Troubleshoot and analyze: Identify when and how changes occurred to support security investigations or operational debugging.

It’s especially useful for governance, risk management, and maintaining a clear view of your cloud environment. Cost for AWS config is based on the number of configuration items recorded and the frequency of evaluations. We may need to continuously monitor the config cost as the pricing varies by region and usage volume and it may increase the AWS Bill significantly!

Boto3 script to get list of Config costs for every account

The below boto3 script gets Config Cost for every account in the organization! Please make sure you have access to the Master account to execute the above script

import boto3
import csv
from datetime import datetime, timedelta

# Set time range to last full month (You can modify it to year)
end_date = datetime.today().replace(day=1)
start_date = (end_date - timedelta(days=1)).replace(day=1)
start_str = start_date.strftime('%Y-%m-%d')
end_str = end_date.strftime('%Y-%m-%d')

# Initialize Cost Explorer client
ce = boto3.client('ce', region_name='us-east-1')

# Query cost grouped by linked account, filtered by AWS Config
response = ce.get_cost_and_usage(
    TimePeriod={'Start': start_str, 'End': end_str},
    Granularity='MONTHLY',
    Metrics=['UnblendedCost'],
    Filter={
        'Dimensions': {
            'Key': 'SERVICE',
            'Values': ['AWS Config']
        }
    },
    GroupBy=[{'Type': 'DIMENSION', 'Key': 'LINKED_ACCOUNT'}]
)

# Extract results
results = response.get('ResultsByTime', [])
cost_data = []

if results:
    for group in results[0].get('Groups', []):
        account_id = group['Keys'][0]
        amount = group['Metrics']['UnblendedCost']['Amount']
        cost_data.append([account_id, start_str, end_str, amount])

# Write to CSV
with open('config_costs_by_account.csv', mode='w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['AccountId', 'StartDate', 'EndDate', 'AWSConfigCostUSD'])
    writer.writerows(cost_data)

print(f"βœ… Done! Cost data written to 'config_costs_by_account.csv'")

Boto3 script to get Config costs for a single account

Here is the boto3 script that gets config cost for a single account and writes the data to a csv file

import boto3
import csv
from datetime import datetime, timedelta

# Set the target linked account ID
target_account_id = "123456789012"  # Replace with your account ID

# Set time range to last full month
end_date = datetime.today().replace(day=1)
start_date = (end_date - timedelta(days=1)).replace(day=1)
start_str = start_date.strftime('%Y-%m-%d')
end_str = end_date.strftime('%Y-%m-%d')

# Initialize Cost Explorer client
ce = boto3.client('ce', region_name='us-east-1')

# Query cost for AWS Config filtered by account and service
response = ce.get_cost_and_usage(
    TimePeriod={'Start': start_str, 'End': end_str},
    Granularity='MONTHLY',
    Metrics=['UnblendedCost'],
    Filter={
        'And': [
            {
                'Dimensions': {
                    'Key': 'SERVICE',
                    'Values': ['AWS Config']
                }
            },
            {
                'Dimensions': {
                    'Key': 'LINKED_ACCOUNT',
                    'Values': [target_account_id]
                }
            }
        ]
    }
)

# Extract cost amount
amount = "0.00"
results = response.get('ResultsByTime', [])
if results and results[0]['Total']:
    amount = results[0]['Total']['UnblendedCost']['Amount']

# Write to CSV
with open('config_cost_single_account.csv', mode='w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['AccountId', 'StartDate', 'EndDate', 'AWSConfigCostUSD'])
    writer.writerow([target_account_id, start_str, end_str, amount])

print(f"βœ… AWS Config cost for account {target_account_id} from {start_str} to {end_str}: ${amount}")
print("πŸ“„ Data written to 'config_cost_single_account.csv'")

Leave a Reply

Your email address will not be published. Required fields are marked *