John
John

Reputation: 11831

How do I pass in values to AWS CDK at deploy time?

How do I pass in values to AWS CDK at deploy time (not synth time)?

I can see that I can retrieve context values within an App:

(String)app.getNode().tryGetContext("keyOfMyValue");

The example above is from the Java API and returns a string where the key value pair was passed using -c keyOfMyValue=someValue. This value is then passed to cdk synth.

Whilst the CLI help for cdk deploy shows an identical Context parameter, I don't see how to access that within a Stack. I specifically don't want to have all values defined at the time of synthesis, I want to pass some simple values (e.g. strings) to CDK at deploy time.

Is there an example of how to do this?

Upvotes: 6

Views: 7615

Answers (3)

Jordan Nelson
Jordan Nelson

Reputation: 653

This snippet will be in .NET but I assume that you can do something similar in Java. Assuming your stack is named astack ...

You can gather the context value with

cdk deploy astack -c environment=prod
var app = new App();
var environment = app.Node.TryGetContext("environment")?.ToString() ?? "dev";

make a class and interface...

public interface IAStackProps : IStackProps
{
    public string Environment { get; set; }
}

public class AStackProps : StackProps, IAStackProps
{
    public string Environment { get; set; }
}

pass it with...

new AStack(app, stackName, new AStackProps {
    Environment = environment,
    ...
});

then you can access it in your stack.

public AStack(Construct scope, string id, IAStackProps props = null) : 
    base(scope, id, props)
{
    // props.Environment

Upvotes: 6

VladH
VladH

Reputation: 702

Passing deploy-time parameters is done with the combination of a) creating CloudFormation template parameters using CfnParameter class, and then b) passing their values with "--parameters" argument of the cdk deploy command. Details at https://docs.aws.amazon.com/cdk/latest/guide/parameters.html.

It's worth nothing that "--context" parameters - the synth-time parameters, may still be passed with cdk deploy, because "cdk deploy" runs "cdk synth" implicitly.

Upvotes: 1

Oleg B
Oleg B

Reputation: 47

Stack is a child of Construct (as App), so - the same way, I guess:

this.getNode().tryGetContext()

Upvotes: 1

Related Questions