|
| 1 | +# Tagging API Change |
| 2 | + |
| 3 | +CDK support tagging and can cascade tags to all its taggable children (see [here](https://docs.aws.amazon.com/cdk/latest/guide/tagging.html)). The current CDK tagging API is shown below: |
| 4 | + |
| 5 | +``` ts |
| 6 | +myConstruct.node.applyAspect(new Tag('key', 'value')); |
| 7 | + |
| 8 | +myConstruct.node.applyAspect(new RemoveTag('key', 'value')); |
| 9 | +``` |
| 10 | + |
| 11 | +As we can see, the current tagging API is not nice and grammatically verbose for using, since there is no reason to expose `node` to users and `applyAspect` does not indicate anything towards tags, which leaves room for improvement. Also, users need to create two objects to add tag and remove tag which causes confusion to some degree. |
| 12 | + |
| 13 | +## General approach |
| 14 | + |
| 15 | +For the tagging behavior part, we propose using just one entry point `Tag` for the new tagging API: |
| 16 | + |
| 17 | +``` ts |
| 18 | +Tag.add(myConstruct, 'key', 'value'); |
| 19 | + |
| 20 | +Tag.remove(myConstruct, 'key'); |
| 21 | +``` |
| 22 | + |
| 23 | +## Code changes |
| 24 | + |
| 25 | +Given the above, we should make the following changes: |
| 26 | + 1. Add two methods `add` and `remove` to `Tag` class, which calls `applyAspect`to add tags or remove tags. |
| 27 | + |
| 28 | +# Part1: Change CDK Tagging API |
| 29 | + |
| 30 | +Implementation for the new tagging API is shown below: |
| 31 | + |
| 32 | +``` ts |
| 33 | +/** |
| 34 | + * The Tag Aspect will handle adding a tag to this node and cascading tags to children |
| 35 | + */ |
| 36 | +export class Tag extends TagBase { |
| 37 | + |
| 38 | + /** |
| 39 | + * add tags to the node of a construct and all its the taggable children |
| 40 | + */ |
| 41 | + public static add(scope: Construct, key: string, value: string, props: TagProps = {}) { |
| 42 | + scope.node.applyAspect(new Tag(key, value, props)); |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * remove tags to the node of a construct and all its the taggable children |
| 47 | + */ |
| 48 | + public static remove(scope: Construct, key: string, props: TagProps = {}) { |
| 49 | + scope.node.applyAspect(new RemoveTag(key, props)); |
| 50 | + } |
| 51 | + |
| 52 | + ... |
| 53 | +} |
| 54 | +``` |
| 55 | + |
| 56 | +And below is an example use case demonstrating how the adjusted tagging API works: |
| 57 | + |
| 58 | +``` ts |
| 59 | +// Create Task Definition |
| 60 | +const taskDefinition = new ecs.Ec2TaskDefinition(stack, 'TaskDef'); |
| 61 | + |
| 62 | +// Create Service |
| 63 | +const service = new ecs.Ec2Service(stack, "Service", { |
| 64 | + cluster, |
| 65 | + taskDefinition, |
| 66 | +}); |
| 67 | + |
| 68 | +Tag.add(taskDefinition, 'tfoo', 'tbar'); |
| 69 | +Tag.remove(taskDefinition, 'foo', 'bar'); |
| 70 | + |
| 71 | +Tag.add(service, 'sfoo', 'sbar'); |
| 72 | +Tag.remove(service, 'foo', 'bar'); |
| 73 | +``` |
0 commit comments