13

Is it possible to obtain a VPC Id using Cloud Formation JSON?

Something like:

{ "Fn::GetAtt" : [ "MyVPCName", "VPCId" ] }
lrepolho
  • 951
  • 1
  • 12
  • 23

4 Answers4

14

You can use the "Ref" built-in function to get the VPC's resource ID iff you created the VPC in the same template, see the Return Values section of http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html

If you are wanting to reference an existing VPC (like your default VPC), then the above won't work. You could pass the VPC's Id as a parameter to the template instead and use the "Ref" built-in to use it where you need it.

9

For a pre-existing VPC, start with the Parameter:

    "VpcId": { "Type": "String" },

Then you can use something like this with your launch script:

aws --profile profile_name --region us-east-1 ec2 describe-vpcs --filters 'Name=tag:Name,Values=MY_VPC_NAME'

This way you find the VPC before you launch the stack. In this way you can launch to different regions or accounts without having to always look up that information by hand.

  • is there a function we can use like Fn::get or select and then filter with property `isDefault` to get the default vpc in the region? – Mohamad Eghlima Mar 29 '22 at 04:18
2

Bradley's answer is right. I'd also add that you might want to look into nested stacks if you find you need to "sew together" resources that are created in separate templates. Another option is to add some code layer that generates the template (e.g. cfn-pyplates) and use the AWS API to do those lookups across stacks.

Assaf Lavie
  • 73,079
  • 34
  • 148
  • 203
1

Important values like this I would recommend be put into CFN exports. And then easily referenced with something like this.

YAML code example

VpcId: !ImportValue VpcId

JSON code example

"VpcId" : {"Fn::ImportValue" : "VpcId"}

Link to AWS documentation on how to import CloudFormation exports

Link to AWS documentation on creating CloudFormation Outputs and Exports

Evan Nadeau
  • 141
  • 5