|
| 1 | +import json |
| 2 | +import os |
| 3 | +from typing import TYPE_CHECKING |
| 4 | + |
| 5 | +import boto3 |
| 6 | +from botocore.config import Config |
| 7 | +from aws_lambda_powertools import Logger |
| 8 | +from aws_lambda_powertools.utilities.typing import LambdaContext |
| 9 | + |
| 10 | +if TYPE_CHECKING: |
| 11 | + from mypy_boto3_logs.client import CloudWatchLogsClient |
| 12 | + from mypy_boto3_sns.client import SNSClient |
| 13 | +else: |
| 14 | + CloudWatchLogsClient = object |
| 15 | + SNSClient = object |
| 16 | + |
| 17 | + |
| 18 | +logger = Logger() |
| 19 | + |
| 20 | +REQUIRED_RETENTION_DAYS = int(os.getenv("REQUIRED_RETENTION_DAYS", "2557")) |
| 21 | +ALERT_SNS_TOPIC_ARN = os.getenv("ALERT_SNS_TOPIC_ARN") |
| 22 | +REGION = os.environ.get("AWS_CURRENT_REGION", default="us-east-1") |
| 23 | +BOTO_CONFIG = Config( |
| 24 | + region_name=REGION, |
| 25 | + # Instructs boto3 to retry upto 10 times using an exponential backoff |
| 26 | + retries={ |
| 27 | + "total_max_attempts": 10, |
| 28 | + "mode": "adaptive", |
| 29 | + }, |
| 30 | + # Double the read timeout for some extra safety when synchrnously invoking the run-locust Lambda |
| 31 | + read_timeout=120, |
| 32 | +) |
| 33 | + |
| 34 | + |
| 35 | +def _list_non_compliant_log_groups(logs_client: CloudWatchLogsClient) -> list[dict[str, object]]: |
| 36 | + """Return log groups that are missing or not equal to required retention.""" |
| 37 | + non_compliant = [] |
| 38 | + paginator = logs_client.get_paginator("describe_log_groups") |
| 39 | + |
| 40 | + for page in paginator.paginate(): |
| 41 | + for group in page.get("logGroups", []): |
| 42 | + log_group_name = group.get("logGroupName") |
| 43 | + configured_retention = group.get("retentionInDays") |
| 44 | + if configured_retention is None or configured_retention < REQUIRED_RETENTION_DAYS: |
| 45 | + non_compliant.append( |
| 46 | + { |
| 47 | + "logGroupName": log_group_name, |
| 48 | + "retentionInDays": configured_retention, |
| 49 | + "requiredRetentionInDays": REQUIRED_RETENTION_DAYS, |
| 50 | + } |
| 51 | + ) |
| 52 | + if log_group_name: |
| 53 | + logger.info( |
| 54 | + "Updating log retention for %s (%s days).", |
| 55 | + log_group_name, |
| 56 | + REQUIRED_RETENTION_DAYS, |
| 57 | + ) |
| 58 | + logs_client.put_retention_policy( |
| 59 | + logGroupName=log_group_name, |
| 60 | + retentionInDays=REQUIRED_RETENTION_DAYS, |
| 61 | + ) |
| 62 | + |
| 63 | + return non_compliant |
| 64 | + |
| 65 | + |
| 66 | +def _publish_alert(sns_client: SNSClient, message: str) -> None: |
| 67 | + """Send alert to SNS when topic ARN is configured.""" |
| 68 | + if not ALERT_SNS_TOPIC_ARN: |
| 69 | + logger.warning("ALERT_SNS_TOPIC_ARN not configured. Alert only logged to CloudWatch.") |
| 70 | + return |
| 71 | + |
| 72 | + sns_client.publish( |
| 73 | + TopicArn=ALERT_SNS_TOPIC_ARN, |
| 74 | + Message=message, |
| 75 | + ) |
| 76 | + |
| 77 | + |
| 78 | +@logger.inject_lambda_context(clear_state=True, log_event=True) |
| 79 | +def lambda_handler(event: dict[str, Any], context: LambdaContext): |
| 80 | + |
| 81 | + logger.info( |
| 82 | + "Environment: REQUIRED_RETENTION_DAYS=%r, ALERT_SNS_TOPIC_ARN=%r", |
| 83 | + os.getenv("REQUIRED_RETENTION_DAYS"), |
| 84 | + os.getenv("ALERT_SNS_TOPIC_ARN"), |
| 85 | + ) |
| 86 | + |
| 87 | + logs_client = boto3.client("logs", config=BOTO_CONFIG) |
| 88 | + sns_client = boto3.client("sns", config=BOTO_CONFIG) |
| 89 | + |
| 90 | + non_compliant = _list_non_compliant_log_groups(logs_client) |
| 91 | + |
| 92 | + if not non_compliant: |
| 93 | + logger.info( |
| 94 | + "All CloudWatch log groups are compliant with retention policy (%s days).", |
| 95 | + REQUIRED_RETENTION_DAYS, |
| 96 | + ) |
| 97 | + return { |
| 98 | + "statusCode": 200, |
| 99 | + "body": json.dumps( |
| 100 | + { |
| 101 | + "message": "All log groups are compliant.", |
| 102 | + "requiredRetentionInDays": REQUIRED_RETENTION_DAYS, |
| 103 | + "nonCompliantCount": 0, |
| 104 | + } |
| 105 | + ), |
| 106 | + } |
| 107 | + |
| 108 | + payload = { |
| 109 | + "AlarmName": "log-retention-non-compliance", |
| 110 | + "AlarmDescription": f"Found {len(non_compliant)} log groups with non-compliant retention (required: {REQUIRED_RETENTION_DAYS} days)", |
| 111 | + "NewStateReason": json.dumps(non_compliant, indent=2), |
| 112 | + "Trigger": {"MetricName": None}, |
| 113 | + } |
| 114 | + # log the non-compliant log groups and publish an alert to SNS |
| 115 | + logger.warning( |
| 116 | + "Invalid resource payload: %s", |
| 117 | + json.dumps(non_compliant, indent=2), |
| 118 | + ) |
| 119 | + alert_message = json.dumps(payload) |
| 120 | + |
| 121 | + logger.warning(alert_message) |
| 122 | + _publish_alert(sns_client, alert_message) |
| 123 | + |
| 124 | + return { |
| 125 | + "statusCode": 200, |
| 126 | + "body": json.dumps( |
| 127 | + { |
| 128 | + "message": "Found log groups with non-compliant retention.", |
| 129 | + "requiredRetentionInDays": REQUIRED_RETENTION_DAYS, |
| 130 | + "nonCompliantCount": len(non_compliant), |
| 131 | + "nonCompliantLogGroups": non_compliant, |
| 132 | + } |
| 133 | + ), |
| 134 | + } |
0 commit comments