Contents

AWS S3 Versioning Status and CloudWatch Dashboard Setup

πŸ‡¦ πŸ‡Ό πŸ‡Έ S3 Versioning Status and CloudWatch Dashboard Setup πŸͺ§ ☁️ πŸ•™ 🧺 πŸ“ˆ

This document provides step-by-step instructions to set up a custom CloudWatch Dashboard that shows which S3 buckets have versioning enabled and disabled. It also includes the total number of buckets, separated by their versioning status.

Step 1: Create a Custom Policy for Lambda Function

Create a Custom Policy 🧾

➀ Go to IAM in the AWS Management Console.

➀ Click on Create Policy.

➀ Select the JSON tab and paste the following policy:

for policy access to github repo

json Copy code

 {
   "Version": "2012-10-17",
   "Statement": [
      {
        "Effect": "Allow",
        "Action": [
            "s3:ListAllMyBuckets",
            "s3:GetBucketVersioning",
            "cloudwatch:PutMetricData"
        ],
        "Resource": "*"
      }
   ]
}

Click on Next.

➀ Provide a suitable name for the custom policy and click on Create policy.

https://github.com/user-attachments/assets/881697c4-0ba8-4c30-93df-bb60a2027964 https://github.com/user-attachments/assets/96911bfc-828c-41d7-9c94-07a125c946c6

Step 2: Create a Lambda Function

Create the Lambda Function βš™οΈ

➀ Go to Lambda in the AWS Management Console.

➀ Click on Create function.

➀ Provide a suitable function name.

➀ Select runtime (Python 3.8).

➀ Click on Create function.

https://github.com/user-attachments/assets/f8d52f88-eb67-4581-bc75-d125f9461e86

Assign IAM Role to Lambda Function πŸ™‹

➀ Click on Configuration > Permissions.

➀ Click on the Role name to open the IAM Role page.

➀ Click on Add permissions > Attach policies.

➀ Click on Filter policies and select Customer managed.

➀ Search for the policy created in Step 1, select it, and click on Add permissions.

https://github.com/user-attachments/assets/7aa2fc77-6983-4d4e-aaed-4bdd65ea3f15

https://github.com/user-attachments/assets/afbf9fbb-c806-445e-a6e3-5e864f95dadc

Add Lambda Function Code

➀ Go back to the Lambda function.

➀ Click on Code.

➀ In the Lambda function section, paste the following code After pasting the code click on Deploy.

➀ Lambda Code for Bucket Versioning Status

for code access to github repo

python

Copy code

import boto3
import json
import datetime

s3_client = boto3.client('s3')
cloudwatch_client = boto3.client('cloudwatch')

def lambda_handler(event, context):
buckets = s3_client.list_buckets()
for bucket in buckets['Buckets']:
    bucket_name = bucket['Name']
    versioning = s3_client.get_bucket_versioning(Bucket=bucket_name)
    status = versioning.get('Status', 'Disabled')

    # Publish metrics to CloudWatch
    cloudwatch_client.put_metric_data(
        Namespace='S3/Versioning',
        MetricData=[
            {
                'MetricName': 'BucketVersioningStatus',
                'Dimensions': [
                    {
                        'Name': 'BucketName',
                        'Value': bucket_name
                    },
                ],
                'Timestamp': datetime.datetime.utcnow(),
                'Value': 1 if status == 'Enabled' else 0,
                'Unit': 'Count'
            },
        ]
    )

return {
    'statusCode': 200,
    'body': json.dumps('Metrics published successfully.')
}

https://github.com/user-attachments/assets/73572951-63d1-461f-8b92-c8e1f7cf1816

Test the Lambda Function βœ…

➀ Click on Test > Configure test event.

➀ Provide an event name.

➀Click on Save.

➀ Click on Test to run the Lambda function.

https://github.com/user-attachments/assets/d89aba2d-7e85-4890-b163-5f272bdb716f

https://github.com/user-attachments/assets/526d28d6-2d93-450f-9b60-b9ada10dd76f

https://github.com/user-attachments/assets/8b348677-3b1f-4840-b68f-a89c66fda4fc

Step 3: Create a CloudWatch Dashboard

Create a Dashboard πŸͺ§

➀ Go to CloudWatch in the AWS Management Console.

➀ Click on Dashboards > Create dashboard.

➀ Provide a name and click on Create dashboard.

https://github.com/user-attachments/assets/6785f710-6498-43b8-bc15-c4cd9411b3e6

Add Widgets to the Dashboard

First Widget: Bucket Versioning Status πŸ“Ÿ

➀ Click on Add widget.

➀ Select Number and click on Next.

➀ Select the namespace S3/Versioning and metric

➀ BucketVersioningStatus.

➀ Select all buckets and click on Create widget.

➀ Click on the three dots of the widget and select Edit.

