marcincuber
marcincuber

Reputation: 3791

Cloudformation yaml- generate a list of instances in AutoScalingGroup resource

I am struggling to figure out how to write overrides section of the yaml template for AutoScalingGroup resource. Currently, what I have only works for a fixed length of the string. In this case string passed into the template is called InstanceTypesOverride.

Below you can see the snippet of the code:

InstanceTypesOverride = "m5.large,m5d.large,m5a.large"

Type: AWS::AutoScaling::AutoScalingGroup
  Properties:
    AutoScalingGroupName: !Ref NodeGroupName
    DesiredCapacity: !Ref NodeAutoScalingGroupDesiredCapacity
    MixedInstancesPolicy:
      InstancesDistribution:
        OnDemandAllocationStrategy: prioritized
        OnDemandBaseCapacity: !Ref OnDemandBaseCapacity
        OnDemandPercentageAboveBaseCapacity: !Ref OnDemandPercentageAboveBaseCapacity
        SpotAllocationStrategy: !Ref SpotAllocStrategy
      LaunchTemplate:
        LaunchTemplateSpecification:
          LaunchTemplateId: !Ref SpotLaunchTemplate
          Version: !GetAtt SpotLaunchTemplate.LatestVersionNumber
        Overrides:
          - InstanceType: !Select [0, !Split [ ",", !Ref InstanceTypesOverride ] ]
          - InstanceType: !Select [1, !Split [ ",", !Ref InstanceTypesOverride ] ]
          - InstanceType: !Select [2, !Split [ ",", !Ref InstanceTypesOverride ] ]

I would like to find out whether it is possible to write the overrides section of the template so that InstanceTypesOverride can handle more instance types or less. As you know, various regions can handle different instances types, therefore it is essential for me to have the ability for the cloudformation to work with different string lengths. Can someone suggest something that would work?

Ideally, I would like to have a cfm template which works with both InstanceTypesOverride = "m5.large,m5d.large,m5a.large" and InstanceTypesOverride = "m5.large,m5d.large,m5a.large,m5ad.large,m5n.large,m5dn.large"

Upvotes: 2

Views: 299

Answers (1)

Marcin
Marcin

Reputation: 238061

Sadly, you can't do this using plain CloudFormation (CFN). This would require looping mechanisms which are not supported in CFN.

The only way to do it would be through CFN custom resources or CFN macro.

In the first case you would have to develop a custom lambda function which would create the entire AutoScalingGroup using AWS SDK (e.g. python). In the second case, lambda would also need to be created but it would parse the original template, expand the Overrides, and return the modified template to CFN for execution.

Alternative is to not use CFN, but terraform (TF) for example. TF has very reach and extensive support for loops which would allow you to easily do what you want.

Upvotes: 2

Related Questions