问题
How to add a tag to an AWS-CDK specific construct or even better one tag definition to all ressources created within the stack?
回答1:
According to aws-cdk doc you can add a tag to all constructs/ressources. Tags will inherits to constructs within same "tree". That's pretty cool.
Example using aws-cdk based on java:
MyStack stack = new MyStack(app, "nameOfStack");
stack.apply(new Tag("tag_foo", "value_bar"));
AWS-Doc CDK Tagging
Tags can be applied to any construct. Tags are inherited, based on the scope. If you tag construct A, and A contains construct B, construct B inherits the tag. The Tag API supports:
Example from aws-cdk doc:
import cdk = require('@aws-cdk/cdk');
const app = new cdk.App();
const theBestStack = new cdk.Stack(app, 'MarketingSystem');
theBestStack.node.apply(new cdk.Tag('StackType', 'TheBest'));
回答2:
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"}));
来源:https://stackoverflow.com/questions/54990414/how-to-add-a-tag-to-an-aws-cdk-construct