CloudFormation – Create subnet if it doesnt exist

amazon-cloudformationsubnet

Using CloudFormation templates is it possible to ensure a subnet is created if it does not already exist?

The use case is for when running a stack deployment in an existing VPC, that VPC may or may not have other resources using the specified subnet.

It seems like this would be a common request but I can't find any documentation on it.

I guess I could assume the subnets I'm working with always exist but that doesn't seem particularly robust.

Best Answer

Generally speaking, no. CloudFormation's resources are always created.

The reason for this is to ensure that a CloudFormation stack's resouces are isolated and can be fully controlled by one-and-only-one stack.

If you want to use an existing subnet, you have a few options:

  1. Hardcode the subnet ID into your template and use it,
  2. Pass a subnet ID into your stack as a parameter,
  3. Use the new CloudFormation stack resource references to reference resource in other stacks.

If you really need to use a create-if-not-exists resource, you may be able to do it using custom resources. However, you'll have to worry about what to do on stack cleanup and rollbacks.