Vineet
Vineet

Reputation: 21

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

Upvotes: 2

Views: 3332

Answers (2)

Vineet
Vineet

Reputation: 21

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();

Upvotes: 0

Jon Legendre
Jon Legendre

Reputation: 370

If you are not deploying the VPC with CDK (or at least not in one of the stacks you are using), I suggest using a tag on each VPC to identify them as the VPC to which to deploy this code. Note this solution assumes that you will have a single one of these VPCs per account. If each of these VPCs had a tag like "type":"appDeploy", you could write CDK code like:

    const vpcId = ec2.Vpc.fromLookup(this, 'VPC', tags:{"type":"appDeploy"})

The alternate path I alluded to above is to deploy the VPC as part of this stack or a parent stack, so you can reference it directly.

Upvotes: 1

Related Questions