2

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

Vineet
  • 21
  • 4
  • This [SO post](https://stackoverflow.com/questions/59301265/how-to-import-existing-vpc-in-aws-cdk) might help you detect current VPC. – vmachan Jul 17 '21 at 18:10
  • I looked at this post previously, unfortunately it uses vpc name from lookup which will result in hard coding of vpc name and app will no more be flexible. – Vineet Jul 17 '21 at 23:48

2 Answers2

1

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.

jonlegend
  • 361
  • 2
  • 6
  • our Tags vary across various vpc. This will again result in hardcoding ! – Vineet Jul 20 '21 at 06:18
  • Add a new tag that does not vary between the VPCs. – jonlegend Jul 20 '21 at 15:01
  • I understand adding the tag is easy but when dealing with many vpc the tags will vary. I am looking for some other solution... which does not require any sort of hardcoding of tags or ids. is there no way we can achieve that ! – Vineet Jul 20 '21 at 23:24
0

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

Vineet
  • 21
  • 4