Skip to content
v2.273.0

App L2 construct ​

A construct which represents an entire CDK app. This construct is normally the root of the construct tree.

You would normally define an App instance in your program's entrypoint, then define constructs where the app is used as the parent scope.

After all the child constructs are defined within the app, you should call app.synth() which will emit a "cloud assembly" from this app into the directory specified by outdir. Cloud assemblies includes artifacts such as CloudFormation templates and assets that are needed to deploy this app into the AWS cloud.

Example ​

ts
import * as cdk from 'aws-cdk-lib';
import * as s3 from 'aws-cdk-lib/aws-s3';

const app = new cdk.App();
const stack = new cdk.Stack(app, 'Stack');

declare const bucket: s3.IBucket;

new dynamodb.Table(stack, 'Table', {
  partitionKey: {
    name: 'id',
    type: dynamodb.AttributeType.STRING,
  },
  importSource: {
    compressionType: dynamodb.InputCompressionType.GZIP,
    inputFormat: dynamodb.InputFormat.csv({
      delimiter: ',',
      headerList: ['id', 'name'],
    }),
    bucket,
    keyPrefix: 'prefix',
  },
});
python
import aws_cdk as cdk
import aws_cdk.aws_s3 as s3

# bucket: s3.IBucket


app = cdk.App()
stack = cdk.Stack(app, "Stack")

dynamodb.Table(stack, "Table",
    partition_key=dynamodb.Attribute(
        name="id",
        type=dynamodb.AttributeType.STRING
    ),
    import_source=dynamodb.ImportSourceSpecification(
        compression_type=dynamodb.InputCompressionType.GZIP,
        input_format=dynamodb.InputFormat.csv(
            delimiter=",",
            header_list=["id", "name"]
        ),
        bucket=bucket,
        key_prefix="prefix"
    )
)
java
import software.amazon.awscdk.*;
import software.amazon.awscdk.services.s3.*;

IBucket bucket;


App app = new App();
Stack stack = new Stack(app, "Stack");

Table.Builder.create(stack, "Table")
        .partitionKey(Attribute.builder()
                .name("id")
                .type(AttributeType.STRING)
                .build())
        .importSource(ImportSourceSpecification.builder()
                .compressionType(InputCompressionType.GZIP)
                .inputFormat(InputFormat.csv(CsvOptions.builder()
                        .delimiter(",")
                        .headerList(List.of("id", "name"))
                        .build()))
                .bucket(bucket)
                .keyPrefix("prefix")
                .build())
        .build();
csharp
// Install: dotnet add package Amazon.CDK.Lib
using Amazon.CDK;
using Amazon.CDK.AWS.S3;

IBucket bucket;


var app = new App();
var stack = new Stack(app, "Stack");

