AWS cdk如何在TypeScript中标记资源?

时间:2020-09-09 10:37:45

标签: amazon-web-services tags aws-cdk

我有一个cdk项目,在其中创建一个DynamoDB表并向其添加标签,如下所示,

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)
    }
}

上面的代码可以很好地向表中添加标签,但是现在不推荐使用这种标签方法here,那么如何替换这种标签方法?

1 个答案:

答案 0 :(得分:3)

您可以标记构造,CDK应该递归添加标记。您不需要包括嵌入式addTags函数。例如,要在代码中使用更新的不推荐使用的方法,可以使用this来引用要处理的构造并执行以下操作:

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');
    }
}