ABCD
ABCD

Reputation: 820

AWS cdk how to tag resources in TypeScript?

I have a cdk project in which I am creating an DynamoDB table and adding tag to it like below,

import * as core from "@aws-cdk/core";
import * as dynamodb from "@aws-cdk/aws-dynamodb";
import { Tag } from "@aws-cdk/core";

export class DynamoDbTable extends core.Construct {
    constructor(scope: core.Construct, id: string) {
        super(scope, id);
        function addTags(resource : any) {
            Tag.add(resource, "Key", "value");
        }
        const table = new dynamodb.Table(this, "abcd", {
            partitionKey: { name: "name", type: dynamodb.AttributeType.STRING },
            stream: dynamodb.StreamViewType.NEW_AND_OLD_IMAGES,
            tableName: 'tableName',
            billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
        });
        addTags(table)
    }
}

Above code works fine add tags to table but this tagging method is deprecated now here so how can I replace this tagging method?

Upvotes: 4

Views: 4527

Answers (1)

Shogan
Shogan

Reputation: 1195

You can tag a construct and CDK should add tags recursively. You shouldn't need to include your embedded addTags function. For example to use the newer non-deprecated method, in your code, you can use this to refer to the construct you are dealing with and do:

import { Tag } from "@aws-cdk/core";

export class DynamoDbTable extends core.Construct {
    constructor(scope: core.Construct, id: string) {
        super(scope, id);
        
        const table = new dynamodb.Table(this, "abcd", {
            partitionKey: { name: "name", type: dynamodb.AttributeType.STRING },
            stream: dynamodb.StreamViewType.NEW_AND_OLD_IMAGES,
            tableName: 'tableName',
            billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
        });

        Tags.of(this).add('Foo', 'Bar');
    }
}

Upvotes: 6

Related Questions