amazon-web-servicesaws-cdkaws-cdk-context

Pass CDK context values per deployment environment


I am using context to pass values to CDK. Is there currently a way to define project context file per deployment environment (dev, test) so that when the number of values that I have to pass grow, they will be easier to manage compared to passing the values in the command-line:

cdk synth --context bucketName1=my-dev-bucket1 --context bucketName2=my-dev-bucket2 MyStack

It would be possible to use one cdk.json context file and only pass the environment as the context value in the command-line, and depending on it's value select the correct values:

{
  ...
  "context": {
    "devBucketName1": "my-dev-bucket1",
    "devBucketName2": "my-dev-bucket2",
    "testBucketName1": "my-test-bucket1",
    "testBucketName2": "my-test-bucket2",
  }
}

But preferably, I would like to split it into separate files, f.e. cdk.dev.json and cdk.test.json which would contain their corresponding values, and use the correct one depending on the environment.


Solution

  • According to the documentation, CDK will look for context in one of several places. However, there's no mention of defining multiple/additional files.

    The best solution I've been able to come up with is to make use of JSON to separate context out per environment:

    "context": {
      "dev": {
        "bucketName": "my-dev-bucket"
      }
      "prod": {
        "bucketName": "my-prod-bucket"
      }
    }
    

    This allows you to access the different values programmatically depending on which environment CDK is deploying to.

    let myEnv = dev         // This could be passed in as a property of the class instead and accessed via props.myEnv
    
    const myBucket = new s3.Bucket(this, "MyBucket", {
      bucketName: app.node.tryGetContext(myEnv).bucketName
    })