new Table(stack, "Table", new TableProps {
    PartitionKey = new Attribute {
        Name = "id",
        Type = AttributeType.STRING
    },
    ImportSource = new ImportSourceSpecification {
        CompressionType = InputCompressionType.GZIP,
        InputFormat = InputFormat.Csv(new CsvOptions {
            Delimiter = ",",
            HeaderList = new [] { "id", "name" }
        }),
        Bucket = bucket,
        KeyPrefix = "prefix"
    }
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
import "github.com/aws/aws-cdk-go/awscdk"
import s3 "github.com/aws/aws-cdk-go/awscdk"

var bucket IBucket


app := cdk.NewApp()
stack := cdk.NewStack(app, jsii.String("Stack"))

dynamodb.NewTable(stack, jsii.String("Table"), &TableProps{
	PartitionKey: &Attribute{
		Name: jsii.String("id"),
		Type: dynamodb.AttributeType_STRING,
	},
	ImportSource: &ImportSourceSpecification{
		CompressionType: dynamodb.InputCompressionType_GZIP,
		InputFormat: dynamodb.InputFormat_Csv(&CsvOptions{
			Delimiter: jsii.String(","),
			HeaderList: []*string{
				jsii.String("id"),
				jsii.String("name"),
			},
		}),
		Bucket: *Bucket,
		KeyPrefix: jsii.String("prefix"),
	},
})

Initializer ​

ts
new App(props?: AppProps)
python
App(props: typing.Optional[AppProps] = None)
java
new App(AppProps props)
csharp
new App(AppProps? props = null)
go
NewApp(Props AppProps)

Construct Props ​

analyticsReportingbooleananalytics_reportingboolanalyticsReportingBooleanAnalyticsReportingboolAnalyticsReporting*bool= Value of 'aws:cdk:version-report…#
Include runtime versioning information in the Stacks of this app.
default

Default: Value of 'aws:cdk:version-reporting' context key

autoSynthbooleanauto_synthboolautoSynthBooleanAutoSynthboolAutoSynth*bool= true if running via CDK CLI (`CD…#
Automatically call `synth()` before the program exits.

If you set this, you don't have to call synth() explicitly. Note that this feature is only available for certain programming languages, and calling synth() is still recommended.

default

Default: true if running via CDK CLI (CDK_OUTDIR is set), false otherwise

context{ [key: string]: any }contexttyping.Mapping[str, Any]contextMap<String, Object>ContextIDictionary<string, object>Context*map[string]interface{}= no additional context#
Additional context values for the application.

Context set by the CLI or the context key in cdk.json has precedence.

Context can be read from any construct using node.getContext(key).

defaultStackSynthesizerIReusableStackSynthesizerdefault_stack_synthesizerIReusableStackSynthesizerdefaultStackSynthesizerIReusableStackSynthesizerDefaultStackSynthesizerIReusableStackSynthesizerDefaultStackSynthesizerIReusableStackSynthesizer= A `DefaultStackSynthesizer` with…#
The stack synthesizer to use by default for all Stacks in the App.

The Stack Synthesizer controls aspects of synthesis and deployment, like how assets are referenced and what IAM roles to use. For more information, see the README of the main CDK package.

default

Default: A DefaultStackSynthesizer with default settings

outdirstringoutdirstroutdirStringOutdirstringOutdir*string= If this value is _not_ set, cons…#
The output directory into which to emit synthesized artifacts.
notes · default

You should never need to set this value. By default, the value you pass to the CLI's --output flag will be used, and if you change it to a different directory the CLI will fail to pick up the generated Cloud Assembly.

This property is intended for internal and testing use.

Default: If this value is not set, considers the environment variable CDK_OUTDIR. If CDK_OUTDIR is not defined, uses a temp directory.

performanceReportingbooleanperformance_reportingboolperformanceReportingBooleanPerformanceReportingboolPerformanceReporting*bool= Value of 'aws:cdk:performance-re…#
Produce a performance counter report if supported by the CLI.

The performance report will be produced if the total synthesis time exceeds 10 seconds/stack, unless this property is used to switch the report off altogether (set to false).

default

Default: Value of 'aws:cdk:performance-reporting' context key

policyValidationBeta1IPolicyValidationPluginBeta1[]policy_validation_beta1typing.List[IPolicyValidationPluginBeta1]policyValidationBeta1List<IPolicyValidationPluginBeta1>PolicyValidationBeta1IPolicyValidationPluginBeta1[]PolicyValidationBeta1*[]IPolicyValidationPluginBeta1= no validation pluginsdeprecated#
Use `Validations.of(app).addPlugins()` instead.
postCliContext{ [key: string]: any }post_cli_contexttyping.Mapping[str, Any]postCliContextMap<String, Object>PostCliContextIDictionary<string, object>PostCliContext*map[string]interface{}= no additional context#
Additional context values for the application.
notes · example

Context provided here has precedence over context set by:

  • The CLI via --context
  • The context key in cdk.json
  • The AppProps.context property

This property is recommended over the AppProps.context property since you can make final decision over which context value to take in your app.

Context can be read from any construct using node.getContext(key).

ts
// context from the CLI and from `cdk.json` are stored in the
// CDK_CONTEXT env variable
const cliContext = JSON.parse(process.env.CDK_CONTEXT!);

// determine whether to take the context passed in the CLI or not
const determineValue = process.env.PROD ? cliContext.SOMEKEY : 'my-prod-value';
new App({
  postCliContext: {
    SOMEKEY: determineValue,
  },
});
propertyInjectorsIPropertyInjector[]property_injectorstyping.List[IPropertyInjector]propertyInjectorsList<IPropertyInjector>PropertyInjectorsIPropertyInjector[]PropertyInjectors*[]IPropertyInjector= no PropertyInjectors#
A list of IPropertyInjector attached to this App.
stackTracesbooleanstack_tracesboolstackTracesBooleanStackTracesboolStackTraces*bool= true stack traces are included u…#
Include construct creation stack trace in the `aws:cdk:trace` metadata key of all constructs.
default

Default: true stack traces are included unless aws:cdk:disable-stack-trace is set in the context.

treeMetadatabooleantree_metadatabooltreeMetadataBooleanTreeMetadataboolTreeMetadata*bool= true#
Include construct tree metadata as part of the Cloud Assembly.

Properties ​

accountstringaccountstraccountStringAccountstringAccount*string#
The default account for all resources defined within this stage.
artifactIdstringartifact_idstrartifactIdStringArtifactIdstringArtifactId*stringrequired#
Artifact ID of the assembly if it is a nested stage. The root stage (app) will return an empty string.

Derived from the construct path.

assetOutdirstringasset_outdirstrassetOutdirStringAssetOutdirstringAssetOutdir*stringrequired#
The cloud assembly asset output directory.
nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
outdirstringoutdirstroutdirStringOutdirstringOutdir*stringrequired#
The cloud assembly output directory.
parentStageStageparent_stageStageparentStageStageParentStageStageParentStageStage#
The parent stage or `undefined` if this is the app.
policyValidationBeta1IPolicyValidationPluginBeta1[]policy_validation_beta1typing.List[IPolicyValidationPluginBeta1]policyValidationBeta1List<IPolicyValidationPluginBeta1>PolicyValidationBeta1IPolicyValidationPluginBeta1[]PolicyValidationBeta1*[]IPolicyValidationPluginBeta1= no validation plugins are usedrequireddeprecated#
Do not use this function to look up validation plugins. Use `Validations.of(stage).plugins` instead.

If any plugin reports any violation, synthesis will be interrupted and the report displayed to the user.

regionstringregionstrregionStringRegionstringRegion*string#
The default region for all resources defined within this stage.
stageNamestringstage_namestrstageNameStringStageNamestringStageName*stringrequired#
The name of the stage.

Based on names of the parent stages separated by hypens.

Methods ​

isApp(obj: any): boolean@staticmethod def is_app(obj: Any) -> boolpublic static Boolean isApp(Object obj)public static bool IsApp(object obj)func IsApp(Obj interface{}) *boolstatic#
Checks if an object is an instance of the `App` class.
1 parameter · returns

Parameters

  • objobjobjobjObj — The object to evaluate.

Returns: true if obj is an App.

isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters

  • xxxxX — Any object.

Returns: true if x is an object created from a class which extends Construct.

isStage(x: any): boolean@staticmethod def is_stage(x: Any) -> boolpublic static Boolean isStage(Object x)public static bool IsStage(object x)func IsStage(X interface{}) *boolstatic#
Test whether the given construct is a stage.
of(construct: IConstruct): Stage@staticmethod def of(construct: IConstruct) -> Stagepublic static Stage of(IConstruct construct)public static Stage Of(IConstruct construct)func Of(Construct IConstruct) Stagestatic#
Return the app that is the root of the construct tree, if available.
synth(options?: StageSynthesisOptions): CloudAssemblydef synth(self, options: typing.Optional[StageSynthesisOptions] = None) -> CloudAssemblypublic CloudAssembly synth(StageSynthesisOptions options)public CloudAssembly Synth(StageSynthesisOptions? options = null)func Synth(Options StageSynthesisOptions) CloudAssembly#
Synthesize this App into a cloud assembly.

Once an assembly has been synthesized, it cannot be modified. Subsequent calls will return the same assembly.

toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.

1 parameter · returns

Parameters

  • mixinsmixinsmixinsmixinsMixins — The mixins to apply.

Returns: This construct for chaining