How do I specify subnet and VPC IDs in AWS CloudFormation?

amazon-ec2, amazon-vpc, amazon-web-services, aws-cloudformation

Solution

If you wish to use a specific VPC and subnet, just insert their values:

{
  "Resources": {
    "MyServer": {
      "Type": "AWS::EC2::Instance",
      "Properties": {
        "InstanceType": "t2.micro",
        "SubnetId": "subnet-abc123",
        "ImageId": "ami-abcd1234"
      }
    }
}

A subnet always belongs to a VPC, so specifying the subnet will automatically select the matching VPC.

Problem

I want my CloudFormation template to use existing subnets and VPCs. I don't want to create new ones. How do I parameterize these? When I look at the docs for `AWS::EC2::VPC` and `AWS::EC2::Subnet`, it seems these resources are only for creating new VPCs and subnets. Is that correct? Should I just point the instance resource directly to the existing VPC and subnets I want it to use? For example - if I have an instance resource in my template and I point it directly to an existing subnet, like this: ``` { "Resources": { "MyServer": { "Type": "AWS::EC2::Instance", "Properties": { "InstanceType": { "Ref": "InstanceType" }, "SubnetId": { "Ref": "subnet-abc123" }, ... ``` I get this error when validating the template: ``` Template contains errors.: Template format error: Unresolved resource dependencies [subnet-abc123] in the Resources block of the template ``` I tried to do this with mappings but still getting an error: ``` "Mappings": { "SubnetID": { "TopKey": { "Default": "subnet-abc123" } } ``` And with this in the instance resource: ``` "SubnetId": { "Fn::FindInMap": [ "SubnetID", { "Ref": "TopKey" }, "Default" ] } ``` I get this error when trying to validate: ``` Template contains errors.: Template format error: Unresolved resource dependencies [TopKey] in the Resources block of the template ```

Original source