Skip to content

Instantly share code, notes, and snippets.

@luketn
Created November 24, 2020 02:23
Show Gist options
  • Save luketn/d9e1bca5a9766921dbe417d36f13c6f4 to your computer and use it in GitHub Desktop.
Save luketn/d9e1bca5a9766921dbe417d36f13c6f4 to your computer and use it in GitHub Desktop.
Customising Name Tags in CDK
import {StackProps} from "@aws-cdk/core";
export interface BaseStackProps extends StackProps {
product: string;
environment: "development" | "production";
}
import {Aspects, Construct, IAspect, IConstruct, Stack, TagManager} from "@aws-cdk/core";
import {ITaggable} from "@aws-cdk/core/lib/tag-manager";
import {BaseStackProps} from "./base-stack-props";
import {createNameTag, shouldHaveNameTag} from "./name-tags";
export class BaseStack extends Stack {
constructor(scope: Construct, id: string, props: BaseStackProps) {
super(scope, id, props);
Aspects.of(this).add(new class implements IAspect {
public visit(construct: IConstruct): void {
if (TagManager.isTaggable(construct) && shouldHaveNameTag(construct)) {
let nameTag = createNameTag(construct, props);
construct.tags.setTag("Name", nameTag, 200);
}
}
});
}
}
import {IConstruct, Stack} from "@aws-cdk/core";
import {ITaggable} from "@aws-cdk/core/lib/tag-manager";
import {BaseStackProps} from "./base-stack-props";
import * as s3 from "@aws-cdk/aws-s3";
const uselessSuffixes = ['resource', 'subnet'];
export const createNameTag = (construct: IConstruct & ITaggable, props: BaseStackProps) => {
let pathName = pathToName(construct);
pathName = stripUselessSuffixes(pathName);
return `${props.product}-${props.environment}-${pathName}`;
}
export const shouldHaveNameTag = (construct: IConstruct & ITaggable) => {
if (construct instanceof Stack) {
return false;
} else if (construct instanceof s3.CfnBucket) {
return false;
} else {
return true;
}
}
export const pathToName = (construct: IConstruct & ITaggable) => {
return construct.node.path.split('/').splice(1).join('-').toLowerCase();
}
export const stripUselessSuffixes = (pathName: string) => {
for (const uselessSuffix of uselessSuffixes) {
let suffix = `-${uselessSuffix}`;
if (pathName.endsWith(suffix)) {
pathName = pathName.slice(0, -suffix.length);
}
}
return pathName;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment