Search code examples
amazon-web-servicesaws-lambdaaws-cdkamazon-cloudwatchlogs

Update Lambda LogGroup KMS to CMS using CDK


Using cdk it is possible to create a lambda function (example in scala for tersness):

val lambdaFunction = lambda.Function.Builder.create...build()

The creation of the Lambda automatically creates a LogGroup in CloudWatch.

How can the KMS key of the automatically created LogGroup be changed to a CMS using cdk?

The lambdaFunction does have a getLogGroup method but that returns an ILogGroup which doesn't have any setter methods.

The lambda.Function.Builder has a logRetention method but no corresponding method for setting the KMS Key.

There is a similar question which does not apply because it is asking to change KMS across ALL LogGroups, not a LogGroup related to a Lambda.

Thank you in advance for your consideration and response.


Solution

  • "The creation of the Lambda automatically creates a LogGroup in CloudWatch." - not exactly, generally the first invocation of the lambda actually creates the LogGroup plus the first LogStream plus the first log events inside of it. CDK / CFN does not create the LogGroup at all, nor is the LogGroup removed when you delete the Lambda.

    But CDK / CFN can do it. It is simply something you need to explicitly do. You need to create the LogGroup, specify the right keys, retention, etc. The LogGroup needs to follow the naming /aws/lambda/LAMBDA_NAME_HERE. And then you need to add an explicit dependency between the Lambda Function and the LogGroup such that the lambda is only created after the LogGroup.

    Note that this does not work for already existing Lambdas because there the LogGroup already exists. In that case you need to either import the existing LogGroup first or use a "custom resource" to change the settings of the LogGroup based on your requirements.


    Fyi the mentioned logRetention logic relies on such a "custom resource". It creates the log group or updates the existing one.