Skip to content

Instantly share code, notes, and snippets.

@pabloariasmora
Created March 17, 2025 18:03
Show Gist options
  • Save pabloariasmora/a6260292457cbe1fb749d489cab8a6e3 to your computer and use it in GitHub Desktop.
Save pabloariasmora/a6260292457cbe1fb749d489cab8a6e3 to your computer and use it in GitHub Desktop.
A Python utility script to scan and inventory AWS resources across all regions based on specific tag patterns. This tool helps in resource management and compliance tracking by identifying all resources with matching tags in your AWS account.

AWS Resource Tag Scanner

A Python script that scans AWS resources across all regions for specific tag patterns and provides a detailed inventory of tagged resources.

Description

This tool helps AWS administrators and developers to:

  • Search for resources with specific tag patterns across all AWS regions
  • List all found resources with their ARNs
  • Provide a total count of resources matching the tag pattern
  • Support for all AWS resource types that allow tagging

Prerequisites

  • Python 3.6 or higher
  • AWS CLI configured with appropriate credentials
  • Required Python packages:
    • boto3
    • botocore

Required AWS Permissions

The AWS user/role running this script needs the following permissions:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "tag:GetResources",
                "resource-groups:SearchResources",
                "ec2:DescribeRegions"
            ],
            "Resource": "*"
        }
    ]
}

Installation

  1. Install required packages:
pip install boto3 botocore
  1. Configure AWS credentials:
aws configure

Usage

  1. Run the script:
python aws_resource_tag_scanner.py
  1. When prompted, enter the tag pattern you want to search for (e.g., 'Environment', 'Project', etc.)

  2. The script will:

    • Search through all AWS regions
    • List all resources with matching tags
    • Display a total count at the end

Example output:

Enter the tag pattern to search for (e.g., 'Environment'): Project

Searching in region: us-east-1
Searching in region: us-west-2
...

Resources found:
- arn:aws:ec2:us-east-1:123456789012:instance/i-1234567890abcdef0
- arn:aws:s3:::my-bucket
...

Total resources found: 42

Features

  • Cross-region resource scanning
  • Support for all taggable AWS resources
  • Paginated results handling
  • Error handling for API calls
  • User-friendly output format

Limitations

  • The script requires appropriate AWS permissions to scan resources
  • Scanning all regions may take some time depending on the number of resources
  • API rate limiting may affect large-scale scans

Error Handling

The script includes error handling for common issues:

  • Invalid AWS credentials
  • Insufficient permissions
  • API throttling
  • Network connectivity issues
import boto3
import re
from botocore.exceptions import ClientError
def get_all_regions():
ec2_client = boto3.client('ec2')
regions = [region['RegionName'] for region in ec2_client.describe_regions()['Regions']]
return regions
def get_resources_with_tag_pattern(tag_pattern):
resource_groups = boto3.client('resource-groups')
resources = []
try:
paginator = resource_groups.get_paginator('search_resources')
for page in paginator.paginate(
ResourceQuery={
'Type': 'TAG_FILTERS_1_0',
'Query': f'{{\"ResourceTypeFilters\":[\"AWS::AllSupported\"],\"TagFilters\":[{{\"Key\":\"{tag_pattern}\",\"Values\":[\"*\"]}}]}}'
}
):
resources.extend(page['ResourceIdentifiers'])
except ClientError as e:
print(f"Error searching for resources: {e}")
return resources
def main():
tag_pattern = input("Enter the tag pattern to search for (e.g., 'Environment'): ")
all_resources = []
for region in get_all_regions():
print(f"Searching in region: {region}")
boto3.setup_default_session(region_name=region)
resources = get_resources_with_tag_pattern(tag_pattern)
all_resources.extend(resources)
print("\nResources found:")
for resource in all_resources:
print(f"- {resource['ResourceArn']}")
print(f"\nTotal resources found: {len(all_resources)}")
if __name__ == "__main__":
main()
# Core AWS SDK
boto3>=1.26.0
botocore>=1.29.0
# Optional but recommended packages
python-dateutil>=2.8.2
PyYAML>=6.0.1
urllib3>=1.26.15
# Development dependencies
pytest>=7.3.1
pylint>=2.17.0
black>=23.3.0
flake8>=6.0.0
# AWS CLI (commented out as it's usually installed separately)
# awscli>=1.27.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment