@aws-cdk/core
Version:
AWS Cloud Development Kit Core Library
1,122 lines • 147 kB
JavaScript
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.rootPathTo = exports.Stack = exports.STACK_RESOURCE_LIMIT_CONTEXT = void 0;
const jsiiDeprecationWarnings = require("../.warnings.jsii.js");
const JSII_RTTI_SYMBOL_1 = Symbol.for("jsii.rtti");
const fs = require("fs");
const path = require("path");
const cxschema = require("@aws-cdk/cloud-assembly-schema");
const cxapi = require("@aws-cdk/cx-api");
const constructs_1 = require("constructs");
const minimatch = require("minimatch");
const annotations_1 = require("./annotations");
const app_1 = require("./app");
const arn_1 = require("./arn");
const cfn_element_1 = require("./cfn-element");
const cfn_fn_1 = require("./cfn-fn");
const cfn_pseudo_1 = require("./cfn-pseudo");
const cfn_resource_1 = require("./cfn-resource");
const context_provider_1 = require("./context-provider");
const feature_flags_1 = require("./feature-flags");
const cloudformation_lang_1 = require("./private/cloudformation-lang");
const logical_id_1 = require("./private/logical-id");
const resolve_1 = require("./private/resolve");
const uniqueid_1 = require("./private/uniqueid");
// v2 - keep this import as a separate section to reduce merge conflict when forward merging with the v2 branch.
// eslint-disable-next-line
const construct_compat_1 = require("./construct-compat");
const STACK_SYMBOL = Symbol.for('@aws-cdk/core.Stack');
const MY_STACK_CACHE = Symbol.for('@aws-cdk/core.Stack.myStack');
exports.STACK_RESOURCE_LIMIT_CONTEXT = '@aws-cdk/core:stackResourceLimit';
const VALID_STACK_NAME_REGEX = /^[A-Za-z][A-Za-z0-9-]*$/;
const MAX_RESOURCES = 500;
/**
* A root construct which represents a single CloudFormation stack.
*/
class Stack extends construct_compat_1.Construct {
/**
* Creates a new stack.
*
* @param scope Parent of this stack, usually an `App` or a `Stage`, but could be any construct.
* @param id The construct ID of this stack. If `stackName` is not explicitly
* defined, this id (and any parent IDs) will be used to determine the
* physical ID of the stack.
* @param props Stack properties.
*/
constructor(scope, id, props = {}) {
try {
jsiiDeprecationWarnings._aws_cdk_core_StackProps(props);
}
catch (error) {
if (process.env.JSII_DEBUG !== "1" && error.name === "DeprecationError") {
Error.captureStackTrace(error, Stack);
}
throw error;
}
// For unit test scope and id are optional for stacks, but we still want an App
// as the parent because apps implement much of the synthesis logic.
scope = scope ?? new app_1.App({
autoSynth: false,
outdir: fs_1.FileSystem.mkdtemp('cdk-test-app-'),
});
// "Default" is a "hidden id" from a `node.uniqueId` perspective
id = id ?? 'Default';
super(scope, id);
this._missingContext = new Array();
this._stackDependencies = {};
this.templateOptions = {};
Object.defineProperty(this, STACK_SYMBOL, { value: true });
this._logicalIds = new logical_id_1.LogicalIDs();
const { account, region, environment } = this.parseEnvironment(props.env);
this.account = account;
this.region = region;
this.environment = environment;
this.terminationProtection = props.terminationProtection;
if (props.description !== undefined) {
// Max length 1024 bytes
// Typically 2 bytes per character, may be more for more exotic characters
if (props.description.length > 512) {
throw new Error(`Stack description must be <= 1024 bytes. Received description: '${props.description}'`);
}
this.templateOptions.description = props.description;
}
this._stackName = props.stackName ?? this.generateStackName();
if (this._stackName.length > 128) {
throw new Error(`Stack name must be <= 128 characters. Stack name: '${this._stackName}'`);
}
this.tags = new tag_manager_1.TagManager(cfn_resource_1.TagType.KEY_VALUE, 'aws:cdk:stack', props.tags);
if (!VALID_STACK_NAME_REGEX.test(this.stackName)) {
throw new Error(`Stack name must match the regular expression: ${VALID_STACK_NAME_REGEX.toString()}, got '${this.stackName}'`);
}
// the preferred behavior is to generate a unique id for this stack and use
// it as the artifact ID in the assembly. this allows multiple stacks to use
// the same name. however, this behavior is breaking for 1.x so it's only
// applied under a feature flag which is applied automatically for new
// projects created using `cdk init`.
//
// Also use the new behavior if we are using the new CI/CD-ready synthesizer; that way
// people only have to flip one flag.
const featureFlags = feature_flags_1.FeatureFlags.of(this);
const stackNameDupeContext = featureFlags.isEnabled(cxapi.ENABLE_STACK_NAME_DUPLICATES_CONTEXT);
const newStyleSynthesisContext = featureFlags.isEnabled(cxapi.NEW_STYLE_STACK_SYNTHESIS_CONTEXT);
this.artifactId = (stackNameDupeContext || newStyleSynthesisContext)
? this.generateStackArtifactId()
: this.stackName;
this.templateFile = `${this.artifactId}.template.json`;
// Not for nested stacks
this._versionReportingEnabled = (props.analyticsReporting ?? this.node.tryGetContext(cxapi.ANALYTICS_REPORTING_ENABLED_CONTEXT))
&& !this.nestedStackParent;
this.synthesizer = props.synthesizer ?? (newStyleSynthesisContext
? new stack_synthesizers_1.DefaultStackSynthesizer()
: new stack_synthesizers_1.LegacyStackSynthesizer());
this.synthesizer.bind(this);
}
/**
* Return whether the given object is a Stack.
*
* We do attribute detection since we can't reliably use 'instanceof'.
*/
static isStack(x) {
return x !== null && typeof (x) === 'object' && STACK_SYMBOL in x;
}
/**
* Looks up the first stack scope in which `construct` is defined. Fails if there is no stack up the tree.
* @param construct The construct to start the search from.
*/
static of(construct) {
// we want this to be as cheap as possible. cache this result by mutating
// the object. anecdotally, at the time of this writing, @aws-cdk/core unit
// tests hit this cache 1,112 times, @aws-cdk/aws-cloudformation unit tests
// hit this 2,435 times).
const cache = construct[MY_STACK_CACHE];
if (cache) {
return cache;
}
else {
const value = _lookup(construct);
Object.defineProperty(construct, MY_STACK_CACHE, {
enumerable: false,
writable: false,
configurable: false,
value,
});
return value;
}
function _lookup(c) {
if (Stack.isStack(c)) {
return c;
}
const _scope = constructs_1.Node.of(c).scope;
if (stage_1.Stage.isStage(c) || !_scope) {
throw new Error(`${construct.constructor?.name ?? 'Construct'} at '${constructs_1.Node.of(construct).path}' should be created in the scope of a Stack, but no Stack found`);
}
return _lookup(_scope);
}
}
/**
* Resolve a tokenized value in the context of the current stack.
*/
resolve(obj) {
return resolve_1.resolve(obj, {
scope: this,
prefix: [],
resolver: cloudformation_lang_1.CLOUDFORMATION_TOKEN_RESOLVER,
preparing: false,
});
}
/**
* Convert an object, potentially containing tokens, to a JSON string
*/
toJsonString(obj, space) {
return cloudformation_lang_1.CloudFormationLang.toJSON(obj, space).toString();
}
/**
* DEPRECATED
* @deprecated use `reportMissingContextKey()`
*/
reportMissingContext(report) {
try {
jsiiDeprecationWarnings.print("@aws-cdk/core.Stack#reportMissingContext", "use `reportMissingContextKey()`");
}
catch (error) {
if (process.env.JSII_DEBUG !== "1" && error.name === "DeprecationError") {
Error.captureStackTrace(error, this.reportMissingContext);
}
throw error;
}
if (!Object.values(cxschema.ContextProvider).includes(report.provider)) {
throw new Error(`Unknown context provider requested in: ${JSON.stringify(report)}`);
}
this.reportMissingContextKey(report);
}
/**
* Indicate that a context key was expected
*
* Contains instructions which will be emitted into the cloud assembly on how
* the key should be supplied.
*
* @param report The set of parameters needed to obtain the context
*/
reportMissingContextKey(report) {
this._missingContext.push(report);
}
/**
* Rename a generated logical identities
*
* To modify the naming scheme strategy, extend the `Stack` class and
* override the `allocateLogicalId` method.
*/
renameLogicalId(oldId, newId) {
this._logicalIds.addRename(oldId, newId);
}
/**
* Allocates a stack-unique CloudFormation-compatible logical identity for a
* specific resource.
*
* This method is called when a `CfnElement` is created and used to render the
* initial logical identity of resources. Logical ID renames are applied at
* this stage.
*
* This method uses the protected method `allocateLogicalId` to render the
* logical ID for an element. To modify the naming scheme, extend the `Stack`
* class and override this method.
*
* @param element The CloudFormation element for which a logical identity is
* needed.
*/
getLogicalId(element) {
try {
jsiiDeprecationWarnings._aws_cdk_core_CfnElement(element);
}
catch (error) {
if (process.env.JSII_DEBUG !== "1" && error.name === "DeprecationError") {
Error.captureStackTrace(error, this.getLogicalId);
}
throw error;
}
const logicalId = this.allocateLogicalId(element);
return this._logicalIds.applyRename(logicalId);
}
/**
* Add a dependency between this stack and another stack.
*
* This can be used to define dependencies between any two stacks within an
* app, and also supports nested stacks.
*/
addDependency(target, reason) {
try {
jsiiDeprecationWarnings._aws_cdk_core_Stack(target);
}
catch (error) {
if (process.env.JSII_DEBUG !== "1" && error.name === "DeprecationError") {
Error.captureStackTrace(error, this.addDependency);
}
throw error;
}
deps_1.addDependency(this, target, reason);
}
/**
* Return the stacks this stack depends on
*/
get dependencies() {
return Object.values(this._stackDependencies).map(x => x.stack);
}
/**
* The concrete CloudFormation physical stack name.
*
* This is either the name defined explicitly in the `stackName` prop or
* allocated based on the stack's location in the construct tree. Stacks that
* are directly defined under the app use their construct `id` as their stack
* name. Stacks that are defined deeper within the tree will use a hashed naming
* scheme based on the construct path to ensure uniqueness.
*
* If you wish to obtain the deploy-time AWS::StackName intrinsic,
* you can use `Aws.stackName` directly.
*/
get stackName() {
return this._stackName;
}
/**
* The partition in which this stack is defined
*/
get partition() {
// Always return a non-scoped partition intrinsic. These will usually
// be used to construct an ARN, but there are no cross-partition
// calls anyway.
return cfn_pseudo_1.Aws.PARTITION;
}
/**
* The Amazon domain suffix for the region in which this stack is defined
*/
get urlSuffix() {
// Since URL Suffix always follows partition, it is unscoped like partition is.
return cfn_pseudo_1.Aws.URL_SUFFIX;
}
/**
* The ID of the stack
*
* @example
* // After resolving, looks like
* 'arn:aws:cloudformation:us-west-2:123456789012:stack/teststack/51af3dc0-da77-11e4-872e-1234567db123'
*/
get stackId() {
return new cfn_pseudo_1.ScopedAws(this).stackId;
}
/**
* Returns the list of notification Amazon Resource Names (ARNs) for the current stack.
*/
get notificationArns() {
return new cfn_pseudo_1.ScopedAws(this).notificationArns;
}
/**
* Indicates if this is a nested stack, in which case `parentStack` will include a reference to it's parent.
*/
get nested() {
return this.nestedStackResource !== undefined;
}
/**
* Creates an ARN from components.
*
* If `partition`, `region` or `account` are not specified, the stack's
* partition, region and account will be used.
*
* If any component is the empty string, an empty string will be inserted
* into the generated ARN at the location that component corresponds to.
*
* The ARN will be formatted as follows:
*
* arn:{partition}:{service}:{region}:{account}:{resource}{sep}}{resource-name}
*
* The required ARN pieces that are omitted will be taken from the stack that
* the 'scope' is attached to. If all ARN pieces are supplied, the supplied scope
* can be 'undefined'.
*/
formatArn(components) {
try {
jsiiDeprecationWarnings._aws_cdk_core_ArnComponents(components);
}
catch (error) {
if (process.env.JSII_DEBUG !== "1" && error.name === "DeprecationError") {
Error.captureStackTrace(error, this.formatArn);
}
throw error;
}
return arn_1.Arn.format(components, this);
}
/**
* Given an ARN, parses it and returns components.
*
* IF THE ARN IS A CONCRETE STRING...
*
* ...it will be parsed and validated. The separator (`sep`) will be set to '/'
* if the 6th component includes a '/', in which case, `resource` will be set
* to the value before the '/' and `resourceName` will be the rest. In case
* there is no '/', `resource` will be set to the 6th components and
* `resourceName` will be set to the rest of the string.
*
* IF THE ARN IS A TOKEN...
*
* ...it cannot be validated, since we don't have the actual value yet at the
* time of this function call. You will have to supply `sepIfToken` and
* whether or not ARNs of the expected format usually have resource names
* in order to parse it properly. The resulting `ArnComponents` object will
* contain tokens for the subexpressions of the ARN, not string literals.
*
* If the resource name could possibly contain the separator char, the actual
* resource name cannot be properly parsed. This only occurs if the separator
* char is '/', and happens for example for S3 object ARNs, IAM Role ARNs,
* IAM OIDC Provider ARNs, etc. To properly extract the resource name from a
* Tokenized ARN, you must know the resource type and call
* `Arn.extractResourceName`.
*
* @param arn The ARN string to parse
* @param sepIfToken The separator used to separate resource from resourceName
* @param hasName Whether there is a name component in the ARN at all. For
* example, SNS Topics ARNs have the 'resource' component contain the topic
* name, and no 'resourceName' component.
*
* @returns an ArnComponents object which allows access to the various
* components of the ARN.
*
* @returns an ArnComponents object which allows access to the various
* components of the ARN.
*
* @deprecated use splitArn instead
*/
parseArn(arn, sepIfToken = '/', hasName = true) {
try {
jsiiDeprecationWarnings.print("@aws-cdk/core.Stack#parseArn", "use splitArn instead");
}
catch (error) {
if (process.env.JSII_DEBUG !== "1" && error.name === "DeprecationError") {
Error.captureStackTrace(error, this.parseArn);
}
throw error;
}
return arn_1.Arn.parse(arn, sepIfToken, hasName);
}
/**
* Splits the provided ARN into its components.
* Works both if 'arn' is a string like 'arn:aws:s3:::bucket',
* and a Token representing a dynamic CloudFormation expression
* (in which case the returned components will also be dynamic CloudFormation expressions,
* encoded as Tokens).
*
* @param arn the ARN to split into its components
* @param arnFormat the expected format of 'arn' - depends on what format the service 'arn' represents uses
*/
splitArn(arn, arnFormat) {
try {
jsiiDeprecationWarnings._aws_cdk_core_ArnFormat(arnFormat);
}
catch (error) {
if (process.env.JSII_DEBUG !== "1" && error.name === "DeprecationError") {
Error.captureStackTrace(error, this.splitArn);
}
throw error;
}
return arn_1.Arn.split(arn, arnFormat);
}
/**
* Returns the list of AZs that are available in the AWS environment
* (account/region) associated with this stack.
*
* If the stack is environment-agnostic (either account and/or region are
* tokens), this property will return an array with 2 tokens that will resolve
* at deploy-time to the first two availability zones returned from CloudFormation's
* `Fn::GetAZs` intrinsic function.
*
* If they are not available in the context, returns a set of dummy values and
* reports them as missing, and let the CLI resolve them by calling EC2
* `DescribeAvailabilityZones` on the target environment.
*
* To specify a different strategy for selecting availability zones override this method.
*/
get availabilityZones() {
// if account/region are tokens, we can't obtain AZs through the context
// provider, so we fallback to use Fn::GetAZs. the current lowest common
// denominator is 2 AZs across all AWS regions.
const agnostic = token_1.Token.isUnresolved(this.account) || token_1.Token.isUnresolved(this.region);
if (agnostic) {
return this.node.tryGetContext(cxapi.AVAILABILITY_ZONE_FALLBACK_CONTEXT_KEY) || [
cfn_fn_1.Fn.select(0, cfn_fn_1.Fn.getAzs()),
cfn_fn_1.Fn.select(1, cfn_fn_1.Fn.getAzs()),
];
}
const value = context_provider_1.ContextProvider.getValue(this, {
provider: cxschema.ContextProvider.AVAILABILITY_ZONE_PROVIDER,
dummyValue: ['dummy1a', 'dummy1b', 'dummy1c'],
}).value;
if (!Array.isArray(value)) {
throw new Error(`Provider ${cxschema.ContextProvider.AVAILABILITY_ZONE_PROVIDER} expects a list`);
}
return value;
}
/**
* Register a file asset on this Stack
*
* @deprecated Use `stack.synthesizer.addFileAsset()` if you are calling,
* and a different IStackSynthesizer class if you are implementing.
*/
addFileAsset(asset) {
try {
jsiiDeprecationWarnings.print("@aws-cdk/core.Stack#addFileAsset", "Use `stack.synthesizer.addFileAsset()` if you are calling,\nand a different IStackSynthesizer class if you are implementing.");
jsiiDeprecationWarnings._aws_cdk_core_FileAssetSource(asset);
}
catch (error) {
if (process.env.JSII_DEBUG !== "1" && error.name === "DeprecationError") {
Error.captureStackTrace(error, this.addFileAsset);
}
throw error;
}
return this.synthesizer.addFileAsset(asset);
}
/**
* Register a docker image asset on this Stack
*
* @deprecated Use `stack.synthesizer.addDockerImageAsset()` if you are calling,
* and a different `IStackSynthesizer` class if you are implementing.
*/
addDockerImageAsset(asset) {
try {
jsiiDeprecationWarnings.print("@aws-cdk/core.Stack#addDockerImageAsset", "Use `stack.synthesizer.addDockerImageAsset()` if you are calling,\nand a different `IStackSynthesizer` class if you are implementing.");
jsiiDeprecationWarnings._aws_cdk_core_DockerImageAssetSource(asset);
}
catch (error) {
if (process.env.JSII_DEBUG !== "1" && error.name === "DeprecationError") {
Error.captureStackTrace(error, this.addDockerImageAsset);
}
throw error;
}
return this.synthesizer.addDockerImageAsset(asset);
}
/**
* If this is a nested stack, returns it's parent stack.
*/
get nestedStackParent() {
return this.nestedStackResource && Stack.of(this.nestedStackResource);
}
/**
* Returns the parent of a nested stack.
*
* @deprecated use `nestedStackParent`
*/
get parentStack() {
try {
jsiiDeprecationWarnings.print("@aws-cdk/core.Stack#parentStack", "use `nestedStackParent`");
}
catch (error) {
if (process.env.JSII_DEBUG !== "1" && error.name === "DeprecationError") {
Error.captureStackTrace(error, jsiiDeprecationWarnings.getPropertyDescriptor(this, "parentStack").get);
}
throw error;
}
return this.nestedStackParent;
}
/**
* Add a Transform to this stack. A Transform is a macro that AWS
* CloudFormation uses to process your template.
*
* Duplicate values are removed when stack is synthesized.
*
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/transform-section-structure.html
* @param transform The transform to add
*
* @example
* declare const stack: Stack;
*
* stack.addTransform('AWS::Serverless-2016-10-31')
*/
addTransform(transform) {
if (!this.templateOptions.transforms) {
this.templateOptions.transforms = [];
}
this.templateOptions.transforms.push(transform);
}
/**
* Called implicitly by the `addDependency` helper function in order to
* realize a dependency between two top-level stacks at the assembly level.
*
* Use `stack.addDependency` to define the dependency between any two stacks,
* and take into account nested stack relationships.
*
* @internal
*/
_addAssemblyDependency(target, reason) {
// defensive: we should never get here for nested stacks
if (this.nested || target.nested) {
throw new Error('Cannot add assembly-level dependencies for nested stacks');
}
reason = reason || 'dependency added using stack.addDependency()';
const cycle = target.stackDependencyReasons(this);
if (cycle !== undefined) {
// eslint-disable-next-line max-len
throw new Error(`'${target.node.path}' depends on '${this.node.path}' (${cycle.join(', ')}). Adding this dependency (${reason}) would create a cyclic reference.`);
}
let dep = this._stackDependencies[names_1.Names.uniqueId(target)];
if (!dep) {
dep = this._stackDependencies[names_1.Names.uniqueId(target)] = {
stack: target,
reasons: [],
};
}
dep.reasons.push(reason);
if (process.env.CDK_DEBUG_DEPS) {
// eslint-disable-next-line no-console
console.error(`[CDK_DEBUG_DEPS] stack "${this.node.path}" depends on "${target.node.path}" because: ${reason}`);
}
}
/**
* Synthesizes the cloudformation template into a cloud assembly.
* @internal
*/
_synthesizeTemplate(session, lookupRoleArn) {
// In principle, stack synthesis is delegated to the
// StackSynthesis object.
//
// However, some parts of synthesis currently use some private
// methods on Stack, and I don't really see the value in refactoring
// this right now, so some parts still happen here.
const builder = session.assembly;
const template = this._toCloudFormation();
// write the CloudFormation template as a JSON file
const outPath = path.join(builder.outdir, this.templateFile);
if (this.maxResources > 0) {
const resources = template.Resources || {};
const numberOfResources = Object.keys(resources).length;
if (numberOfResources > this.maxResources) {
const counts = Object.entries(count(Object.values(resources).map((r) => `${r?.Type}`))).map(([type, c]) => `${type} (${c})`).join(', ');
throw new Error(`Number of resources in stack '${this.node.path}': ${numberOfResources} is greater than allowed maximum of ${this.maxResources}: ${counts}`);
}
else if (numberOfResources >= (this.maxResources * 0.8)) {
annotations_1.Annotations.of(this).addInfo(`Number of resources: ${numberOfResources} is approaching allowed maximum of ${this.maxResources}`);
}
}
fs.writeFileSync(outPath, JSON.stringify(template, undefined, 1));
for (const ctx of this._missingContext) {
if (lookupRoleArn != null) {
builder.addMissing({ ...ctx, props: { ...ctx.props, lookupRoleArn } });
}
else {
builder.addMissing(ctx);
}
}
}
/**
* Look up a fact value for the given fact for the region of this stack
*
* Will return a definite value only if the region of the current stack is resolved.
* If not, a lookup map will be added to the stack and the lookup will be done at
* CDK deployment time.
*
* What regions will be included in the lookup map is controlled by the
* `@aws-cdk/core:target-partitions` context value: it must be set to a list
* of partitions, and only regions from the given partitions will be included.
* If no such context key is set, all regions will be included.
*
* This function is intended to be used by construct library authors. Application
* builders can rely on the abstractions offered by construct libraries and do
* not have to worry about regional facts.
*
* If `defaultValue` is not given, it is an error if the fact is unknown for
* the given region.
*/
regionalFact(factName, defaultValue) {
if (!token_1.Token.isUnresolved(this.region)) {
const ret = region_info_1.Fact.find(this.region, factName) ?? defaultValue;
if (ret === undefined) {
throw new Error(`region-info: don't know ${factName} for region ${this.region}. Use 'Fact.register' to provide this value.`);
}
return ret;
}
const partitions = constructs_1.Node.of(this).tryGetContext(cxapi.TARGET_PARTITIONS);
if (partitions !== undefined && !Array.isArray(partitions)) {
throw new Error(`Context value '${cxapi.TARGET_PARTITIONS}' should be a list of strings, got: ${JSON.stringify(cxapi.TARGET_PARTITIONS)}`);
}
const lookupMap = partitions ? region_info_1.RegionInfo.limitedRegionMap(factName, partitions) : region_info_1.RegionInfo.regionMap(factName);
return region_lookup_1.deployTimeLookup(this, factName, lookupMap, defaultValue);
}
/**
* Create a CloudFormation Export for a value
*
* Returns a string representing the corresponding `Fn.importValue()`
* expression for this Export. You can control the name for the export by
* passing the `name` option.
*
* If you don't supply a value for `name`, the value you're exporting must be
* a Resource attribute (for example: `bucket.bucketName`) and it will be
* given the same name as the automatic cross-stack reference that would be created
* if you used the attribute in another Stack.
*
* One of the uses for this method is to *remove* the relationship between
* two Stacks established by automatic cross-stack references. It will
* temporarily ensure that the CloudFormation Export still exists while you
* remove the reference from the consuming stack. After that, you can remove
* the resource and the manual export.
*
* ## Example
*
* Here is how the process works. Let's say there are two stacks,
* `producerStack` and `consumerStack`, and `producerStack` has a bucket
* called `bucket`, which is referenced by `consumerStack` (perhaps because
* an AWS Lambda Function writes into it, or something like that).
*
* It is not safe to remove `producerStack.bucket` because as the bucket is being
* deleted, `consumerStack` might still be using it.
*
* Instead, the process takes two deployments:
*
* ### Deployment 1: break the relationship
*
* - Make sure `consumerStack` no longer references `bucket.bucketName` (maybe the consumer
* stack now uses its own bucket, or it writes to an AWS DynamoDB table, or maybe you just
* remove the Lambda Function altogether).
* - In the `ProducerStack` class, call `this.exportValue(this.bucket.bucketName)`. This
* will make sure the CloudFormation Export continues to exist while the relationship
* between the two stacks is being broken.
* - Deploy (this will effectively only change the `consumerStack`, but it's safe to deploy both).
*
* ### Deployment 2: remove the bucket resource
*
* - You are now free to remove the `bucket` resource from `producerStack`.
* - Don't forget to remove the `exportValue()` call as well.
* - Deploy again (this time only the `producerStack` will be changed -- the bucket will be deleted).
*/
exportValue(exportedValue, options = {}) {
try {
jsiiDeprecationWarnings._aws_cdk_core_ExportValueOptions(options);
}
catch (error) {
if (process.env.JSII_DEBUG !== "1" && error.name === "DeprecationError") {
Error.captureStackTrace(error, this.exportValue);
}
throw error;
}
if (options.name) {
new cfn_output_1.CfnOutput(this, `Export${options.name}`, {
value: exportedValue,
exportName: options.name,
});
return cfn_fn_1.Fn.importValue(options.name);
}
const resolvable = token_1.Tokenization.reverse(exportedValue);
if (!resolvable || !reference_1.Reference.isReference(resolvable)) {
throw new Error('exportValue: either supply \'name\' or make sure to export a resource attribute (like \'bucket.bucketName\')');
}
// if exportValue is being called manually (which is pre onPrepare) then the logicalId
// could potentially be changed by a call to overrideLogicalId. This would cause our Export/Import
// to have an incorrect id. For a better user experience, lock the logicalId and throw an error
// if the user tries to override the id _after_ calling exportValue
if (cfn_element_1.CfnElement.isCfnElement(resolvable.target)) {
resolvable.target._lockLogicalId();
}
// "teleport" the value here, in case it comes from a nested stack. This will also
// ensure the value is from our own scope.
const exportable = refs_1.referenceNestedStackValueInParent(resolvable, this);
// Ensure a singleton "Exports" scoping Construct
// This mostly exists to trigger LogicalID munging, which would be
// disabled if we parented constructs directly under Stack.
// Also it nicely prevents likely construct name clashes
const exportsScope = getCreateExportsScope(this);
// Ensure a singleton CfnOutput for this value
const resolved = this.resolve(exportable);
const id = 'Output' + JSON.stringify(resolved);
const exportName = generateExportName(exportsScope, id);
if (token_1.Token.isUnresolved(exportName)) {
throw new Error(`unresolved token in generated export name: ${JSON.stringify(this.resolve(exportName))}`);
}
const output = exportsScope.node.tryFindChild(id);
if (!output) {
new cfn_output_1.CfnOutput(exportsScope, id, { value: token_1.Token.asString(exportable), exportName });
}
return cfn_fn_1.Fn.importValue(exportName);
}
/**
* Returns the naming scheme used to allocate logical IDs. By default, uses
* the `HashedAddressingScheme` but this method can be overridden to customize
* this behavior.
*
* In order to make sure logical IDs are unique and stable, we hash the resource
* construct tree path (i.e. toplevel/secondlevel/.../myresource) and add it as
* a suffix to the path components joined without a separator (CloudFormation
* IDs only allow alphanumeric characters).
*
* The result will be:
*
* <path.join('')><md5(path.join('/')>
* "human" "hash"
*
* If the "human" part of the ID exceeds 240 characters, we simply trim it so
* the total ID doesn't exceed CloudFormation's 255 character limit.
*
* We only take 8 characters from the md5 hash (0.000005 chance of collision).
*
* Special cases:
*
* - If the path only contains a single component (i.e. it's a top-level
* resource), we won't add the hash to it. The hash is not needed for
* disamiguation and also, it allows for a more straightforward migration an
* existing CloudFormation template to a CDK stack without logical ID changes
* (or renames).
* - For aesthetic reasons, if the last components of the path are the same
* (i.e. `L1/L2/Pipeline/Pipeline`), they will be de-duplicated to make the
* resulting human portion of the ID more pleasing: `L1L2Pipeline<HASH>`
* instead of `L1L2PipelinePipeline<HASH>`
* - If a component is named "Default" it will be omitted from the path. This
* allows refactoring higher level abstractions around constructs without affecting
* the IDs of already deployed resources.
* - If a component is named "Resource" it will be omitted from the user-visible
* path, but included in the hash. This reduces visual noise in the human readable
* part of the identifier.
*
* @param cfnElement The element for which the logical ID is allocated.
*/
allocateLogicalId(cfnElement) {
try {
jsiiDeprecationWarnings._aws_cdk_core_CfnElement(cfnElement);
}
catch (error) {
if (process.env.JSII_DEBUG !== "1" && error.name === "DeprecationError") {
Error.captureStackTrace(error, this.allocateLogicalId);
}
throw error;
}
const scopes = cfnElement.node.scopes;
const stackIndex = scopes.indexOf(cfnElement.stack);
const pathComponents = scopes.slice(stackIndex + 1).map(x => x.node.id);
return uniqueid_1.makeUniqueId(pathComponents);
}
/**
* Validate stack name
*
* CloudFormation stack names can include dashes in addition to the regular identifier
* character classes, and we don't allow one of the magic markers.
*
* @internal
*/
_validateId(name) {
if (name && !VALID_STACK_NAME_REGEX.test(name)) {
throw new Error(`Stack name must match the regular expression: ${VALID_STACK_NAME_REGEX.toString()}, got '${name}'`);
}
}
/**
* Returns the CloudFormation template for this stack by traversing
* the tree and invoking _toCloudFormation() on all Entity objects.
*
* @internal
*/
_toCloudFormation() {
let transform;
if (this.templateOptions.transform) {
// eslint-disable-next-line max-len
annotations_1.Annotations.of(this).addWarning('This stack is using the deprecated `templateOptions.transform` property. Consider switching to `addTransform()`.');
this.addTransform(this.templateOptions.transform);
}
if (this.templateOptions.transforms) {
if (this.templateOptions.transforms.length === 1) { // Extract single value
transform = this.templateOptions.transforms[0];
}
else { // Remove duplicate values
transform = Array.from(new Set(this.templateOptions.transforms));
}
}
const template = {
Description: this.templateOptions.description,
Transform: transform,
AWSTemplateFormatVersion: this.templateOptions.templateFormatVersion,
Metadata: this.templateOptions.metadata,
};
const elements = cfnElements(this);
const fragments = elements.map(e => this.resolve(e._toCloudFormation()));
// merge in all CloudFormation fragments collected from the tree
for (const fragment of fragments) {
merge(template, fragment);
}
// resolve all tokens and remove all empties
const ret = this.resolve(template) || {};
this._logicalIds.assertAllRenamesApplied();
return ret;
}
/**
* Deprecated.
*
* @see https://github.com/aws/aws-cdk/pull/7187
* @returns reference itself without any change
* @deprecated cross reference handling has been moved to `App.prepare()`.
*/
prepareCrossReference(_sourceStack, reference) {
try {
jsiiDeprecationWarnings.print("@aws-cdk/core.Stack#prepareCrossReference", "cross reference handling has been moved to `App.prepare()`.");
jsiiDeprecationWarnings._aws_cdk_core_Stack(_sourceStack);
jsiiDeprecationWarnings._aws_cdk_core_Reference(reference);
}
catch (error) {
if (process.env.JSII_DEBUG !== "1" && error.name === "DeprecationError") {
Error.captureStackTrace(error, this.prepareCrossReference);
}
throw error;
}
return reference;
}
/**
* Determine the various stack environment attributes.
*
*/
parseEnvironment(env = {}) {
// if an environment property is explicitly specified when the stack is
// created, it will be used. if not, use tokens for account and region.
//
// (They do not need to be anchored to any construct like resource attributes
// are, because we'll never Export/Fn::ImportValue them -- the only situation
// in which Export/Fn::ImportValue would work is if the value are the same
// between producer and consumer anyway, so we can just assume that they are).
const containingAssembly = stage_1.Stage.of(this);
const account = env.account ?? containingAssembly?.account ?? cfn_pseudo_1.Aws.ACCOUNT_ID;
const region = env.region ?? containingAssembly?.region ?? cfn_pseudo_1.Aws.REGION;
// this is the "aws://" env specification that will be written to the cloud assembly
// manifest. it will use "unknown-account" and "unknown-region" to indicate
// environment-agnosticness.
const envAccount = !token_1.Token.isUnresolved(account) ? account : cxapi.UNKNOWN_ACCOUNT;
const envRegion = !token_1.Token.isUnresolved(region) ? region : cxapi.UNKNOWN_REGION;
return {
account,
region,
environment: cxapi.EnvironmentUtils.format(envAccount, envRegion),
};
}
/**
* Maximum number of resources in the stack
*
* Set to 0 to mean "unlimited".
*/
get maxResources() {
const contextLimit = this.node.tryGetContext(exports.STACK_RESOURCE_LIMIT_CONTEXT);
return contextLimit !== undefined ? parseInt(contextLimit, 10) : MAX_RESOURCES;
}
/**
* Check whether this stack has a (transitive) dependency on another stack
*
* Returns the list of reasons on the dependency path, or undefined
* if there is no dependency.
*/
stackDependencyReasons(other) {
if (this === other) {
return [];
}
for (const dep of Object.values(this._stackDependencies)) {
const ret = dep.stack.stackDependencyReasons(other);
if (ret !== undefined) {
return [...dep.reasons, ...ret];
}
}
return undefined;
}
/**
* Calculate the stack name based on the construct path
*
* The stack name is the name under which we'll deploy the stack,
* and incorporates containing Stage names by default.
*
* Generally this looks a lot like how logical IDs are calculated.
* The stack name is calculated based on the construct root path,
* as follows:
*
* - Path is calculated with respect to containing App or Stage (if any)
* - If the path is one component long just use that component, otherwise
* combine them with a hash.
*
* Since the hash is quite ugly and we'd like to avoid it if possible -- but
* we can't anymore in the general case since it has been written into legacy
* stacks. The introduction of Stages makes it possible to make this nicer however.
* When a Stack is nested inside a Stage, we use the path components below the
* Stage, and prefix the path components of the Stage before it.
*/
generateStackName() {
const assembly = stage_1.Stage.of(this);
const prefix = (assembly && assembly.stageName) ? `${assembly.stageName}-` : '';
return `${prefix}${this.generateStackId(assembly)}`;
}
/**
* The artifact ID for this stack
*
* Stack artifact ID is unique within the App's Cloud Assembly.
*/
generateStackArtifactId() {
return this.generateStackId(this.node.root);
}
/**
* Generate an ID with respect to the given container construct.
*/
generateStackId(container) {
const rootPath = rootPathTo(this, container);
const ids = rootPath.map(c => constructs_1.Node.of(c).id);
// In unit tests our Stack (which is the only component) may not have an
// id, so in that case just pretend it's "Stack".
if (ids.length === 1 && !ids[0]) {
throw new Error('unexpected: stack id must always be defined');
}
return makeStackName(ids);
}
/**
* Indicates whether the stack requires bundling or not
*/
get bundlingRequired() {
const bundlingStacks = this.node.tryGetContext(cxapi.BUNDLING_STACKS) ?? ['*'];
// bundlingStacks is of the form `Stage/Stack`, convert it to `Stage-Stack` before comparing to stack name
return bundlingStacks.some(pattern => minimatch(this.stackName, pattern.replace('/', '-')));
}
}
exports.Stack = Stack;
_a = JSII_RTTI_SYMBOL_1;
Stack[_a] = { fqn: "@aws-cdk/core.Stack", version: "1.204.0" };
function merge(template, fragment) {
for (const section of Object.keys(fragment)) {
const src = fragment[section];
// create top-level section if it doesn't exist
const dest = template[section];
if (!dest) {
template[section] = src;
}
else {
template[section] = mergeSection(section, dest, src);
}
}
}
function mergeSection(section, val1, val2) {
switch (section) {
case 'Description':
return `${val1}\n${val2}`;
case 'AWSTemplateFormatVersion':
if (val1 != null && val2 != null && val1 !== val2) {
throw new Error(`Conflicting CloudFormation template versions provided: '${val1}' and '${val2}`);
}
return val1 ?? val2;
case 'Transform':
return mergeSets(val1, val2);
default:
return mergeObjectsWithoutDuplicates(section, val1, val2);
}
}
function mergeSets(val1, val2) {
const array1 = val1 == null ? [] : (Array.isArray(val1) ? val1 : [val1]);
const array2 = val2 == null ? [] : (Array.isArray(val2) ? val2 : [val2]);
for (const value of array2) {
if (!array1.includes(value)) {
array1.push(value);
}
}
return array1.length === 1 ? array1[0] : array1;
}
function mergeObjectsWithoutDuplicates(section, dest, src) {
if (typeof dest !== 'object') {
throw new Error(`Expecting ${JSON.stringify(dest)} to be an object`);
}
if (typeof src !== 'object') {
throw new Error(`Expecting ${JSON.stringify(src)} to be an object`);
}
// add all entities from source section to destination section
for (const id of Object.keys(src)) {
if (id in dest) {
throw new Error(`section '${section}' already contains '${id}'`);
}
dest[id] = src[id];
}
return dest;
}
/**
* Collect all CfnElements from a Stack.
*
* @param node Root node to collect all CfnElements from
* @param into Array to append CfnElements to
* @returns The same array as is being collected into
*/
function cfnElements(node, into = []) {
if (cfn_element_1.CfnElement.isCfnElement(node)) {
into.push(node);
}
for (const child of constructs_1.Node.of(node).children) {
// Don't recurse into a substack
if (Stack.isStack(child)) {
continue;
}
cfnElements(child, into);
}
return into;
}
/**
* Return the construct root path of the given construct relative to the given ancestor
*
* If no ancestor is given or the ancestor is not found, return the entire root path.
*/
function rootPathTo(construct, ancestor) {
const scopes = constructs_1.Node.of(construct).scopes;
for (let i = scopes.length - 2; i >= 0; i--) {
if (scopes[i] === ancestor) {
return scopes.slice(i + 1);
}
}
return scopes;
}
exports.rootPathTo = rootPathTo;
/**
* makeUniqueId, specialized for Stack names
*
* Stack names may contain '-', so we allow that character if the stack name
* has only one component. Otherwise we fall back to the regular "makeUniqueId"
* behavior.
*/
function makeStackName(components) {
if (components.length === 1) {
return components[0];
}
return uniqueid_1.makeUniqueId(components);
}
function getCreateExportsScope(stack) {
const exportsName = 'Exports';
let stackExports = stack.node.tryFindChild(exportsName);
if (stackExports === undefined) {
stackExports = new construct_compat_1.Construct(stack, exportsName);
}
return stackExports;
}
function generateExportName(stackExports, id) {
const stackRelativeExports = feature_flags_1.FeatureFlags.of(stackExports).isEnabled(cxapi.STACK_RELATIVE_EXPORTS_CONTEXT);
const stack = Stack.of(stackExports);
const components = [
...stackExports.node.scopes
.slice(stackRelativeExports ? stack.node.scopes.length : 2)
.map(c => c.node.id),
id,
];
const prefix = stack.stackName ? stack.stackName + ':' : '';
const localPart = uniqueid_1.makeUniqueId(components);
const maxLength = 255;
return prefix + localPart.slice(Math.max(0, localPart.length - maxLength + prefix.length));
}
function count(xs) {
const ret = {};
for (const x of xs) {
if (x in ret) {
ret[x] += 1;
}
else {
ret[x] = 1;
}
}
return ret;
}
// These imports have to be at the end to prevent circular imports
const cfn_output_1 = require("./cfn-output");
const deps_1 = require("./deps");
const fs_1 = require("./fs");
const names_1 = require("./names");
const reference_1 = require("./reference");
const stack_synthesizers_1 = require("./stack-synthesizers");
const stage_1 = require("./stage");
const tag_manager_1 = require("./tag-manager");
const token_1 = require("./token");
const refs_1 = require("./private/refs");
const region_info_1 = require("@aws-cdk/region-info");
const region_lookup_1 = require("./private/region-lookup");
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic3RhY2suanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJzdGFjay50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7QUFBQSx5QkFBeUI7QUFDekIsNkJBQTZCO0FBQzdCLDJEQUEyRDtBQUMzRCx5Q0FBeUM7QUFDekMsMkNBQXlEO0FBQ3pELHVDQUF1QztBQUN2QywrQ0FBNEM7QUFDNUMsK0JBQTRCO0FBQzVCLCtCQUFzRDtBQUV0RCwrQ0FBMkM7QUFDM0MscUNBQThCO0FBQzlCLDZDQUE4QztBQUM5QyxpREFBc0Q7QUFFdEQseURBQXFEO0FBRXJELG1EQUErQztBQUMvQyx1RUFBa0c7QUFDbEcscURBQWtEO0FBQ2xELCtDQUE0QztBQUM1QyxpREFBa0Q7QUFFbEQsZ0hBQWdIO0FBQ2hILDJCQUEyQjtBQUMzQix5REFBZ0U7QUFFaEUsTUFBTSxZQUFZLEdBQUcsTUFBTSxDQUFDLEdBQUcsQ0FBQyxxQkFBcUIsQ0FBQyxDQUFDO0FBQ3ZELE1BQU0sY0FBYyxHQUFHLE1BQU0sQ0FBQyxHQUFHLENBQUMsNkJBQTZCLENBQUMsQ0FBQztBQUVwRCxRQUFBLDRCQUE0QixHQUFHLGtDQUFrQyxDQUFDO0FBRS9FLE1BQU0sc0JBQXNCLEdBQUcseUJBQXlCLENBQUM7QUFFekQsTUFBTSxhQUFhLEdBQUcsR0FBRyxDQUFDO0FBa0gxQjs7R0FFRztBQUNILE1BQWEsS0FBTSxTQUFRLDRCQUFhO0lBK0t0Qzs7Ozs7Ozs7T0FRRztJQUNILFlBQW1CLEtBQWlCLEVBQUUsRUFBVyxFQUFFLFFBQW9CLEVBQUU7Ozs7OzsrQ0F4TDlELEtBQUs7Ozs7UUF5TGQsK0VBQStFO1FBQy9FLG9FQUFvRTtRQUNwRSxLQUFLLEdBQUcsS0FBSyxJQUFJLElBQUksU0FBRyxDQUFDO1lBQ3ZCLFNBQVMsRUFBRSxLQUFLO1lBQ2hCLE1BQU0sRUFBRSxlQUFVLENBQUMsT0FBTyxDQUFDLGVBQWUsQ0FBQztTQUM1QyxDQUFDLENBQUM7UUFFSCxnRUFBZ0U7UUFDaEUsRUFBRSxHQ