typescriptamazon-web-servicesaws-cdkaws-cdk-typescript

CDK : why does CDK not able to understand codepieline variable syntax at runtime?


I am trying to achieve a very simple thing Try to defined variables syntax for codepipeline manual approval action.

The variable value is coming from the previous stage which is being exported successfully.

cdk context

  "namespace": "nameSpaceValue",
    "variable1": "variableValue1",

cdk code where I am using context values

 const manualApprovalAction = new codepipeline_actions.ManualApprovalAction({
      actionName: "Approve",
      notificationTopic: manualApprovalNotificationTopic,
      additionalInformation: '#{' + props.namespace + '.' + props.variableValue1 + '}',

    });

Error I recieve

Valid format for a pipeline execution variable reference is a namespace and a key separated by a period (.). The following pipeline execution variables are referencing a namespace that does not exist.

In my opinion, I think cdk is not able to understand #{} characters at runtime.

If I directly add these values in cdk context it works.


Solution

  • Another way you can provide the variables from the CDK context is by obtaining the values via this.node.tryGetContext as described here:

    // cdk.json
    {
      "app": "npx ts-node --prefer-ts-exts ...",
      "context": {
       "namespace": "nameSpaceValue",
       "variable1": "variableValue1"
     }
    }
    

    And now in the CDK code itself:

    // stack declaration code...
    const namespace = this.node.tryGetContext('namespace');
    const variable1 = this.node.tryGetContext('variable1');
    
    ...
    
    const manualApprovalAction = new codepipeline_actions.ManualApprovalAction({
          actionName: "Approve",
          notificationTopic: manualApprovalNotificationTopic,
          additionalInformation: `#{${namespace}.${variable1}}`,
        });
    

    If you also have different environments you can separate them out per environment in the cdk.json file as such:

    // cdk.json
    {
      "app": "npx ts-node --prefer-ts-exts ...",
      "context": {
      "test": {
         "namespace": "test-space-value",
         "variable1": "test-value"
      },
      "acc": {
         "namespace": "acc-space-value",
         "variable1": "acc-value"
      },
      "prod": {
         "namespace": "prod-space-value",
         "variable1": "prod-value"
      },
     }
    }
    

    And in the CDK code itself you can retrieve the entire environment context

    // stack declaration code...
    const envVariables = this.node.tryGetContext('test');
    const { namespace, variable1 } = envVariables;