2025-11-18 11:00:28 +00:00
2025-11-18 10:55:12 +00:00

بسم الله الرحمن الرحيم

AWS Resource Inventory Script

This script provides a comprehensive, automated inventory of AWS resources across multiple services and regions. It collects detailed metadata for various resource types and exports the data in multiple formats for auditing, cost analysis, security reviews, or migration planning.


Overview

The AWS Resource Inventory Script uses the AWS SDK for Python (Boto3) to query your AWS account and generate structured reports listing key resources. It supports multiple AWS services, includes robust error handling, and is designed to run securely in environments with varying permission scopes.


Supported Services

The script currently collects inventory for the following AWS services:

  • Amazon S3: Buckets with creation date and region
  • AWS Lambda: Functions with runtime, memory, timeout, and environment variable count
  • Amazon Route 53: Hosted zones and DNS record sets
  • Amazon EC2: Instances with instance type, state, launch time, network configuration, and tags
  • Amazon RDS: Database instances with engine, status, storage, and endpoint
  • AWS IAM: Users with creation date, group membership, and attached policy count
  • Amazon CloudFront: Distributions with domain name, status, and enablement

Note

: Support for additional services can be added by extending the class with new get_* methods.


Features

  • Multi-region scanning: Automatically discovers and queries all supported regions (configurable)
  • Robust error handling: Gracefully handles missing permissions or service-specific errors
  • Multiple output formats: Generates JSON, CSV, and console summary reports
  • Modular design: Easy to extend with new resource types or filtering logic
  • Account identification: Includes AWS account ID in all output for multi-account workflows
  • Timestamped reports: All files are saved with unique timestamps to prevent overwrites

Prerequisites

AWS Permissions

The script requires read-only access to the services listed above. At a minimum, the following IAM permissions (or equivalent) are recommended:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:ListAllMyBuckets",
        "s3:GetBucketLocation",
        "lambda:ListFunctions",
        "ec2:DescribeInstances",
        "rds:DescribeDBInstances",
        "iam:ListUsers",
        "iam:ListGroupsForUser",
        "iam:ListAttachedUserPolicies",
        "route53:ListHostedZones",
        "route53:ListResourceRecordSets",
        "cloudfront:ListDistributions",
        "sts:GetCallerIdentity"
      ],
      "Resource": "*"
    }
  ]
}

Note on S3 Metrics: Bucket size estimation uses CloudWatch metrics and requires cloudwatch:GetMetricStatistics. If unavailable, size fields will be omitted.

Python Dependencies

  • Python 3.7 or later
  • Required packages:
    • boto3
    • pandas

Install dependencies via:

pip install boto3 pandas

Usage

Basic Execution

Run the script with default AWS credentials (e.g., ~/.aws/credentials or instance role):

python aws_inventory.py

Using a Specific AWS Profile

Uncomment and modify the profile_name parameter in the main() function:

inventory = AWSResourceInventory(
    profile_name="my-profile",
    # regions=['us-east-1', 'eu-west-1']
)

Alternatively, set the AWS_PROFILE environment variable before execution:

AWS_PROFILE=my-profile python aws_inventory.py

Specifying Regions

To restrict scanning to specific regions, uncomment and provide a list in the constructor:

inventory = AWSResourceInventory(
    regions=['us-east-1', 'us-west-2', 'eu-central-1']
)

Output

Reports are saved to the ./reports/ directory (created automatically), with filenames in the format:

aws_inventory_<account-id>_<timestamp>.<extension>

File Types

Format Filename Example Use Case
JSON aws_inventory_123456789012_20251118_143022.json Machine-readable, detailed nested structure
CSV aws_inventory_123456789012_20251118_143022.csv Spreadsheet analysis, import into BI tools
Console Summary Printed to stdout Quick overview during execution

The console summary includes:

  • Account ID
  • Timestamp
  • Number of regions scanned
  • Resource count per service
  • Total resource count

Security Considerations

  • This tool reads metadata only and does not modify any AWS resources.
  • All AWS API calls use read-only actions.
  • Avoid running with excessive permissions (e.g., AdministratorAccess) — least privilege is recommended.
  • Report files may contain sensitive identifiers (e.g., instance IDs, bucket names). Store and share outputs securely.

Extending the Script

To add support for a new service (e.g., DynamoDB):

  1. Add a new method, e.g., def get_dynamodb_tables(self):
  2. Implement resource collection logic using Boto3 clients/resources
  3. Append results to self.resources['DynamoDB']
  4. Add the method to the resource_methods list in generate_report()

Ensure all new methods:

  • Include the AccountId, Region, Service, and Type fields
  • Handle pagination where applicable
  • Log errors without crashing the entire inventory run

Troubleshooting

Issue Possible Cause Resolution
NoCredentialProviders error Missing AWS credentials Configure credentials via CLI, environment variables, or IAM role
Empty results for a service Insufficient permissions Verify IAM policy includes required List*/Describe* actions
Script hangs on a region Network or service throttling Add retry logic or exclude problematic regions
Timestamp parsing errors Date format inconsistency Ensure system timezone is UTC or handle localization explicitly

Check the log output (INFO and ERROR levels) for detailed diagnostics.


License

This script is provided under the MIT License. See LICENSE for full terms.


Disclaimer: This tool is provided "as-is" for informational purposes. Always validate outputs against the AWS Management Console or AWS CLI before making operational decisions.

الوصف
لا يوجد وصف
اقرأني 41 KiB
اللغات
Python 100%