10
votes

I get that I can create resources using CloudFormation, and that I can also create a VPC using CloudFormation, along with the resources inside it.

Can I create a stack, using a CloudFormation template, inside a pre-existing VPC? For example, let's say that I have a VPC for my company, and there is a Services segment, some production segments (private and public), and maybe some Development segments.

I want to define each set of services - Services, production environment, Development environments - with its own CloudFormation template inside the VPC.

Can I do that?

4
Using the subnet-id in each resources definition is not enough? - Guy
I didn't know you could! - deitch

4 Answers

11
votes

Since this isn't documented very well, and all the examples I've seen (including Julio's) just use a string field prompting for manual entry of the VPC ID, here is the best way.

You can have your template prompt you with a drop-down showing all existing VPCs, allowing you to select one.

Use the AWS::EC2::VPC::Id property in your template:

{
  "Parameters" : {
    "VpcId" : {
      "Type" : "AWS::EC2::VPC::Id",
      "Description" : "VpcId of your existing Virtual Private Cloud (VPC)"
    }
  }
}

http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html

10
votes

Yes, you can. You can either pass the subnet id as a parameter and create resources inside those subnets or pass the vpc id as a parameter and create the subnets and resources inside it.

For example, this template will create an RDS database inside an existing VPC: https://s3.amazonaws.com/cloudformation-templates-us-east-1/RDS_VPC.template

0
votes

Interesting I was about to point out it should be List<> but I tested both and your approach works as well.

"VpcId" : {
  "Type" : "List<AWS::EC2::VPC::Id>",
  "Description" : "VpcId Ids"
}
0
votes

Yes you can. The stack defined in another file is for the master JSON a resource of type stack. Of course you must tell where to retrieve the other JSON/YML file.

Cloudformation is not easy so I would suggest try with an existing architecture and modify step by step.

This example should help you.