Skip to content

Instantly share code, notes, and snippets.

@atheiman
Last active December 4, 2024 01:19
Show Gist options
  • Save atheiman/9830de25a3fb54a06b86953a2675bbd1 to your computer and use it in GitHub Desktop.
Save atheiman/9830de25a3fb54a06b86953a2675bbd1 to your computer and use it in GitHub Desktop.
Example of querying AWS Config aggregator using Python and boto3
#!/usr/bin/env python3
# Example usage:
#
# ~ $ export AWS_PROFILE=organization-management-account
# ~ $ export AGGREGATOR_NAME=my-config-aggregator
# ~ $ python ~/tmp/config_aggregator_query.py
# 53 resources inspected
#
import os
import json
import boto3
config = boto3.client("config")
resource_type = "AWS::EC2::Instance"
# Load aggregator name from environment variable. Or, if only one aggregator exists in the current
# region, use that aggregator by default
aggregator_name = os.environ.get('AGGREGATOR_NAME', '')
if not aggregator_name:
aggregators = config.describe_configuration_aggregators()["ConfigurationAggregators"]
if len(aggregators) != 1:
raise Exception(
"ERROR - specify Config aggregator name using environment variable 'AGGREGATOR_NAME'. List available"
" aggregators with aws-cli: aws configservice describe-configuration-aggregators"
)
aggregator_name = aggregators[0]['ConfigurationAggregatorName']
resource_count = 0
for pg in config.get_paginator("list_aggregate_discovered_resources").paginate(
ConfigurationAggregatorName=aggregator_name,
ResourceType=resource_type,
PaginationConfig={
#'MaxItems': 500,
'PageSize': 100, # batch_get_aggregate_resource_config only accepts batches of up to 100 resource identifiers
}
):
res = config.batch_get_aggregate_resource_config(
ConfigurationAggregatorName=aggregator_name,
ResourceIdentifiers=pg["ResourceIdentifiers"],
)
if res["UnprocessedResourceIdentifiers"]:
print(res["UnprocessedResourceIdentifiers"])
# Not exactly sure what issue this would indicate. Raise an exception if we run into it just to be safe.
raise Exception("ERROR - config.batch_get_aggregate_resource_config() response includes 'UnprocessedResourceIdentifiers'")
for resource in res["BaseConfigurationItems"]:
resource_count += 1
# Parse the resource configuration json
resource['configuration'] = json.loads(resource["configuration"])
# Print resource config record
print(resource["arn"])
#print(json.dumps(resource, indent=2, default=str))
# THIS SECTION CAN BE UPDATED TO DO SOMETHING WITH THE RESOURCE
# if resource["configuration"]["state"]["name"] == "running":
# do_something_with_running_instance(resource)
print(f"{resource_count} resources inspected")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment