Skip to content

Instantly share code, notes, and snippets.

@prenagha
Last active October 31, 2018 16:48
Show Gist options
  • Save prenagha/dd29d3a902a8202aaae940095ca63b83 to your computer and use it in GitHub Desktop.
Save prenagha/dd29d3a902a8202aaae940095ca63b83 to your computer and use it in GitHub Desktop.
Lambda CloudWatch Log Retention Manager
import boto3
import os
def lambda_handler(event, context):
default_region = os.environ.get('AWS_REGION', 'us-east-1')
retain_days = int(os.environ.get('RETAIN_DAYS', '30'))
session = boto3.Session()
client = session.client('ec2', region_name=default_region)
for region_dict in client.describe_regions()['Regions']:
region = region_dict['RegionName']
print('Region:', region)
logs = session.client('logs', region_name=region)
log_groups = logs.describe_log_groups()
for log_group in log_groups['logGroups']:
log_group_name = log_group['logGroupName']
if 'retentionInDays' in log_group:
print(region, log_group_name, log_group['retentionInDays'], 'days')
else:
print(region, log_group_name, retain_days, 'days **PUT**')
response = logs.put_retention_policy(
logGroupName=log_group_name,
retentionInDays=retain_days
)
return 'CloudWatchLogRetention.Success'
{
"version": "0",
"id": "arar40ba-aaaa-bbbb-cccc-81d33314b7",
"detail-type": "Scheduled Event",
"source": "aws.events",
"account": "1212121212",
"time": "2018-10-30T10:22:22Z",
"region": "us-east-1",
"resources": [
"arn:aws:events:us-east-1:1212121212:rule/logrtnmgr"
],
"detail": {}
}
@prenagha
Copy link
Author

See blog post

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment