How to add a tag to an AWS-CDK construct

后端 未结 4 1427
孤街浪徒
孤街浪徒 2021-01-19 21:22

How to add a tag to an AWS-CDK specific construct or even better one tag definition to all ressources created within the stack?

4条回答
  •  日久生厌
    2021-01-19 21:55

    Because you'll likely want to add more than one Tag to a construct, its handy to pass an object of tags. You can use aspects in cdk to descend nodes looking for node of your type and applying whatever you want to apply to said node. The following example adds tags.

    export class TagAspect implements cdk.IAspect {
     private readonly tags: Object;
    
     constructor(tags: Object) {
       this.tags = tags;
     }
    
    public visit(node: cdk.IConstruct): void {
      if (node instanceof cdk.Stack) {
          Object.entries(this.tags).forEach( ([key, value]) => {
          cdk.Tag.add(node,key,value); 
      });
     }}}
    

    Then in the Stack you want to apply an aspect to run this.node.applyAspect(new TagAspect({"tag1":"mytag1","tag2":"another tag","tag3":"andanother"}));

提交回复
热议问题