How to create variable number of EC2 instance resources in Cloudformation template, according to a template parameter?
The EC2 API and management tools allow launching multiple instances of the same AMI, but I can't find how to do this using Cloudformation.
Best Answer
The
AWS::EC2::Instance
Resource doesn't support theMinCount
/MaxCount
parameters of the underlyingRunInstances
API, so it's not possible to create a variable number of EC2 instances by passing Parameters to a single copy of this Resource.To create a variable number of EC2 instance resources in CloudFormation template according to a template Parameter, and without deploying an Auto Scaling Group instead, there are two options:
1. Conditions
You can use
Conditions
to create a variable number ofAWS::EC2::Instance
Resources depending on the Parameter.It's a little verbose (because you have to use
Fn::Equals
), but it works.Here's a working example that allows the user to specify up to a maximum of 5 instances:
1a. Template preprocessor with Conditions
As a variation on the above, you can use a template preprocessor like Ruby's Erb to generate the above template based on a specified maximum, making your source code more compact and eliminating duplication:
To process the above source into a CloudFormation-compatible template, run:
For convenience, here is a gist with the generated output YAML for 10 variable EC2 instances.
2. Custom Resource
An alternate approach is to implement a Custom Resource that calls the
RunInstances
/TerminateInstances
APIs directly: