This is the AWS CDK v2 Developer Guide. If you're using v1, see the CDK v1 Developer Guide. CDK v1 enters maintenance on June 1, 2022.
Get a value from a context variable
You can specify a context variable either as part of an AWS CDK CLI command, or in
cdk.json
.
To create a command line context variable, use the --context (-c) option, as shown in the following example.
cdk synth -c bucket_name=mygroovybucket
To specify the same context variable and value in the cdk.json
file, use the
following code.
{ "context": { "bucket_name": "myotherbucket" } }
To get the value of a context variable in your app, use the TryGetContext
method in the context of a construct (that is, when this
, or self
in
Python, is an instance of some construct). The example gets the context value bucket_name. If the requested value is not defined,
TryGetContext
returns undefined
(None
in Python;
null
in Java and C#) rather than raising an exception.
Outside the context of a construct, you can access the context variable from the app object, like this.
For more details on working with context variables, see Runtime context.