Jon Erickson
Jon Erickson

Reputation: 114826

Setting up variable number of CloudWatch alarms in a CloudFormation template

We have an ElastiCache Replication group (AWS::ElastiCache::ReplicationGroup) with NumCacheClusters currently set to 2 in a CloudFormation template and want to setup a set of CloudWatch alarms for each CacheClusterId that CloudFormation creates for us as part of the replication group.

There are 2 roadblocks that I am facing:

  1. how do you set up a variable number of resources in the CloudFormation template (want N number of AWS::CloudWatch::Alarm, where N == NumCacheClusters)
  2. A CloudWatch alarm needs the CacheClusterId within the Dimensions property, how do I get that value for each Cache Cluster that CloudFormation creates for us.

BTW, I'm very new to CloudFormation so any resources on the topic would be helpful as well.

Thanks.

Upvotes: 1

Views: 1067

Answers (1)

mfisherca
mfisherca

Reputation: 2499

  1. You unfortunately can't setup a truly variable number of resources in CloudFormation. The best you can do is support a fixed number of conditional resources (e.g. write a template that can create cache clusters with 1-3 nodes). If you have a parameter for the number of cache clusters NumCacheClusters, you could write your conditions like:

    Conditions:
    
      TwoCacheClusters:
        Fn::Or:
          - Fn::Equals:
            - Ref: NumCacheClusters
            - 2
          - Fn::Equals:
            - Ref: NumCacheClusters
            - 3
    
      ThreeCacheClusters:
        Fn::Equals:
          - Ref: NumCacheClusters
          - 3
    

    Then you would conditionally create the CloudWatch alarms:

    Resources:
    
      ...
    
      SecondCloudWatchAlarm:
        Type: AWS::CloudWatch::Alarm
        Condition: TwoCacheClusters
        Properties:
          ...
    
      ThirdCloudWatchAlarm:
        Type: AWS::CloudWatch::Alarm
        Condition: ThreeCacheClusters
        Properties:
          ...
    

    See the CloudFormation Conditions documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/conditions-section-structure.html

  2. You can refer to resources you've created elsewhere in the template using the Ref intrinsic function. I believe Ref returns the cluster ID by default for AWS::ElastiCache::ReplicationGroup, so that is all you should need to use: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-ref.html

    If Ref doesn't return the resource value you want by default, look at using Fn::GetAtt instead to return a specific attribute. The alternate values available depends on the resource type, and they're all listed in the documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-getatt.html

Upvotes: 1

Related Questions