aws-cdk-lib.NestedStack

class NestedStack (construct)

LanguageType name
.NETAmazon.CDK.NestedStack
Gogithub.com/aws/aws-cdk-go/awscdk/v2#NestedStack
Javasoftware.amazon.awscdk.NestedStack
Pythonaws_cdk.NestedStack
TypeScript (source)aws-cdk-lib » NestedStack

Implements IConstruct, IDependable, ITaggable

A CloudFormation nested stack.

When you apply template changes to update a top-level stack, CloudFormation updates the top-level stack and initiates an update to its nested stacks. CloudFormation updates the resources of modified nested stacks, but does not update the resources of unmodified nested stacks.

Furthermore, this stack will not be treated as an independent deployment artifact (won't be listed in "cdk list" or deployable through "cdk deploy"), but rather only synthesized as a template and uploaded as an asset to S3.

Cross references of resource attributes between the parent stack and the nested stack will automatically be translated to stack parameters and outputs.

Example

import { Construct } from 'constructs';
import { App, CfnOutput, NestedStack, NestedStackProps, Stack } from '../../core';
import { Deployment, Method, MockIntegration, PassthroughBehavior, RestApi, Stage } from '../lib';

/**
 * This file showcases how to split up a RestApi's Resources and Methods across nested stacks.
 *
 * The root stack 'RootStack' first defines a RestApi.
 * Two nested stacks BooksStack and PetsStack, create corresponding Resources '/books' and '/pets'.
 * They are then deployed to a 'prod' Stage via a third nested stack - DeployStack.
 *
 * To verify this worked, go to the APIGateway
 */

class RootStack extends Stack {
  constructor(scope: Construct) {
    super(scope, 'integ-restapi-import-RootStack');

    const restApi = new RestApi(this, 'RestApi', {
      cloudWatchRole: true,
      deploy: false,
    });
    restApi.root.addMethod('ANY');

    const petsStack = new PetsStack(this, {
      restApiId: restApi.restApiId,
      rootResourceId: restApi.restApiRootResourceId,
    });
    const booksStack = new BooksStack(this, {
      restApiId: restApi.restApiId,
      rootResourceId: restApi.restApiRootResourceId,
    });
    new DeployStack(this, {
      restApiId: restApi.restApiId,
      methods: petsStack.methods.concat(booksStack.methods),
    });

    new CfnOutput(this, 'PetsURL', {
      value: `https://${restApi.restApiId}.execute-api.${this.region}.amazonaws.com/prod/pets`,
    });

    new CfnOutput(this, 'BooksURL', {
      value: `https://${restApi.restApiId}.execute-api.${this.region}.amazonaws.com/prod/books`,
    });
  }
}

interface ResourceNestedStackProps extends NestedStackProps {
  readonly restApiId: string;

  readonly rootResourceId: string;
}

class PetsStack extends NestedStack {
  public readonly methods: Method[] = [];

  constructor(scope: Construct, props: ResourceNestedStackProps) {
    super(scope, 'integ-restapi-import-PetsStack', props);

    const api = RestApi.fromRestApiAttributes(this, 'RestApi', {
      restApiId: props.restApiId,
      rootResourceId: props.rootResourceId,
    });

    const method = api.root.addResource('pets').addMethod('GET', new MockIntegration({
      integrationResponses: [{
        statusCode: '200',
      }],
      passthroughBehavior: PassthroughBehavior.NEVER,
      requestTemplates: {
        'application/json': '{ "statusCode": 200 }',
      },
    }), {
      methodResponses: [{ statusCode: '200' }],
    });

    this.methods.push(method);
  }
}

class BooksStack extends NestedStack {
  public readonly methods: Method[] = [];

  constructor(scope: Construct, props: ResourceNestedStackProps) {
    super(scope, 'integ-restapi-import-BooksStack', props);

    const api = RestApi.fromRestApiAttributes(this, 'RestApi', {
      restApiId: props.restApiId,
      rootResourceId: props.rootResourceId,
    });

    const method = api.root.addResource('books').addMethod('GET', new MockIntegration({
      integrationResponses: [{
        statusCode: '200',
      }],
      passthroughBehavior: PassthroughBehavior.NEVER,
      requestTemplates: {
        'application/json': '{ "statusCode": 200 }',
      },
    }), {
      methodResponses: [{ statusCode: '200' }],
    });

    this.methods.push(method);
  }
}

interface DeployStackProps extends NestedStackProps {
  readonly restApiId: string;

  readonly methods?: Method[];
}

class DeployStack extends NestedStack {
  constructor(scope: Construct, props: DeployStackProps) {
    super(scope, 'integ-restapi-import-DeployStack', props);

    const deployment = new Deployment(this, 'Deployment', {
      api: RestApi.fromRestApiId(this, 'RestApi', props.restApiId),
    });
    if (props.methods) {
      for (const method of props.methods) {
        deployment.node.addDependency(method);
      }
    }
    new Stage(this, 'Stage', { deployment });
  }
}

new RootStack(new App());

Initializer

new NestedStack(scope: Construct, id: string, props?: NestedStackProps)

Parameters

  • scope Construct
  • id string
  • props NestedStackProps

Construct Props

NameTypeDescription
description?stringA description of the stack.
notificationArns?string[]The Simple Notification Service (SNS) topics to publish stack related events.
parameters?{ [string]: string }The set value pairs that represent the parameters passed to CloudFormation when this nested stack is created.
removalPolicy?RemovalPolicyPolicy to apply when the nested stack is removed.
timeout?DurationThe length of time that CloudFormation waits for the nested stack to reach the CREATE_COMPLETE state.

description?

Type: string (optional, default: No description.)

A description of the stack.


notificationArns?

Type: string[] (optional, default: notifications are not sent for this stack.)

The Simple Notification Service (SNS) topics to publish stack related events.


parameters?

Type: { [string]: string } (optional, default: no user-defined parameters are passed to the nested stack)

The set value pairs that represent the parameters passed to CloudFormation when this nested stack is created.

Each parameter has a name corresponding to a parameter defined in the embedded template and a value representing the value that you want to set for the parameter.

The nested stack construct will automatically synthesize parameters in order to bind references from the parent stack(s) into the nested stack.


removalPolicy?

Type: RemovalPolicy (optional, default: RemovalPolicy.DESTROY)

Policy to apply when the nested stack is removed.

The default is Destroy, because all Removal Policies of resources inside the Nested Stack should already have been set correctly. You normally should not need to set this value.


timeout?

Type: Duration (optional, default: no timeout)

The length of time that CloudFormation waits for the nested stack to reach the CREATE_COMPLETE state.

When CloudFormation detects that the nested stack has reached the CREATE_COMPLETE state, it marks the nested stack resource as CREATE_COMPLETE in the parent stack and resumes creating the parent stack. If the timeout period expires before the nested stack reaches CREATE_COMPLETE, CloudFormation marks the nested stack as failed and rolls back both the nested stack and parent stack.

Properties

NameTypeDescription
accountstringThe AWS account into which this stack will be deployed.
artifactIdstringThe ID of the cloud assembly artifact for this stack.
availabilityZonesstring[]Returns the list of AZs that are available in the AWS environment (account/region) associated with this stack.
bundlingRequiredbooleanIndicates whether the stack requires bundling or not.
dependenciesStack[]Return the stacks this stack depends on.
environmentstringThe environment coordinates in which this stack is deployed.
nestedbooleanIndicates if this is a nested stack, in which case parentStack will include a reference to it's parent.
nodeNodeThe tree node.
notificationArnsstring[]Returns the list of notification Amazon Resource Names (ARNs) for the current stack.
partitionstringThe partition in which this stack is defined.
regionstringThe AWS region into which this stack will be deployed (e.g. us-west-2).
stackIdstringAn attribute that represents the ID of the stack.
stackNamestringAn attribute that represents the name of the nested stack.
synthesizerIStackSynthesizerSynthesis method for this stack.
tagsTagManagerTags to be applied to the stack.
templateFilestringThe name of the CloudFormation template file emitted to the output directory during synthesis.
templateOptionsITemplateOptionsOptions for CloudFormation template (like version, transform, description).
urlSuffixstringThe Amazon domain suffix for the region in which this stack is defined.
nestedStackParent?StackIf this is a nested stack, returns it's parent stack.
nestedStackResource?CfnResourceIf this is a nested stack, this represents its AWS::CloudFormation::Stack resource.
terminationProtection?booleanWhether termination protection is enabled for this stack.

account

Type: string

The AWS account into which this stack will be deployed.

This value is resolved according to the following rules:

  1. The value provided to env.account when the stack is defined. This can either be a concrete account (e.g. 585695031111) or the Aws.ACCOUNT_ID token.
  2. Aws.ACCOUNT_ID, which represents the CloudFormation intrinsic reference { "Ref": "AWS::AccountId" } encoded as a string token.

Preferably, you should use the return value as an opaque string and not attempt to parse it to implement your logic. If you do, you must first check that it is a concrete value an not an unresolved token. If this value is an unresolved token (Token.isUnresolved(stack.account) returns true), this implies that the user wishes that this stack will synthesize into a account-agnostic template. In this case, your code should either fail (throw an error, emit a synth error using Annotations.of(construct).addError()) or implement some other region-agnostic behavior.


artifactId

Type: string

The ID of the cloud assembly artifact for this stack.


availabilityZones

Type: string[]

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.


bundlingRequired

Type: boolean

Indicates whether the stack requires bundling or not.


dependencies

Type: Stack[]

Return the stacks this stack depends on.


environment

Type: string

The environment coordinates in which this stack is deployed.

In the form aws://account/region. Use stack.account and stack.region to obtain the specific values, no need to parse.

You can use this value to determine if two stacks are targeting the same environment.

If either stack.account or stack.region are not concrete values (e.g. Aws.ACCOUNT_ID or Aws.REGION) the special strings unknown-account and/or unknown-region will be used respectively to indicate this stack is region/account-agnostic.


nested

Type: boolean

Indicates if this is a nested stack, in which case parentStack will include a reference to it's parent.


node

Type: Node

The tree node.


notificationArns

Type: string[]

Returns the list of notification Amazon Resource Names (ARNs) for the current stack.


partition

Type: string

The partition in which this stack is defined.


region

Type: string

The AWS region into which this stack will be deployed (e.g. us-west-2).

This value is resolved according to the following rules:

  1. The value provided to env.region when the stack is defined. This can either be a concrete region (e.g. us-west-2) or the Aws.REGION token.
  2. Aws.REGION, which is represents the CloudFormation intrinsic reference { "Ref": "AWS::Region" } encoded as a string token.

Preferably, you should use the return value as an opaque string and not attempt to parse it to implement your logic. If you do, you must first check that it is a concrete value an not an unresolved token. If this value is an unresolved token (Token.isUnresolved(stack.region) returns true), this implies that the user wishes that this stack will synthesize into a region-agnostic template. In this case, your code should either fail (throw an error, emit a synth error using Annotations.of(construct).addError()) or implement some other region-agnostic behavior.


stackId

Type: string

An attribute that represents the ID of the stack.

This is a context aware attribute:

  • If this is referenced from the parent stack, it will return { "Ref": "LogicalIdOfNestedStackResource" }.
  • If this is referenced from the context of the nested stack, it will return { "Ref": "AWS::StackId" }

Example value: arn:aws:cloudformation:us-east-2:123456789012:stack/mystack-mynestedstack-sggfrhxhum7w/f449b250-b969-11e0-a185-5081d0136786


stackName

Type: string

An attribute that represents the name of the nested stack.

This is a context aware attribute:

  • If this is referenced from the parent stack, it will return a token that parses the name from the stack ID.
  • If this is referenced from the context of the nested stack, it will return { "Ref": "AWS::StackName" }

Example value: mystack-mynestedstack-sggfrhxhum7w


synthesizer

Type: IStackSynthesizer

Synthesis method for this stack.


tags

Type: TagManager

Tags to be applied to the stack.


templateFile

Type: string

The name of the CloudFormation template file emitted to the output directory during synthesis.

Example value: MyStack.template.json


templateOptions

Type: ITemplateOptions

Options for CloudFormation template (like version, transform, description).


urlSuffix

Type: string

The Amazon domain suffix for the region in which this stack is defined.


nestedStackParent?

Type: Stack (optional)

If this is a nested stack, returns it's parent stack.


nestedStackResource?

Type: CfnResource (optional)

If this is a nested stack, this represents its AWS::CloudFormation::Stack resource.

undefined for top-level (non-nested) stacks.


terminationProtection?

Type: boolean (optional)

Whether termination protection is enabled for this stack.

Methods

NameDescription
addDependency(target, reason?)Add a dependency between this stack and another stack.
addMetadata(key, value)Adds an arbitary key-value pair, with information you want to record about the stack.
addTransform(transform)Add a Transform to this stack. A Transform is a macro that AWS CloudFormation uses to process your template.
exportStringListValue(exportedValue, options?)Create a CloudFormation Export for a string list value.
exportValue(exportedValue, options?)Create a CloudFormation Export for a string value.
formatArn(components)Creates an ARN from components.
getLogicalId(element)Allocates a stack-unique CloudFormation-compatible logical identity for a specific resource.
regionalFact(factName, defaultValue?)Look up a fact value for the given fact for the region of this stack.
renameLogicalId(oldId, newId)Rename a generated logical identities.
reportMissingContextKey(report)Indicate that a context key was expected.
resolve(obj)Resolve a tokenized value in the context of the current stack.
setParameter(name, value)Assign a value to one of the nested stack parameters.
splitArn(arn, arnFormat)Splits the provided ARN into its components.
toJsonString(obj, space?)Convert an object, potentially containing tokens, to a JSON string.
toString()Returns a string representation of this construct.
toYamlString(obj)Convert an object, potentially containing tokens, to a YAML string.
static isNestedStack(x)Checks if x is an object of type NestedStack.

addDependency(target, reason?)

public addDependency(target: Stack, reason?: string): void

Parameters

  • target Stack
  • reason string

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.


addMetadata(key, value)

public addMetadata(key: string, value: any): void

Parameters

  • key string
  • value any

Adds an arbitary key-value pair, with information you want to record about the stack.

These get translated to the Metadata section of the generated template.

See also: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/metadata-section-structure.html


addTransform(transform)

public addTransform(transform: string): void

Parameters

  • transform string — The transform to add.

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 also: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/transform-section-structure.html Example

declare const stack: Stack;

stack.addTransform('AWS::Serverless-2016-10-31')

exportStringListValue(exportedValue, options?)

public exportStringListValue(exportedValue: any, options?: ExportValueOptions): string[]

Parameters

  • exportedValue any
  • options ExportValueOptions

Returns

  • string[]

Create a CloudFormation Export for a string list value.

Returns a string list representing the corresponding Fn.importValue() expression for this Export. The export expression is automatically wrapped with an Fn::Join and the import value with an Fn::Split, since CloudFormation can only export strings. 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.

See exportValue for an example of this process.


exportValue(exportedValue, options?)

public exportValue(exportedValue: any, options?: ExportValueOptions): string

Parameters

  • exportedValue any
  • options ExportValueOptions

Returns

  • string

Create a CloudFormation Export for a string 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).

