@guardian/cdk 63.2.1 → 63.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -88,7 +88,7 @@ class GuStack extends aws_cdk_lib_1.Stack {
|
|
|
88
88
|
this.addTag("App", this.app);
|
|
89
89
|
}
|
|
90
90
|
if (this.riffRaffProjectName) {
|
|
91
|
-
this.addTag("gu:riff-raff
|
|
91
|
+
this.addTag("gu:riff-raff:project", this.riffRaffProjectName);
|
|
92
92
|
}
|
|
93
93
|
if (this.repositoryName) {
|
|
94
94
|
this.addTag(constants_1.MetadataKeys.REPOSITORY_NAME, this.repositoryName);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stack.js","sourceRoot":"","sources":["../../../src/constructs/core/stack.ts"],"names":[],"mappings":";;;;;;AACA,6CAAsG;AAEtG,kEAAwC;AACxC,6EAAwE;AACxE,iFAA4E;AAC5E,qDAAkD;AAClD,+CAAyE;AACzE,yCAAqD;AAkDrD;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAa,OAAQ,SAAQ,mBAAK;IAYhC;;;;;;;;;OASG;IACO,MAAM,CAAC,GAAW,EAAE,KAAa,EAAE,2BAAoC,IAAI;QACnF,4CAA4C;QAC5C,wGAAwG;QACxG,kBAAI,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,wBAAwB,EAAE,CAAC,CAAC;IAC9D,CAAC;IAED;;;;OAIG;IACH,IAAI,UAAU;QACZ,OAAO,IAAI,CAAC,IAAI;aACb,OAAO,EAAE;aACT,MAAM,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,YAAY,0BAAY,CAAC;aACxD,MAAM,CAAC,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,GAAG,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,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C;IACvG,CAAC;CACF;AA/KD,0BA+KC","sourcesContent":["import type { App, CfnElement, StackProps } from \"aws-cdk-lib\";\nimport { Annotations, Aspects, CfnParameter, LegacyStackSynthesizer, Stack, Tags } from \"aws-cdk-lib\";\nimport type { IConstruct } from \"constructs\";\nimport gitUrlParse from \"git-url-parse\";\nimport { CfnIncludeReporter } from \"../../aspects/cfn-include-reporter\";\nimport { CfnParameterReporter } from \"../../aspects/cfn-parameter-reporter\";\nimport { Metadata } from \"../../aspects/metadata\";\nimport { ContextKeys, MetadataKeys, TrackingTag } from \"../../constants\";\nimport { gitRemoteOriginUrl } from \"../../utils/git\";\nimport type { StackStageIdentity } from \"./identity\";\nimport type { GuStaticLogicalId } from \"./migrating\";\n\nexport interface GuStackProps extends Omit<StackProps, \"stackName\"> {\n /**\n * The Guardian stack being used (as defined in your riff-raff.yaml).\n * This will be applied as a tag to all of your resources.\n */\n stack: string;\n\n /**\n * The stage being used (as defined in your riff-raff.yaml).\n * This will be applied as a tag to all of your resources.\n */\n stage: string;\n\n /**\n * Optional name of the app. If defined, all resources will have an App tag.\n */\n app?: string;\n\n /**\n * The name of the Riff-Raff project used to deploy these resources.\n * Used as the value of the `gu:riff-raff-project` tag on all resources.\n * If using {@link GuRoot} or {@link RiffRaffYamlFile}, this value is also used in the location of the generated `riff-raff.yaml`.\n *\n * @see https://github.com/guardian/riffraff-platform\n */\n riffRaffProjectName?: string;\n\n /**\n * The AWS CloudFormation stack name (as shown in the AWS CloudFormation UI).\n * @defaultValue the `GU_CFN_STACK_NAME` environment variable\n */\n cloudFormationStackName?: string;\n /**\n * Set this to true to stop the GuStack from tagging all of your AWS resources.\n * This should only be turned on as part of an initial migration from CloudFormation.\n */\n withoutTags?: boolean;\n\n /**\n * Set to disable CDK metadata. Only for internal use (for disabling for some\n * snapshot tests). We rely on tracking data to prioritise future work so\n * please do not override this.\n */\n withoutMetadata?: boolean;\n}\n\n/**\n * GuStack provides the `stack` and `stage` parameters to a template.\n * It also takes the `app` in the constructor.\n *\n * GuStack will add the Stack, Stage and App tags to all resources.\n *\n * GuStack also adds the tag `X-Gu-CDK-Version`.\n * This tag allows us to measure adoption of this library.\n * It's value is the version of guardian/cdk being used, as defined in `package.json`.\n * As a result, the change sets between version numbers will be fairly noisy,\n * as all resources receive a tag update.\n * It is recommended to upgrade the version of @guardian/cdk being used in two steps:\n * 1. Bump the library, apply the tag updates\n * 2. Make any other stack changes\n *\n * Typical usage is to extend GuStack:\n *\n * ```typescript\n * class MyStack extends GuStack {\n * constructor(scope: App, id: string, props: GuStackProps) {\n * super(scope, id, props)\n * }\n *\n * // add resources here\n * }\n * ```\n */\nexport class GuStack extends Stack implements StackStageIdentity {\n public readonly stack: string;\n public readonly stage: string;\n public readonly app: string | undefined;\n public readonly riffRaffProjectName: string | undefined;\n\n /**\n * The repository name, if it can be determined from the context or the git remote origin url.\n * If it cannot be determined from either of these sources, it will be `undefined`.\n */\n public readonly repositoryName: string | undefined;\n\n /**\n * A helper function to add a tag to all resources in a stack.\n *\n * Note: tags will be listed in alphabetical order during synthesis.\n *\n * @param key the tag name\n * @param value the value of the tag\n * @param applyToLaunchedInstances whether or not to apply the tag to instances launched in an ASG.\n * @protected\n */\n protected addTag(key: string, value: string, applyToLaunchedInstances: boolean = true): void {\n // TODO add validation for `key` and `value`\n // see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html\n Tags.of(this).add(key, value, { applyToLaunchedInstances });\n }\n\n /**\n * Returns all the parameters on this stack.\n *\n * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html\n */\n get parameters(): Record<string, CfnParameter> {\n return this.node\n .findAll()\n .filter((construct) => construct instanceof CfnParameter)\n .reduce((acc, param) => ({ ...acc, [param.node.id]: param as CfnParameter }), {});\n }\n\n // eslint-disable-next-line custom-rules/valid-constructors -- GuStack is the exception as it must take an App\n constructor(scope: App, id: string, props: GuStackProps) {\n const {\n cloudFormationStackName = process.env.GU_CFN_STACK_NAME,\n stack,\n stage,\n app,\n riffRaffProjectName,\n withoutTags,\n } = props;\n\n super(scope, id, {\n ...props,\n stackName: cloudFormationStackName,\n\n // TODO Use `DefaultStackSynthesizer` or create own synthesizer?\n // see https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html#bootstrapping-custom-synth\n synthesizer: new LegacyStackSynthesizer(),\n });\n\n this.stack = stack;\n this.stage = stage.toUpperCase();\n this.app = app;\n this.riffRaffProjectName = riffRaffProjectName;\n this.repositoryName = this.tryGetRepositoryTag();\n\n if (!withoutTags) {\n this.addTag(TrackingTag.Key, TrackingTag.Value);\n\n this.addTag(\"Stack\", this.stack);\n this.addTag(\"Stage\", this.stage);\n if (this.app) {\n this.addTag(\"App\", this.app);\n }\n\n if (this.riffRaffProjectName) {\n this.addTag(\"gu:riff-raff-project\", this.riffRaffProjectName);\n }\n\n if (this.repositoryName) {\n this.addTag(MetadataKeys.REPOSITORY_NAME, this.repositoryName);\n }\n }\n\n if (!props.withoutMetadata) {\n Aspects.of(this).add(new Metadata(this));\n }\n\n Aspects.of(this).add(new CfnIncludeReporter());\n Aspects.of(this).add(new CfnParameterReporter());\n }\n\n /**\n * Returns the repository name.\n * The value is retrieved in the following order:\n * 1. From the context\n * 2. From git config\n *\n * @private\n */\n private tryGetRepositoryTag(): string | undefined {\n try {\n const urlFromContext = this.node.tryGetContext(ContextKeys.REPOSITORY_URL) as string | undefined;\n const repositoryUrl: string = urlFromContext ?? gitRemoteOriginUrl();\n return gitUrlParse(repositoryUrl).full_name;\n } catch {\n console.info(\n `Unable to find git repository name. Set the ${ContextKeys.REPOSITORY_URL} context value or configure a git remote`,\n );\n return undefined;\n }\n }\n\n /**\n * Override the auto-generated logical ID for a resource, in the generated CloudFormation template, with a static one.\n *\n * Of particular use when migrating a JSON/YAML CloudFormation template into GuCDK.\n * It's generally advised to retain the logical ID for stateful resources, such as databases or buckets.\n *\n * Let's say we have a YAML template:\n *\n * ```yaml\n * AWSTemplateFormatVersion: '2010-09-09'\n * Resources:\n * UsesTable:\n * Type: AWS::DynamoDB::Table\n * Properties:\n * TableName: !Sub 'users-${stage}'\n * ```\n *\n * When moving to GuCDK we'll have this:\n *\n * class MyStack extends GuStack {\n * constructor(app: App, id: string, props: GuStackProps) {\n * super(app, id, props);\n *\n * const { stage } = this;\n *\n * new Table(this, \"UsersTable\", {\n * name: `users-${stage}`\n * });\n * }\n * }\n *\n * During synthesis, CDK auto-generates logical IDs, so we'll have a stack with a DynamoDB table named 'UsersTable<SOME GUID>', NOT `UsersTable`.\n * That is, the `UsersTable` table will be deleted.\n *\n * In order to retain the original ID from the YAML template, we will do:\n *\n * class MyStack extends GuStack {\n * constructor(app: App, id: string, props: GuStackProps) {\n * super(app, id, props);\n *\n * const { stage } = this;\n *\n * const table = new Table(this, \"UsersTable\", {\n * name: `users-${stage}`\n * });\n *\n * this.overrideLogicalId(table, { logicalId: \"UsersTable\", reason: \"Retaining a stateful resource from the YAML template\" });\n * }\n * }\n *\n * @param construct The (stateful) resource to retain the logical ID of.\n * @param logicalId The logical ID of the resource (as defined in the JSON/YAML template.\n * @param reason A small explanation to keep the logical ID. Mainly used to help future developers.\n */\n public overrideLogicalId(construct: IConstruct, { logicalId, reason }: GuStaticLogicalId): void {\n const {\n node: { id, defaultChild },\n } = construct;\n\n (defaultChild as CfnElement).overrideLogicalId(logicalId);\n Annotations.of(construct).addInfo(`Setting logical ID for ${id} to ${logicalId}. Reason: ${reason}`);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"stack.js","sourceRoot":"","sources":["../../../src/constructs/core/stack.ts"],"names":[],"mappings":";;;;;;AACA,6CAAsG;AAEtG,kEAAwC;AACxC,6EAAwE;AACxE,iFAA4E;AAC5E,qDAAkD;AAClD,+CAAyE;AACzE,yCAAqD;AAkDrD;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAa,OAAQ,SAAQ,mBAAK;IAYhC;;;;;;;;;OASG;IACO,MAAM,CAAC,GAAW,EAA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CAA+C,uBAAW,CAAC,cAAc,0CAA0C,CACpH,CAAC;YACF,OAAO,SAAS,CAAC;SAClB;IACH,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAqDG;IACI,iBAAiB,CAAC,SAAqB,EAAE,EAAE,SAAS,EAAE,MAAM,EAAqB;QACtF,MAAM,EACJ,IAAI,EAAE,EAAE,EAAE,EAAE,YAAY,EAAE,GAC3B,GAAG,SAAS,CAAC;QAEb,YAA2B,CAAC,iBAAiB,CAAC,SAAS,CAAC,CAAC;QAC1D,yBAAW,CAAC,EAAE,CAAC,SAAS,CAAC,CAAC,OAAO,CAAC,0BAA0B,EAAE,OAAO,SAAS,aAAa,MAAM,EAAE,CAAC,CAAC;IACvG,CAAC;CACF;AA/KD,0BA+KC","sourcesContent":["import type { App, CfnElement, StackProps } from \"aws-cdk-lib\";\nimport { Annotations, Aspects, CfnParameter, LegacyStackSynthesizer, Stack, Tags } from \"aws-cdk-lib\";\nimport type { IConstruct } from \"constructs\";\nimport gitUrlParse from \"git-url-parse\";\nimport { CfnIncludeReporter } from \"../../aspects/cfn-include-reporter\";\nimport { CfnParameterReporter } from \"../../aspects/cfn-parameter-reporter\";\nimport { Metadata } from \"../../aspects/metadata\";\nimport { ContextKeys, MetadataKeys, TrackingTag } from \"../../constants\";\nimport { gitRemoteOriginUrl } from \"../../utils/git\";\nimport type { StackStageIdentity } from \"./identity\";\nimport type { GuStaticLogicalId } from \"./migrating\";\n\nexport interface GuStackProps extends Omit<StackProps, \"stackName\"> {\n /**\n * The Guardian stack being used (as defined in your riff-raff.yaml).\n * This will be applied as a tag to all of your resources.\n */\n stack: string;\n\n /**\n * The stage being used (as defined in your riff-raff.yaml).\n * This will be applied as a tag to all of your resources.\n */\n stage: string;\n\n /**\n * Optional name of the app. If defined, all resources will have an App tag.\n */\n app?: string;\n\n /**\n * The name of the Riff-Raff project used to deploy these resources.\n * Used as the value of the `gu:riff-raff-project` tag on all resources.\n * If using {@link GuRoot} or {@link RiffRaffYamlFile}, this value is also used in the location of the generated `riff-raff.yaml`.\n *\n * @see https://github.com/guardian/riffraff-platform\n */\n riffRaffProjectName?: string;\n\n /**\n * The AWS CloudFormation stack name (as shown in the AWS CloudFormation UI).\n * @defaultValue the `GU_CFN_STACK_NAME` environment variable\n */\n cloudFormationStackName?: string;\n /**\n * Set this to true to stop the GuStack from tagging all of your AWS resources.\n * This should only be turned on as part of an initial migration from CloudFormation.\n */\n withoutTags?: boolean;\n\n /**\n * Set to disable CDK metadata. Only for internal use (for disabling for some\n * snapshot tests). We rely on tracking data to prioritise future work so\n * please do not override this.\n */\n withoutMetadata?: boolean;\n}\n\n/**\n * GuStack provides the `stack` and `stage` parameters to a template.\n * It also takes the `app` in the constructor.\n *\n * GuStack will add the Stack, Stage and App tags to all resources.\n *\n * GuStack also adds the tag `X-Gu-CDK-Version`.\n * This tag allows us to measure adoption of this library.\n * It's value is the version of guardian/cdk being used, as defined in `package.json`.\n * As a result, the change sets between version numbers will be fairly noisy,\n * as all resources receive a tag update.\n * It is recommended to upgrade the version of @guardian/cdk being used in two steps:\n * 1. Bump the library, apply the tag updates\n * 2. Make any other stack changes\n *\n * Typical usage is to extend GuStack:\n *\n * ```typescript\n * class MyStack extends GuStack {\n * constructor(scope: App, id: string, props: GuStackProps) {\n * super(scope, id, props)\n * }\n *\n * // add resources here\n * }\n * ```\n */\nexport class GuStack extends Stack implements StackStageIdentity {\n public readonly stack: string;\n public readonly stage: string;\n public readonly app: string | undefined;\n public readonly riffRaffProjectName: string | undefined;\n\n /**\n * The repository name, if it can be determined from the context or the git remote origin url.\n * If it cannot be determined from either of these sources, it will be `undefined`.\n */\n public readonly repositoryName: string | undefined;\n\n /**\n * A helper function to add a tag to all resources in a stack.\n *\n * Note: tags will be listed in alphabetical order during synthesis.\n *\n * @param key the tag name\n * @param value the value of the tag\n * @param applyToLaunchedInstances whether or not to apply the tag to instances launched in an ASG.\n * @protected\n */\n protected addTag(key: string, value: string, applyToLaunchedInstances: boolean = true): void {\n // TODO add validation for `key` and `value`\n // see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html\n Tags.of(this).add(key, value, { applyToLaunchedInstances });\n }\n\n /**\n * Returns all the parameters on this stack.\n *\n * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html\n */\n get parameters(): Record<string, CfnParameter> {\n return this.node\n .findAll()\n .filter((construct) => construct instanceof CfnParameter)\n .reduce((acc, param) => ({ ...acc, [param.node.id]: param as CfnParameter }), {});\n }\n\n // eslint-disable-next-line custom-rules/valid-constructors -- GuStack is the exception as it must take an App\n constructor(scope: App, id: string, props: GuStackProps) {\n const {\n cloudFormationStackName = process.env.GU_CFN_STACK_NAME,\n stack,\n stage,\n app,\n riffRaffProjectName,\n withoutTags,\n } = props;\n\n super(scope, id, {\n ...props,\n stackName: cloudFormationStackName,\n\n // TODO Use `DefaultStackSynthesizer` or create own synthesizer?\n // see https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html#bootstrapping-custom-synth\n synthesizer: new LegacyStackSynthesizer(),\n });\n\n this.stack = stack;\n this.stage = stage.toUpperCase();\n this.app = app;\n this.riffRaffProjectName = riffRaffProjectName;\n this.repositoryName = this.tryGetRepositoryTag();\n\n if (!withoutTags) {\n this.addTag(TrackingTag.Key, TrackingTag.Value);\n\n this.addTag(\"Stack\", this.stack);\n this.addTag(\"Stage\", this.stage);\n if (this.app) {\n this.addTag(\"App\", this.app);\n }\n\n if (this.riffRaffProjectName) {\n this.addTag(\"gu:riff-raff:project\", this.riffRaffProjectName);\n }\n\n if (this.repositoryName) {\n this.addTag(MetadataKeys.REPOSITORY_NAME, this.repositoryName);\n }\n }\n\n if (!props.withoutMetadata) {\n Aspects.of(this).add(new Metadata(this));\n }\n\n Aspects.of(this).add(new CfnIncludeReporter());\n Aspects.of(this).add(new CfnParameterReporter());\n }\n\n /**\n * Returns the repository name.\n * The value is retrieved in the following order:\n * 1. From the context\n * 2. From git config\n *\n * @private\n */\n private tryGetRepositoryTag(): string | undefined {\n try {\n const urlFromContext = this.node.tryGetContext(ContextKeys.REPOSITORY_URL) as string | undefined;\n const repositoryUrl: string = urlFromContext ?? gitRemoteOriginUrl();\n return gitUrlParse(repositoryUrl).full_name;\n } catch {\n console.info(\n `Unable to find git repository name. Set the ${ContextKeys.REPOSITORY_URL} context value or configure a git remote`,\n );\n return undefined;\n }\n }\n\n /**\n * Override the auto-generated logical ID for a resource, in the generated CloudFormation template, with a static one.\n *\n * Of particular use when migrating a JSON/YAML CloudFormation template into GuCDK.\n * It's generally advised to retain the logical ID for stateful resources, such as databases or buckets.\n *\n * Let's say we have a YAML template:\n *\n * ```yaml\n * AWSTemplateFormatVersion: '2010-09-09'\n * Resources:\n * UsesTable:\n * Type: AWS::DynamoDB::Table\n * Properties:\n * TableName: !Sub 'users-${stage}'\n * ```\n *\n * When moving to GuCDK we'll have this:\n *\n * class MyStack extends GuStack {\n * constructor(app: App, id: string, props: GuStackProps) {\n * super(app, id, props);\n *\n * const { stage } = this;\n *\n * new Table(this, \"UsersTable\", {\n * name: `users-${stage}`\n * });\n * }\n * }\n *\n * During synthesis, CDK auto-generates logical IDs, so we'll have a stack with a DynamoDB table named 'UsersTable<SOME GUID>', NOT `UsersTable`.\n * That is, the `UsersTable` table will be deleted.\n *\n * In order to retain the original ID from the YAML template, we will do:\n *\n * class MyStack extends GuStack {\n * constructor(app: App, id: string, props: GuStackProps) {\n * super(app, id, props);\n *\n * const { stage } = this;\n *\n * const table = new Table(this, \"UsersTable\", {\n * name: `users-${stage}`\n * });\n *\n * this.overrideLogicalId(table, { logicalId: \"UsersTable\", reason: \"Retaining a stateful resource from the YAML template\" });\n * }\n * }\n *\n * @param construct The (stateful) resource to retain the logical ID of.\n * @param logicalId The logical ID of the resource (as defined in the JSON/YAML template.\n * @param reason A small explanation to keep the logical ID. Mainly used to help future developers.\n */\n public overrideLogicalId(construct: IConstruct, { logicalId, reason }: GuStaticLogicalId): void {\n const {\n node: { id, defaultChild },\n } = construct;\n\n (defaultChild as CfnElement).overrideLogicalId(logicalId);\n Annotations.of(construct).addInfo(`Setting logical ID for ${id} to ${logicalId}. Reason: ${reason}`);\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/riff-raff-yaml-file/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAuBvC,OAAO,KAAK,EAMV,mBAAmB,EACnB,YAAY,EAGb,MAAM,SAAS,CAAC;AA+BjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAEhC;;;;;;;OAOG;IACH,SAAgB,aAAa,EAAE,GAAG,CAAC,mBAAmB,EAAE,YAAY,CAAC,CAAC;gBAG1D,GAAG,EAAE,GAAG;IA6IpB;;;;;OAKG;IACH,MAAM,CAAC,mBAAmB,GAAE,mBAAgD,GAAG,MAAM;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/riff-raff-yaml-file/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAuBvC,OAAO,KAAK,EAMV,mBAAmB,EACnB,YAAY,EAGb,MAAM,SAAS,CAAC;AA+BjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAEhC;;;;;;;OAOG;IACH,SAAgB,aAAa,EAAE,GAAG,CAAC,mBAAmB,EAAE,YAAY,CAAC,CAAC;gBAG1D,GAAG,EAAE,GAAG;IA6IpB;;;;;OAKG;IACH,MAAM,CAAC,mBAAmB,GAAE,mBAAgD,GAAG,MAAM;IAgCrF;;OAEG;IACH,KAAK,IAAI,IAAI;CAed;AAED,wBAAgB,6BAA6B,CAAC,QAAQ,EAAE,MAAM,EAAE,mBAAmB,EAAE,mBAAmB,GAAG,MAAM,CAahH"}
|
|
@@ -204,7 +204,14 @@ class RiffRaffYamlFile {
|
|
|
204
204
|
if (!content) {
|
|
205
205
|
throw new Error(`No Riff-Raff project found with name: ${riffRaffProjectName}`);
|
|
206
206
|
}
|
|
207
|
-
|
|
207
|
+
const yaml = (0, js_yaml_1.dump)(content, { replacer });
|
|
208
|
+
const comments = [
|
|
209
|
+
"This file was generated by @guardian/cdk, do not edit it directly.",
|
|
210
|
+
"See also https://github.com/guardian/cdk/blob/main/src/riff-raff-yaml-file/README.md.",
|
|
211
|
+
]
|
|
212
|
+
.map((line) => `# ${line}`)
|
|
213
|
+
.join("\n");
|
|
214
|
+
return [comments, yaml].join("\n");
|
|
208
215
|
}
|
|
209
216
|
/**
|
|
210
217
|
* Write the `riff-raff.yaml` file(s) to disk, located in the same directory as the CFN JSON templates generated by `cdk synth`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/riff-raff-yaml-file/index.ts"],"names":[],"mappings":";;;;;;AAAA,2BAA0D;AAC1D,gDAAwB;AAExB,6CAAoC;AAEpC,qCAA+B;AAC/B,2DAA+D;AAC/D,6CAA6C;AAC7C,iDAAwD;AACxD,8DAAmG;AACnG,2DAA6F;AAC7F,iEAIsC;AACtC,iDAAoF;AACpF,uEAA6E;AAC7E,yCAMoB;AAYpB,mCAAqD;AAErD,SAAS,6BAA6B,CAAC,OAAiB;IACtD,MAAM,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,mBAAK,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC;IAE1E,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE;QAC3B,MAAM,IAAI,KAAK,CAAC,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Y,GAAG,cAAI,CAAC,QAAQ,CAAC,YAAY,EAAE,YAAY,CAAC,CAAC;IAC/D,MAAM,SAAS,GAAG,YAAY,KAAK,IAAI,IAAI,YAAY,CAAC,UAAU,CAAC,KAAK,cAAI,CAAC,GAAG,EAAE,CAAC,IAAI,cAAI,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC;IAErH,IAAI,SAAS,EAAE;QACb,MAAM,IAAI,KAAK,CACb,kCAAkC,mBAAmB,yCAAyC,QAAQ,yBAAyB,mBAAmB,mBAAmB,YAAY,oBAAoB,YAAY,IAAI,CACtN,CAAC;KACH;IAED,OAAO,YAAY,CAAC;AACtB,CAAC;AAbD,sEAaC","sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from \"fs\";\nimport path from \"path\";\nimport type { App } from \"aws-cdk-lib\";\nimport { Token } from \"aws-cdk-lib\";\nimport type { CfnAutoScalingGroup } from \"aws-cdk-lib/aws-autoscaling\";\nimport { dump } from \"js-yaml\";\nimport { GuAutoScalingGroup } from \"../constructs/autoscaling\";\nimport { GuStack } from \"../constructs/core\";\nimport { GuLambdaFunction } from \"../constructs/lambda\";\nimport { GuAsgMinInstancesInServiceParameterExperimental } from \"../experimental/patterns/ec2-app\";\nimport { autoscalingDeployment, uploadAutoscalingArtifact } from \"./deployments/autoscaling\";\nimport {\n cloudFormationDeployment,\n getAmiParameters,\n getMinInstancesInServiceParameters,\n} from \"./deployments/cloudformation\";\nimport { updateLambdaDeployment, uploadLambdaArtifact } from \"./deployments/lambda\";\nimport { updateDeploymentParameters } from \"./deployments/update-parameters\";\nimport {\n groupByClassName,\n groupByRegion,\n groupByRiffRaffProjectName,\n groupByStackTag,\n groupByStageTag,\n} from \"./group-by\";\nimport type {\n ClassName,\n Region,\n RiffRaffDeployment,\n RiffRaffDeploymentName,\n RiffRaffDeploymentProps,\n RiffRaffProjectName,\n RiffRaffYaml,\n StackTag,\n StageTag,\n} from \"./types\";\nimport { UnknownRiffRaffProjectName } from \"./types\";\n\nfunction validateAllRegionsAreResolved(regions: Region[]): void {\n const unresolved = regions.filter((region) => Token.isUnresolved(region));\n\n if (unresolved.length !== 0) {\n throw new Error(`Unable to produce a working riff-raff.yaml file; all stacks must have an explicit region set`);\n }\n}\n\nfunction getLambdas(cdkStack: GuStack): GuLambdaFunction[] {\n return cdkStack.node.findAll().filter((_) => _ instanceof GuLambdaFunction) as GuLambdaFunction[];\n}\n\nfunction getAutoScalingGroups(cdkStack: GuStack): GuAutoScalingGroup[] {\n return cdkStack.node.findAll().filter((_) => _ instanceof GuAutoScalingGroup) as GuAutoScalingGroup[];\n}\n\nfunction getGuStackDependencies(cdkStack: GuStack): GuStack[] {\n return cdkStack.dependencies.filter((_) => _ instanceof GuStack) as GuStack[];\n}\n\ninterface MissingStack {\n riffRaffProjectName: RiffRaffProjectName;\n className: ClassName;\n stack: StackTag;\n stage: StageTag;\n region: Region;\n}\n\n/**\n * A class that creates a `riff-raff.yaml` file.\n *\n * Rather than using this directly, prefer to use [[`GuRoot`]] instead.\n *\n * Supports:\n * - Multiple CloudFormation stacks\n * - Multiple regions\n * - Lambda applications\n * - EC2 (autoscaling) applications\n *\n * For lambda applications, 3 deployments will be defined:\n * 1. Lambda upload (`aws-lambda`, `action: [uploadLambda]`)\n * 2. CloudFormation deploy (`cloud-formation`)\n * 3. Lambda update (`aws-lambda`, `action: [updateLambda]`)\n *\n * For EC2 applications, 3 deployments will be defined:\n * 1. Artifact upload (`autoscaling`, `action: [uploadArtifacts]`)\n * 2. CloudFormation deploy (`cloud-formation`)\n * 3. Autoscaling deploy (`autoscaling`, `action: [deploy]`)\n *\n * It assumes a Riff-Raff bundle structure as follows:\n *\n * ```\n * .\n * ├── cdk.out\n * │ └── MyApplication.template.json\n * ├── my-application\n * │ └── my-application.deb\n * └── my-lambda\n * └── my-lambda.zip\n * ```\n *\n * That is, all CloudFormation templates are in a `cdk.out` directory, and there is a directory per app.\n * Application artifact(s) are in the app directory.\n *\n * NOTE: The file extension is decided by you, the above file tree is used for illustration purposes.\n *\n * NOTE: Resources will be looked up by tags (Stack, Stage, App). Ensure your CFN stack is tagged appropriately!\n *\n * @see https://riffraff.gutools.co.uk/docs/reference/riff-raff.yaml.md\n * @see https://riffraff.gutools.co.uk/docs/magenta-lib/types\n */\nexport class RiffRaffYamlFile {\n private readonly outdir: string;\n\n /**\n * A mapping between a Riff-Raff project and `riff-raff.yaml` content as an object.\n *\n * It is useful for specifying additional deployment types that GuCDK does not support.\n * Consider raising an issue or pull request if you think it should be supported.\n *\n * @see https://riffraff.gutools.co.uk/docs/magenta-lib/types\n */\n public readonly configuration: Map<RiffRaffProjectName, RiffRaffYaml>;\n\n // eslint-disable-next-line custom-rules/valid-constructors -- this needs to sit above GuStack on the cdk tree\n constructor(app: App) {\n const allCdkStacks = app.node.findAll().filter((_) => _ instanceof GuStack) as GuStack[];\n const allRegions = Array.from(new Set(allCdkStacks.map((_) => _.region)));\n\n validateAllRegionsAreResolved(allRegions);\n\n this.outdir = app.outdir;\n const configuration = new Map<RiffRaffProjectName, RiffRaffYaml>();\n const missingStacks: MissingStack[] = [];\n\n Object.entries(groupByRiffRaffProjectName(allCdkStacks)).forEach(\n ([riffRaffProjectName, stacksGroupedByRiffRaffProject]) => {\n const allowedStages = new Set(stacksGroupedByRiffRaffProject.map((_) => _.stage));\n const requiredStages = Array.from(allowedStages);\n const deployments = new Map<RiffRaffDeploymentName, RiffRaffDeploymentProps>();\n\n Object.entries(groupByClassName(stacksGroupedByRiffRaffProject)).forEach(\n ([className, stacksGroupedByClassName]) => {\n Object.entries(groupByStackTag(stacksGroupedByClassName)).forEach(([stackTag, stacksGroupedByStackTag]) => {\n Object.entries(groupByRegion(stacksGroupedByStackTag)).forEach(([region, stacksGroupedByRegion]) => {\n const stacks: GuStack[] = Object.values(groupByStageTag(stacksGroupedByRegion)).flat();\n\n requiredStages.forEach((requiredStage) => {\n if (!stacks.find(({ stage }) => stage === requiredStage)) {\n missingStacks.push({\n riffRaffProjectName,\n className,\n region,\n stack: stackTag,\n stage: requiredStage,\n });\n }\n });\n\n // The items in `stacks` only differ by stage, so we can just use the first item in the list.\n const [stack] = stacks;\n\n if (!stack) {\n throw new Error(\"Unable to produce a working riff-raff.yaml file; there are no stacks!\");\n }\n\n const lambdas = getLambdas(stack);\n const autoscalingGroups = getAutoScalingGroups(stack);\n\n const artifactUploads: RiffRaffDeployment[] = [\n lambdas.filter((_) => !_.withoutArtifactUpload).map(uploadLambdaArtifact),\n autoscalingGroups.map(uploadAutoscalingArtifact),\n ].flat();\n artifactUploads.forEach(({ name, props }) => deployments.set(name, props));\n\n const parentStacks: RiffRaffDeployment[] = getGuStackDependencies(stack).map((x) =>\n cloudFormationDeployment([x], [], this.outdir),\n );\n\n const cfnDeployment = cloudFormationDeployment(\n stacks,\n [...artifactUploads, ...parentStacks],\n this.outdir,\n );\n deployments.set(cfnDeployment.name, cfnDeployment.props);\n\n const lambdasWithoutAnAlias = lambdas.filter((lambda) => lambda.alias === undefined);\n // If the Lambda has an alias it is using versioning. When using versioning, there is no need for Riff-Raff\n // to modify the unpublished version of the function\n lambdasWithoutAnAlias.forEach((lambda) => {\n const lambdaDeployment = updateLambdaDeployment(lambda, cfnDeployment);\n deployments.set(lambdaDeployment.name, lambdaDeployment.props);\n });\n\n /*\n Instances in an ASG with an `AutoScalingRollingUpdate` update policy are rotated via CloudFormation.\n Therefore, they do not need to also perform an `autoscaling` deployment via Riff-Raff.\n */\n const legacyAutoscalingGroups = autoscalingGroups.filter((asg) => {\n const { cfnOptions } = asg.node.defaultChild as CfnAutoScalingGroup;\n const { updatePolicy } = cfnOptions;\n return updatePolicy?.autoScalingRollingUpdate === undefined;\n });\n\n legacyAutoscalingGroups.forEach((asg) => {\n const asgDeployment = autoscalingDeployment(asg, cfnDeployment);\n deployments.set(asgDeployment.name, asgDeployment.props);\n });\n\n // only add the `amiParametersToTags` property if there are some ASGs in the stack\n if (autoscalingGroups.length > 0) {\n updateDeploymentParameters(deployments, cfnDeployment, {\n amiParametersToTags: getAmiParameters(autoscalingGroups),\n });\n }\n\n /*\n At this point, `stacks` is a collection of similar `GuStack`s that differ only by their `stage`.\n We're about to add `minInstancesInServiceParameters` to assist Riff-Raff when deploying ASGs with scaling policies.\n This is driven by the presence of conditionally added CFN Parameters.\n To support the possibility of there being a scaling policy in PROD but not CODE, look at all the CFN Parameters in `stacks`.\n */\n const minInstancesInServiceParameters: Map<string, GuAsgMinInstancesInServiceParameterExperimental> =\n stacks\n .flatMap((stack) => Object.values(stack.parameters))\n .filter(\n (_): _ is GuAsgMinInstancesInServiceParameterExperimental =>\n _ instanceof GuAsgMinInstancesInServiceParameterExperimental,\n )\n .reduce((acc, item) => {\n if (!acc.has(item.node.id)) {\n acc.set(item.node.id, item);\n }\n return acc;\n }, new Map<string, GuAsgMinInstancesInServiceParameterExperimental>());\n\n /**\n * Only add the `minInstancesInServiceParameters` property if there are some ASGs affected by {@link GuHorizontallyScalingDeploymentPropertiesExperimental}.\n */\n if (minInstancesInServiceParameters.size > 0) {\n updateDeploymentParameters(deployments, cfnDeployment, {\n minInstancesInServiceParameters: getMinInstancesInServiceParameters(\n minInstancesInServiceParameters,\n ),\n });\n }\n });\n });\n },\n );\n\n configuration.set(riffRaffProjectName, { allowedStages, deployments });\n },\n );\n\n if (missingStacks.length > 0) {\n const message = `Unable to produce a working riff-raff.yaml file; missing ${missingStacks.length} definitions`;\n console.log(`${message} (details below)`);\n console.table(missingStacks);\n\n throw new Error(message);\n }\n\n this.configuration = configuration;\n }\n\n /**\n * A `riff-raff.yaml` file as a string.\n * Useful for testing.\n *\n * @param riffRaffProjectName which project to convert to YAML. Defaults to {@link UnknownRiffRaffProjectName} - any {@link GuStack} without an explicit `riffRaffProjectName` property.\n */\n toYAML(riffRaffProjectName: RiffRaffProjectName = UnknownRiffRaffProjectName): string {\n // Add support for ES6 Set and Map. See https://github.com/nodeca/js-yaml/issues/436.\n const replacer = (_key: string, value: unknown) => {\n if (value instanceof Set) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return -- this is how `js-yaml` is typed\n return Array.from(value);\n }\n if (value instanceof Map) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return -- this is how `js-yaml` is typed\n return Object.fromEntries(value);\n }\n return value;\n };\n\n const content = this.configuration.get(riffRaffProjectName);\n\n if (!content) {\n throw new Error(`No Riff-Raff project found with name: ${riffRaffProjectName}`);\n }\n\n return dump(content, { replacer });\n }\n\n /**\n * Write the `riff-raff.yaml` file(s) to disk, located in the same directory as the CFN JSON templates generated by `cdk synth`.\n */\n synth(): void {\n this.configuration.forEach((_, riffRaffProjectName) => {\n const targetDirectory =\n riffRaffProjectName === UnknownRiffRaffProjectName\n ? this.outdir\n : validateRiffRaffYamlDirectory(this.outdir, riffRaffProjectName);\n\n if (!existsSync(targetDirectory)) {\n mkdirSync(targetDirectory, { recursive: true });\n }\n\n const outPath = path.join(targetDirectory, \"riff-raff.yaml\");\n writeFileSync(outPath, this.toYAML(riffRaffProjectName));\n });\n }\n}\n\nexport function validateRiffRaffYamlDirectory(basePath: string, riffRaffProjectName: RiffRaffProjectName): string {\n const resolvedBase = path.resolve(basePath);\n const resolvedPath = path.resolve(basePath, riffRaffProjectName);\n const relativePath = path.relative(resolvedBase, resolvedPath);\n const isOutside = relativePath === \"..\" || relativePath.startsWith(`..${path.sep}`) || path.isAbsolute(relativePath);\n\n if (isOutside) {\n throw new Error(\n `Directory traversal detected: '${riffRaffProjectName}' would create a directory outside of ${basePath} (riffRaffProjectName=${riffRaffProjectName}, resolvedPath='${resolvedPath}', resolvedBase='${resolvedBase}')`,\n );\n }\n\n return resolvedPath;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/riff-raff-yaml-file/index.ts"],"names":[],"mappings":";;;;;;AAAA,2BAA0D;AAC1D,gDAAwB;AAExB,6CAAoC;AAEpC,qCAA+B;AAC/B,2DAA+D;AAC/D,6CAA6C;AAC7C,iDAAwD;AACxD,8DAAmG;AACnG,2DAA6F;AAC7F,iEA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CAAC,IAAA,eAAU,EAAC,eAAe,CAAC,EAAE;gBAChC,IAAA,cAAS,EAAC,eAAe,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;aACjD;YAED,MAAM,OAAO,GAAG,cAAI,CAAC,IAAI,CAAC,eAAe,EAAE,gBAAgB,CAAC,CAAC;YAC7D,IAAA,kBAAa,EAAC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,mBAAmB,CAAC,CAAC,CAAC;QAC3D,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAnND,4CAmNC;AAED,SAAgB,6BAA6B,CAAC,QAAgB,EAAE,mBAAwC;IACtG,MAAM,YAAY,GAAG,cAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IAC5C,MAAM,YAAY,GAAG,cAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,mBAAmB,CAAC,CAAC;IACjE,MAAM,YAAY,GAAG,cAAI,CAAC,QAAQ,CAAC,YAAY,EAAE,YAAY,CAAC,CAAC;IAC/D,MAAM,SAAS,GAAG,YAAY,KAAK,IAAI,IAAI,YAAY,CAAC,UAAU,CAAC,KAAK,cAAI,CAAC,GAAG,EAAE,CAAC,IAAI,cAAI,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC;IAErH,IAAI,SAAS,EAAE;QACb,MAAM,IAAI,KAAK,CACb,kCAAkC,mBAAmB,yCAAyC,QAAQ,yBAAyB,mBAAmB,mBAAmB,YAAY,oBAAoB,YAAY,IAAI,CACtN,CAAC;KACH;IAED,OAAO,YAAY,CAAC;AACtB,CAAC;AAbD,sEAaC","sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from \"fs\";\nimport path from \"path\";\nimport type { App } from \"aws-cdk-lib\";\nimport { Token } from \"aws-cdk-lib\";\nimport type { CfnAutoScalingGroup } from \"aws-cdk-lib/aws-autoscaling\";\nimport { dump } from \"js-yaml\";\nimport { GuAutoScalingGroup } from \"../constructs/autoscaling\";\nimport { GuStack } from \"../constructs/core\";\nimport { GuLambdaFunction } from \"../constructs/lambda\";\nimport { GuAsgMinInstancesInServiceParameterExperimental } from \"../experimental/patterns/ec2-app\";\nimport { autoscalingDeployment, uploadAutoscalingArtifact } from \"./deployments/autoscaling\";\nimport {\n cloudFormationDeployment,\n getAmiParameters,\n getMinInstancesInServiceParameters,\n} from \"./deployments/cloudformation\";\nimport { updateLambdaDeployment, uploadLambdaArtifact } from \"./deployments/lambda\";\nimport { updateDeploymentParameters } from \"./deployments/update-parameters\";\nimport {\n groupByClassName,\n groupByRegion,\n groupByRiffRaffProjectName,\n groupByStackTag,\n groupByStageTag,\n} from \"./group-by\";\nimport type {\n ClassName,\n Region,\n RiffRaffDeployment,\n RiffRaffDeploymentName,\n RiffRaffDeploymentProps,\n RiffRaffProjectName,\n RiffRaffYaml,\n StackTag,\n StageTag,\n} from \"./types\";\nimport { UnknownRiffRaffProjectName } from \"./types\";\n\nfunction validateAllRegionsAreResolved(regions: Region[]): void {\n const unresolved = regions.filter((region) => Token.isUnresolved(region));\n\n if (unresolved.length !== 0) {\n throw new Error(`Unable to produce a working riff-raff.yaml file; all stacks must have an explicit region set`);\n }\n}\n\nfunction getLambdas(cdkStack: GuStack): GuLambdaFunction[] {\n return cdkStack.node.findAll().filter((_) => _ instanceof GuLambdaFunction) as GuLambdaFunction[];\n}\n\nfunction getAutoScalingGroups(cdkStack: GuStack): GuAutoScalingGroup[] {\n return cdkStack.node.findAll().filter((_) => _ instanceof GuAutoScalingGroup) as GuAutoScalingGroup[];\n}\n\nfunction getGuStackDependencies(cdkStack: GuStack): GuStack[] {\n return cdkStack.dependencies.filter((_) => _ instanceof GuStack) as GuStack[];\n}\n\ninterface MissingStack {\n riffRaffProjectName: RiffRaffProjectName;\n className: ClassName;\n stack: StackTag;\n stage: StageTag;\n region: Region;\n}\n\n/**\n * A class that creates a `riff-raff.yaml` file.\n *\n * Rather than using this directly, prefer to use [[`GuRoot`]] instead.\n *\n * Supports:\n * - Multiple CloudFormation stacks\n * - Multiple regions\n * - Lambda applications\n * - EC2 (autoscaling) applications\n *\n * For lambda applications, 3 deployments will be defined:\n * 1. Lambda upload (`aws-lambda`, `action: [uploadLambda]`)\n * 2. CloudFormation deploy (`cloud-formation`)\n * 3. Lambda update (`aws-lambda`, `action: [updateLambda]`)\n *\n * For EC2 applications, 3 deployments will be defined:\n * 1. Artifact upload (`autoscaling`, `action: [uploadArtifacts]`)\n * 2. CloudFormation deploy (`cloud-formation`)\n * 3. Autoscaling deploy (`autoscaling`, `action: [deploy]`)\n *\n * It assumes a Riff-Raff bundle structure as follows:\n *\n * ```\n * .\n * ├── cdk.out\n * │ └── MyApplication.template.json\n * ├── my-application\n * │ └── my-application.deb\n * └── my-lambda\n * └── my-lambda.zip\n * ```\n *\n * That is, all CloudFormation templates are in a `cdk.out` directory, and there is a directory per app.\n * Application artifact(s) are in the app directory.\n *\n * NOTE: The file extension is decided by you, the above file tree is used for illustration purposes.\n *\n * NOTE: Resources will be looked up by tags (Stack, Stage, App). Ensure your CFN stack is tagged appropriately!\n *\n * @see https://riffraff.gutools.co.uk/docs/reference/riff-raff.yaml.md\n * @see https://riffraff.gutools.co.uk/docs/magenta-lib/types\n */\nexport class RiffRaffYamlFile {\n private readonly outdir: string;\n\n /**\n * A mapping between a Riff-Raff project and `riff-raff.yaml` content as an object.\n *\n * It is useful for specifying additional deployment types that GuCDK does not support.\n * Consider raising an issue or pull request if you think it should be supported.\n *\n * @see https://riffraff.gutools.co.uk/docs/magenta-lib/types\n */\n public readonly configuration: Map<RiffRaffProjectName, RiffRaffYaml>;\n\n // eslint-disable-next-line custom-rules/valid-constructors -- this needs to sit above GuStack on the cdk tree\n constructor(app: App) {\n const allCdkStacks = app.node.findAll().filter((_) => _ instanceof GuStack) as GuStack[];\n const allRegions = Array.from(new Set(allCdkStacks.map((_) => _.region)));\n\n validateAllRegionsAreResolved(allRegions);\n\n this.outdir = app.outdir;\n const configuration = new Map<RiffRaffProjectName, RiffRaffYaml>();\n const missingStacks: MissingStack[] = [];\n\n Object.entries(groupByRiffRaffProjectName(allCdkStacks)).forEach(\n ([riffRaffProjectName, stacksGroupedByRiffRaffProject]) => {\n const allowedStages = new Set(stacksGroupedByRiffRaffProject.map((_) => _.stage));\n const requiredStages = Array.from(allowedStages);\n const deployments = new Map<RiffRaffDeploymentName, RiffRaffDeploymentProps>();\n\n Object.entries(groupByClassName(stacksGroupedByRiffRaffProject)).forEach(\n ([className, stacksGroupedByClassName]) => {\n Object.entries(groupByStackTag(stacksGroupedByClassName)).forEach(([stackTag, stacksGroupedByStackTag]) => {\n Object.entries(groupByRegion(stacksGroupedByStackTag)).forEach(([region, stacksGroupedByRegion]) => {\n const stacks: GuStack[] = Object.values(groupByStageTag(stacksGroupedByRegion)).flat();\n\n requiredStages.forEach((requiredStage) => {\n if (!stacks.find(({ stage }) => stage === requiredStage)) {\n missingStacks.push({\n riffRaffProjectName,\n className,\n region,\n stack: stackTag,\n stage: requiredStage,\n });\n }\n });\n\n // The items in `stacks` only differ by stage, so we can just use the first item in the list.\n const [stack] = stacks;\n\n if (!stack) {\n throw new Error(\"Unable to produce a working riff-raff.yaml file; there are no stacks!\");\n }\n\n const lambdas = getLambdas(stack);\n const autoscalingGroups = getAutoScalingGroups(stack);\n\n const artifactUploads: RiffRaffDeployment[] = [\n lambdas.filter((_) => !_.withoutArtifactUpload).map(uploadLambdaArtifact),\n autoscalingGroups.map(uploadAutoscalingArtifact),\n ].flat();\n artifactUploads.forEach(({ name, props }) => deployments.set(name, props));\n\n const parentStacks: RiffRaffDeployment[] = getGuStackDependencies(stack).map((x) =>\n cloudFormationDeployment([x], [], this.outdir),\n );\n\n const cfnDeployment = cloudFormationDeployment(\n stacks,\n [...artifactUploads, ...parentStacks],\n this.outdir,\n );\n deployments.set(cfnDeployment.name, cfnDeployment.props);\n\n const lambdasWithoutAnAlias = lambdas.filter((lambda) => lambda.alias === undefined);\n // If the Lambda has an alias it is using versioning. When using versioning, there is no need for Riff-Raff\n // to modify the unpublished version of the function\n lambdasWithoutAnAlias.forEach((lambda) => {\n const lambdaDeployment = updateLambdaDeployment(lambda, cfnDeployment);\n deployments.set(lambdaDeployment.name, lambdaDeployment.props);\n });\n\n /*\n Instances in an ASG with an `AutoScalingRollingUpdate` update policy are rotated via CloudFormation.\n Therefore, they do not need to also perform an `autoscaling` deployment via Riff-Raff.\n */\n const legacyAutoscalingGroups = autoscalingGroups.filter((asg) => {\n const { cfnOptions } = asg.node.defaultChild as CfnAutoScalingGroup;\n const { updatePolicy } = cfnOptions;\n return updatePolicy?.autoScalingRollingUpdate === undefined;\n });\n\n legacyAutoscalingGroups.forEach((asg) => {\n const asgDeployment = autoscalingDeployment(asg, cfnDeployment);\n deployments.set(asgDeployment.name, asgDeployment.props);\n });\n\n // only add the `amiParametersToTags` property if there are some ASGs in the stack\n if (autoscalingGroups.length > 0) {\n updateDeploymentParameters(deployments, cfnDeployment, {\n amiParametersToTags: getAmiParameters(autoscalingGroups),\n });\n }\n\n /*\n At this point, `stacks` is a collection of similar `GuStack`s that differ only by their `stage`.\n We're about to add `minInstancesInServiceParameters` to assist Riff-Raff when deploying ASGs with scaling policies.\n This is driven by the presence of conditionally added CFN Parameters.\n To support the possibility of there being a scaling policy in PROD but not CODE, look at all the CFN Parameters in `stacks`.\n */\n const minInstancesInServiceParameters: Map<string, GuAsgMinInstancesInServiceParameterExperimental> =\n stacks\n .flatMap((stack) => Object.values(stack.parameters))\n .filter(\n (_): _ is GuAsgMinInstancesInServiceParameterExperimental =>\n _ instanceof GuAsgMinInstancesInServiceParameterExperimental,\n )\n .reduce((acc, item) => {\n if (!acc.has(item.node.id)) {\n acc.set(item.node.id, item);\n }\n return acc;\n }, new Map<string, GuAsgMinInstancesInServiceParameterExperimental>());\n\n /**\n * Only add the `minInstancesInServiceParameters` property if there are some ASGs affected by {@link GuHorizontallyScalingDeploymentPropertiesExperimental}.\n */\n if (minInstancesInServiceParameters.size > 0) {\n updateDeploymentParameters(deployments, cfnDeployment, {\n minInstancesInServiceParameters: getMinInstancesInServiceParameters(\n minInstancesInServiceParameters,\n ),\n });\n }\n });\n });\n },\n );\n\n configuration.set(riffRaffProjectName, { allowedStages, deployments });\n },\n );\n\n if (missingStacks.length > 0) {\n const message = `Unable to produce a working riff-raff.yaml file; missing ${missingStacks.length} definitions`;\n console.log(`${message} (details below)`);\n console.table(missingStacks);\n\n throw new Error(message);\n }\n\n this.configuration = configuration;\n }\n\n /**\n * A `riff-raff.yaml` file as a string.\n * Useful for testing.\n *\n * @param riffRaffProjectName which project to convert to YAML. Defaults to {@link UnknownRiffRaffProjectName} - any {@link GuStack} without an explicit `riffRaffProjectName` property.\n */\n toYAML(riffRaffProjectName: RiffRaffProjectName = UnknownRiffRaffProjectName): string {\n // Add support for ES6 Set and Map. See https://github.com/nodeca/js-yaml/issues/436.\n const replacer = (_key: string, value: unknown) => {\n if (value instanceof Set) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return -- this is how `js-yaml` is typed\n return Array.from(value);\n }\n if (value instanceof Map) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return -- this is how `js-yaml` is typed\n return Object.fromEntries(value);\n }\n return value;\n };\n\n const content = this.configuration.get(riffRaffProjectName);\n\n if (!content) {\n throw new Error(`No Riff-Raff project found with name: ${riffRaffProjectName}`);\n }\n\n const yaml = dump(content, { replacer });\n\n const comments = [\n \"This file was generated by @guardian/cdk, do not edit it directly.\",\n \"See also https://github.com/guardian/cdk/blob/main/src/riff-raff-yaml-file/README.md.\",\n ]\n .map((line) => `# ${line}`)\n .join(\"\\n\");\n\n return [comments, yaml].join(\"\\n\");\n }\n\n /**\n * Write the `riff-raff.yaml` file(s) to disk, located in the same directory as the CFN JSON templates generated by `cdk synth`.\n */\n synth(): void {\n this.configuration.forEach((_, riffRaffProjectName) => {\n const targetDirectory =\n riffRaffProjectName === UnknownRiffRaffProjectName\n ? this.outdir\n : validateRiffRaffYamlDirectory(this.outdir, riffRaffProjectName);\n\n if (!existsSync(targetDirectory)) {\n mkdirSync(targetDirectory, { recursive: true });\n }\n\n const outPath = path.join(targetDirectory, \"riff-raff.yaml\");\n writeFileSync(outPath, this.toYAML(riffRaffProjectName));\n });\n }\n}\n\nexport function validateRiffRaffYamlDirectory(basePath: string, riffRaffProjectName: RiffRaffProjectName): string {\n const resolvedBase = path.resolve(basePath);\n const resolvedPath = path.resolve(basePath, riffRaffProjectName);\n const relativePath = path.relative(resolvedBase, resolvedPath);\n const isOutside = relativePath === \"..\" || relativePath.startsWith(`..${path.sep}`) || path.isAbsolute(relativePath);\n\n if (isOutside) {\n throw new Error(\n `Directory traversal detected: '${riffRaffProjectName}' would create a directory outside of ${basePath} (riffRaffProjectName=${riffRaffProjectName}, resolvedPath='${resolvedPath}', resolvedBase='${resolvedBase}')`,\n );\n }\n\n return resolvedPath;\n}\n"]}
|