Reputation: 13
Suppose I am working on an app for a grocery shop. We all know there are hundreds of grocery items in a grocery shop. Now, my requirement is to create a AWS Cloudwatch alarm using AWS Cloudformation template (CFT).
Earlier suppose we have only rice and wheat in our grocery shop and thus we created separate alarm resources in the CFT. An example:
{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "AWS cloudwatch Grocery",
"Parameters": {
"Email": {
"Type": "String",
"Description": "Email address to notify when alarm is triggered",
"Default": "[email protected]"
}
},
"Resources": {
"AlarmNotificationTopic": {
"Type": "AWS::SNS::Topic",
"Properties": {
"Subscription": [
{
"Endpoint": {
"Ref": "Email"
},
"Protocol": "email"
}
]
}
},
"RiceQuantityLowAlarm": {
"Type": "AWS::CloudWatch::Alarm",
"Properties": {
"AlarmName": "RiceQuantityLowAlarm",
"AlarmDescription": "Alarm which gets triggered when Rice quantity is low",
"AlarmActions": [
{
"Ref": "AlarmNotificationTopicTest"
}
],
"MetricName": "Quantity",
"Namespace": "Grocery",
"Dimensions": [
{
"Name": "Item",
"Value": "Rice"
}
],
"ComparisonOperator": "LessThanOrEqualToThreshold",
"EvaluationPeriods": "10",
"Period": "360",
"Statistic": "Sum",
"Threshold": "1",
"TreatMissingData": "notBreaching"
}
},
"WheatQuantityLowAlarm": {
"Type": "AWS::CloudWatch::Alarm",
"Properties": {
"AlarmName": "WheatQuantityLowAlarm",
"AlarmDescription": "Alarm which gets triggered when Wheat quantity is low",
"AlarmActions": [
{
"Ref": "AlarmNotificationTopicTest"
}
],
"MetricName": "Quantity",
"Namespace": "Grocery",
"Dimensions": [
{
"Name": "Item",
"Value": "Wheat"
}
],
"ComparisonOperator": "LessThanOrEqualToThreshold",
"EvaluationPeriods": "10",
"Period": "360",
"Statistic": "Sum",
"Threshold": "1",
"TreatMissingData": "notBreaching"
}
}
}
}
Now lets suppose I want to add more items into my grocery shop and I do not want to be limited only to rice and wheat. In this case, let's assume I want to add 5 new items into my grocery shop. So, if I follow the above approach I will be creating 5 new separate cloudwatch alarm resources into the CFT and will do so whenever any new item comes. But I DO NOT WANT TO DO THAT AS I AM VERY LAZY.
Is there any way we can standardize the CFT resources ? You can see there is only the difference in name (rice/wheat) above in CFT cloudwatch alarm resources and rest everything is common between both.
Upvotes: 1
Views: 1978
Reputation: 22821
This is not really possible with pure CloudFormation. The templates are declarative and you cannot use code constructs such as loops to generate resources. The following list outlines some ways (in no particular order) you could make the templates more dynamic or be able to reuse code:
Each of these have their own pros and cons, and all involve significantly more work than ctrl/cmd+c, ctrl/cmd+v so bear this in mind when making a decision!
Upvotes: 1