Home > Software design >  Is it possible to apply tags to only those resources that are created by the defined constructs in A
Is it possible to apply tags to only those resources that are created by the defined constructs in A

Time:10-05

Let's say I have a stack that creates a lambda function with logRetention enabled, like so

export class MainStack extends Stack {
constructor(scope: Construct, id:string, props:StackProps) {
    super(scope, id, props);
    Tags.of(this).add('createdBy','cdk')

    const func = new Function(this, 'function', {
        functionName: 'cdk-function',
        code: Code.fromInline('print(event)'),
        handler: 'lambda.handler',
        runtime: Runtime.PYTHON_3_8,
        logRetention: RetentionDays.ONE_DAY
    })
}}

When I deploy the above stack it creates two lambda functions, 'cdk-function' and one more lambda to manage log retention. It applies the mentioned tag to both the lambda function since they exist in the same scope, but my intention was to apply the tags to only those resources that I have in my cdk code. I don't want to apply tags to all the automatically created resources by cdk. Is it possible to skip tags for those resources?

CodePudding user response:

Every L2 Construct in AWS CDK has a property called Node, and within this Node property you can access all the underlying resources with func.node.children which returns an array of all the children resources of that main Construct, then you can access these children and manipulate them as you need (e.g: removing the tags for one child). Hope that help you!

CodePudding user response:

A construct can provision an arbitrary number of resources under the hood, and this is true for both the constructs that ship with aws-cdk-lib and the ones you write yourself.

Most L2 constructs that ship with CDK have a default child, though, and you can apply your tags to that.

Tags.of(func.node.defaultChild).add('createdBy','cdk')

This prop is optional, though, and you may need to add a check to ensure it's not undefined.

This will not prevent the tags being propagated to any constructs that are created in the scope of the default child, but this usually never happens with constructs that ship with AWS CDK by default.

  • Related