I understand that it is not possible to use NumberofInstance property in Cloudformation, I have used "DesiredCapacity" in AWS::AutoScaling::AutoScalingGroup, But I would like to know if there is any alternative for this, like using iteration inside the template

or use customer scripts under user data to create identical instances

1

There are 1 best solutions below

1
On

Unfortunately, although the EC2 RunInstances API supports launching multiple EC2 instances (via MaxCount/MinCount parameters), the AWS::EC2::Instance CloudFormation resource only allows you to create a single EC2 instance at a time (see also this forum post for confirmation from ChrisW@AWS on this limitation).

In addition, iteration inside the template is not possible using CloudFormation's Intrinsic Functions, so that is not an option either.

As an alternative, I would recommend using an intermediate template format, then compile down to a CloudFormation-template (JSON or YML) using a preprocessor when greater expressive power is needed. You can use a full-featured library like troposphere, but it's also easy enough to code up your own basic preprocessing layer to suit your use-case and programming-language/library preferences.

My current choice is embedded Ruby (ERB), mostly because I'm already familiar with it. Here's an example template.yml.erb file using iteration that generates a CloudFormation YAML:

Resources:
<% (1..5).each do |i| -%>
  Instance<%=i%>:
    Type: AWS::EC2::Instance
    # ...etc etc...
<% end -%>

To process, run cat template.yml.erb | | ruby -rerb -e "puts ERB.new(ARGF.read, nil, '-').result" > template.yml, which will write the following CloudFormation-ready template to template.yml:

Resources:
  Instance1:
    Type: AWS::EC2::Instance
    # ...etc etc...
  Instance2:
    Type: AWS::EC2::Instance
    # ...etc etc...
  Instance3:
    Type: AWS::EC2::Instance
    # ...etc etc...
  Instance4:
    Type: AWS::EC2::Instance
    # ...etc etc...
  Instance5:
    Type: AWS::EC2::Instance
    # ...etc etc...

I've used this technique to help manage large numbers of resources in complex CloudFormation stacks with good results.