serverless-tag-resources
Version:
Datamart: Tag all AWS resources with dual legacy + datamart:* tag support
79 lines (65 loc) • 2.13 kB
JavaScript
;
/**
* Tag building module.
*
* Auto-generates datamart:* tags only (no legacy PascalCase):
* - datamart:environment (from deployment stage)
* - datamart:resource (from CloudFormation LogicalID)
*
* Legacy tags (Stage, Resource) removed in v3.1.0 per tagging policy v2.1.
*/
// Tags injected by SFW that should be removed post-deploy
const TAGS_TO_REMOVE = ["STAGE"];
/**
* Build list-based tags [{Key, Value}] for CloudFormation resources.
* Merges stackTags + auto-generated datamart:* tags.
*/
function buildListTags(stackTags, stage, logicalId) {
const tags = [];
const seen = new Set();
// User-provided stackTags
if (stackTags && typeof stackTags === "object") {
for (const [key, value] of Object.entries(stackTags)) {
tags.push({ Key: key, Value: String(value) });
seen.add(key.toLowerCase());
}
}
// Auto-generated datamart:* tags only
const autoTags = [
{ Key: "datamart:environment", Value: stage },
{ Key: "datamart:resource", Value: logicalId },
];
for (const tag of autoTags) {
if (!seen.has(tag.Key.toLowerCase())) {
tags.push(tag);
seen.add(tag.Key.toLowerCase());
}
}
return tags;
}
/**
* Build dict-based tags {key: value} for resources that use map format
* (SSM Parameter, API Gateway V2, Glue, Batch, etc.)
*/
function buildDictTags(stackTags, stage, logicalId) {
const tags = {};
// User-provided stackTags
if (stackTags && typeof stackTags === "object") {
for (const [key, value] of Object.entries(stackTags)) {
tags[key] = String(value);
}
}
// Auto-generated datamart:* tags only — don't overwrite user-provided
if (!tags["datamart:environment"]) tags["datamart:environment"] = stage;
if (!tags["datamart:resource"]) tags["datamart:resource"] = logicalId;
return tags;
}
/**
* Filter out aws: prefixed tags (reserved by AWS, cannot be set by user).
*/
function excludeAwsTags(tags) {
return tags.filter(
(tag) => !tag.Key.toLowerCase().startsWith("aws:")
);
}
module.exports = { buildListTags, buildDictTags, excludeAwsTags, TAGS_TO_REMOVE };