1

Currently, I am trying to delete a log group from a lambda function that's created by AWS CDK

Here is what my stack currently looks like:

from aws_cdk import (
    core,
    aws_lambda
)
from aws_cdk.aws_logs import CfnLogGroup, LogGroup
from datetime import datetime
f = """
import json
from datetime import datetime

def handler(event, context):
    print(f'test {datetime.now()}')
    return {
        'statusCode': 200,
        'body': json.dumps(f'test {datetime.now()}')
    }
"""

class CdktestStack(core.Stack):

    def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        fn = aws_lambda.Function(self, f"AndyTest-{datetime.now()}",
            runtime=aws_lambda.Runtime.PYTHON_3_8,
            handler="index.handler",
            code=aws_lambda.InlineCode(f)
        )

        lg = LogGroup.from_log_group_name(self, f"lambda_log_group-{datetime.now()}", fn.log_group.log_group_name)
        lg.apply_removal_policy(core.RemovalPolicy.DESTROY)

By default, the lambda log group is retained after CDK destroy has completed.

I have tried to manage the log group by using LogGroups to manage the logs.

I have seen this answer for destroying a log group but it will not as this line:

lg = LogGroup.from_log_group_name(self, f"lambda_log_group-{datetime.now()}", fn.log_group.log_group_name)

returns an ILogGroup and throws this error when I try and call

lg.apply_removal_policy(core.RemovalPolicy.DESTROY)

with this error:

jsii.errors.JSIIError: Cannot apply RemovalPolicy: no child or not a CfnResource. Apply the removal policy on the CfnResource directly.

My objective is to use CDK to manage the log group so that the resource can be deleted on destroy without using boto3.

apollowebdesigns
  • 658
  • 11
  • 26
  • Really cool. I've been wondering if this was possible for a while, but you've gotten a lot farther than I. I'll look into this over the course of the day. –  Jul 29 '21 at 12:28
  • 1
    @Hcaertnit thanks for taking a look, I did notice this [issue on github](https://github.com/aws/aws-cdk/issues/11549) so it looks like it was requested as a feature but I don't know how much further the issue got – apollowebdesigns Jul 29 '21 at 12:32

1 Answers1

2

The code below works fine by creating a log group seperately based on name rather than loading it in from name. See below for detailed implementation:

from aws_cdk import core, aws_lambda
from aws_cdk.aws_logs import CfnLogGroup, LogGroup, RetentionDays
from datetime import datetime

f = """
import json
from datetime import datetime

def handler(event, context):
    print(f'test {datetime.now()}')
    return {
        'statusCode': 200,
        'body': json.dumps(f'test {datetime.now()}')
    }
"""


class CdktestStack(core.Stack):
    def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        fn = aws_lambda.Function(
            self,
            f"AndyTest-{datetime.now()}",
            runtime=aws_lambda.Runtime.PYTHON_3_8,
            handler="index.handler",
            code=aws_lambda.InlineCode(f),
        )

        LogGroup(
            self,
            f"lambda_log_group-{datetime.now()}",
            log_group_name=f"/aws/lambda/{fn.function_name}",
            removal_policy=core.RemovalPolicy.DESTROY,
            retention=RetentionDays.ONE_DAY,
        )

A word of warning, if you use a log_retention attribute it creates a custom resource to automatically generate an associated log group for you. So the above works fine.

apollowebdesigns
  • 658
  • 11
  • 26