2
votes

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
2

2 Answers

6
votes

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.

4
votes

Specify them in the Parameters section, and refer them in Resources section. CF will let you select the VPC first and then the Subnet.

  "Parameters" : {

    "VpcId" : {
      "Type" : "AWS::EC2::VPC::Id",
      "Description" : "VPCId of Virtual Private Cloud (VPC).",
      "Default" : ""
    },

    "VpcSubnet": {
      "Description" : "SubnetId in VPC",
      "Type" : "AWS::EC2::Subnet::Id",
      "Default" : ""
    },


  "Resources" : {
    ...
    "Ec2Instance" : {
      "Properties" : {
        "SubnetId" : { "Ref" : "VpcSubnet" },