formatArn(components)

public formatArn(components: ArnComponents): string

Parameters

  • components ArnComponents

Returns

  • string

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'.


getLogicalId(element)

public getLogicalId(element: CfnElement): string

Parameters

  • element CfnElement — The CloudFormation element for which a logical identity is needed.

Returns

  • string

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.


regionalFact(factName, defaultValue?)

public regionalFact(factName: string, defaultValue?: string): string

Parameters

  • factName string
  • defaultValue string

Returns

  • string

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.


renameLogicalId(oldId, newId)

public renameLogicalId(oldId: string, newId: string): void

Parameters

  • oldId string
  • newId string

Rename a generated logical identities.

To modify the naming scheme strategy, extend the Stack class and override the allocateLogicalId method.


reportMissingContextKey(report)

public reportMissingContextKey(report: MissingContext): void

Parameters

  • report MissingContext — The set of parameters needed to obtain the context.

Indicate that a context key was expected.

Contains instructions which will be emitted into the cloud assembly on how the key should be supplied.


resolve(obj)

public resolve(obj: any): any

Parameters

  • obj any

Returns

  • any

Resolve a tokenized value in the context of the current stack.


setParameter(name, value)

public setParameter(name: string, value: string): void

Parameters

  • name string — The parameter name (ID).
  • value string — The value to assign.

Assign a value to one of the nested stack parameters.


splitArn(arn, arnFormat)

public splitArn(arn: string, arnFormat: ArnFormat): ArnComponents

Parameters

  • arn string — the ARN to split into its components.
  • arnFormat ArnFormat — the expected format of 'arn' - depends on what format the service 'arn' represents uses.

Returns

  • ArnComponents

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).


toJsonString(obj, space?)

public toJsonString(obj: any, space?: number): string

Parameters

  • obj any
  • space number

Returns

  • string

Convert an object, potentially containing tokens, to a JSON string.


toString()

public toString(): string

Returns

  • string

Returns a string representation of this construct.


toYamlString(obj)

public toYamlString(obj: any): string

Parameters

  • obj any

Returns

  • string

Convert an object, potentially containing tokens, to a YAML string.


static isNestedStack(x)

public static isNestedStack(x: any): boolean

Parameters

  • x any

Returns

  • boolean

Checks if x is an object of type NestedStack.