typescriptaws-cdk

How to make aws-cdk app that can be deployed to different VPC


I am trying to create environment agnostic app via cdk. The app consists of EC2 with Load balancer and few other aws services. The objective is to automate the process of deployment of the stack in various AWS accounts via jenkins pipelines.

Currently, we have different VPC in each AWS account with different tags. This is getting complex here as how should I make the code, so that it can fetch and use VPC value from the account the cdk code is deployed ?

I tried using vpc as parameter but its not working. What is the best way to do this without hardcoding vpc id or vpc name ?

    const vpcparam = new CfnParameter(this, 'VPCParam', {
      type: 'String',
      description: "Enter the VPC ID ",
      }
    )

    // Allocate to Stack
    const vpcId = ec2.Vpc.fromLookup(this, 'VPC', {
      vpcId: vpcparam.valueAsString
    })

Error All arguments to Vpc.fromLookup() must be concrete (no Tokens) Subprocess exited with error 1


Solution

  • Finally, I got a solution to this problem.

    Steps are listed below

    1. Create SSM parameter with the value of VPC ID
    2. Use Dynamic referencing to resolve the ssm parameters during the run time.
    3. Synthesise the stack using cdk synth with account and region values.
    4. Run cdk deploy

    const vpcId = new CfnDynamicReference(CfnDynamicReferenceService.SSM,'ssm-parameter-name').toString();