➀ Click on Data table and select Only display summary columns in the table.

➀ In Summary, select Average and click on Update widget.

https://github.com/user-attachments/assets/6785f710-6498-43b8-bc15-c4cd9411b3e6

https://github.com/user-attachments/assets/b084bc95-ebfd-4a2d-8757-9e907f226890

https://github.com/user-attachments/assets/7154d0e3-c5c1-4c34-ab0a-a423fde4ef37

https://github.com/user-attachments/assets/c8cdf361-abb4-45a7-bc0c-92e0e01b6c24

Second Widget: Total Number of Buckets and Versioning Status

➀ Create a new Lambda function similar to the first one, but with the following code:

➀ Lambda Code for Total Number of Buckets and Versioning Status

for code access to github repo

python

Copy code

import boto3
import json
import datetime

def lambda_handler(event, context):
s3 = boto3.client('s3')
cloudwatch = boto3.client('cloudwatch')

# Get list of all S3 buckets
buckets = s3.list_buckets()

total_buckets = len(buckets['Buckets'])
versioning_enabled_buckets = []
versioning_disabled_buckets = []

for bucket in buckets['Buckets']:
    bucket_name = bucket['Name']
    versioning = s3.get_bucket_versioning(Bucket=bucket_name)
    
    if 'Status' in versioning and versioning['Status'] == 'Enabled':
        versioning_enabled_buckets.append(bucket_name)
    else:
        versioning_disabled_buckets.append(bucket_name)

# Publish custom metrics to CloudWatch
cloudwatch.put_metric_data(
    Namespace='S3/Versioning',
    MetricData=[
        {
            'MetricName': 'TotalBuckets',
            'Timestamp': datetime.datetime.utcnow(),
            'Value': total_buckets,
            'Unit': 'Count'
        },
        {
            'MetricName': 'VersioningEnabledBuckets',
            'Timestamp': datetime.datetime.utcnow(),
            'Value': len(versioning_enabled_buckets),
            'Unit': 'Count'
        },
        {
            'MetricName': 'VersioningDisabledBuckets',
            'Timestamp': datetime.datetime.utcnow(),
            'Value': len(versioning_disabled_buckets),
            'Unit': 'Count'
        }
    ]
)

# Create a detailed log output
response = {
    'TotalBuckets': total_buckets,
    'VersioningEnabledBuckets': versioning_enabled_buckets,
    'VersioningDisabledBuckets': versioning_disabled_buckets
}

return {
    'statusCode': 200,
    'body': json.dumps(response)
}

Add the Second Widget πŸ“Ÿ

➀ Click on the + button in the CloudWatch dashboard.

➀ Select Data table and click on Next.

➀ Select the namespace S3/Versioning.

➀ Select metrics with no dimensions.

➀ Select all metric names and click on Create widget.

➀ Click on the three dots of the widget and select Edit.

➀ Select options as per the previous widget and click on Update widget.

https://github.com/user-attachments/assets/3a296fd6-ed19-4431-b417-3819fdfd1ef8

https://github.com/user-attachments/assets/265b81ca-06dc-4aac-bf7d-5756223e3f45

https://github.com/user-attachments/assets/0593b50c-6844-4041-a5b7-84764e8c03aa

πŸ“† Schedule for Lambda Trigger πŸ”˜

➀ Go to AWS CloudWatch.

➀ Click on Rules.

➀ Amazon EventBridge will open. Select Schedules.

➀ Click on Create Schedule.

➀ Provide a name.

➀ Schedule group should be (default).

➀ Schedule pattern (Recurring schedule).

➀ Schedule type (Rate-based schedule).

➀ Rate expression (days).

➀ Flexible time window (15 minutes).

➀ Leave the timeframe empty and click on Next.

For Target 🎯

➀ Select AWS Lambda.

➀ Invoke the Lambda function created earlier and click on Next.

➀ Leave the next page settings as default and click on Next.

➀ Review all settings and click on Create schedule. This schedule will run once a day.

https://github.com/user-attachments/assets/40c8b3db-24b0-4e3a-bba6-2573a2054334

https://github.com/user-attachments/assets/fafd71e9-ac5e-4908-9f02-3e6655601e88

https://github.com/user-attachments/assets/3e334ed7-a4e9-46d9-a1ec-8f5482f72554

https://github.com/user-attachments/assets/7a902970-a3f3-4f17-a841-e1ccd7500cc8

https://github.com/user-attachments/assets/bb3f9b57-ce29-4faa-b841-5c2968d324eb

https://github.com/user-attachments/assets/6d21e94d-479d-4839-8c36-9557d809cc23

https://github.com/user-attachments/assets/4fe87f34-1fd4-47c8-993a-067c3958bcea

https://github.com/user-attachments/assets/606d2326-2bb6-4b1b-bb61-88d68e8f0646