Set AWS Lambda Log Group Retention With AWS CDK

The guide shows how to set AWS Lambda retention policy with AWS CDK

Friday, November 1, 2019

CDK Script (CDK version 1.23 and higher)

The setting is now extremelly simple, you just set the logRetention property with desired RetentionDays value. Special value exists for infinite log retention - RetentionDays.Infinite. Setting this value will erase any existing log retention.

The script will create a custom resource in form of the CDK managed lambda function which will be controlling the log retention settings of the given lambda function.

CDK Script (Obsolote for pre 1.23 version)

When lambda function assumes role which has access to create AWS CloudWatch log group and push logs into it, log group is created automatically by convention. We can create log group with same name and provided retention configuration.

logGroupName needs to have exact format as written above, as that is the format automatically generated by AWS when Lambda will try to create a log. Retention policy of the log entries is set to 7 days. The log group will be destroyed together with lambda function.