Created
January 25, 2019 08:45
-
-
Save vatshat/5ff6efcbcf3f02faf3a589cb3eba05a8 to your computer and use it in GitHub Desktop.
Create alarm for each metric generated with a dimension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# metric math alarms | |
aws cloudwatch put-metric-alarm --alarm-name test2 --evaluation-periods 2 --alarm-actions arn:aws:sns:eu-west-1:037559324442:cloudwatch-sqs --threshold 1 --comparison-operator GreaterThanThreshold --metrics '[{"Id":"e1","Label":"Expression1","ReturnData":true,"Expression":"SUM(METRICS()/2)"},{"Id":"m1","ReturnData":false,"MetricStat":{"Metric":{"MetricName":"Available","Dimensions":[{"Name":"WorkspaceId","Value":"ws-fdw4f2pt8"}],"Namespace":"AWS/WorkSpaces"},"Period":300,"Stat":"Average"}}]' | |
metrics=$(cat ~/temp/temp2.json | | |
#temp=$(aws cloudwatch list-metrics --metric-name CPUUtilization --namespace AWS/EC2 --region eu-west-1 --query "Metrics[?Dimensions[0].Name == 'InstanceId']" | | |
# when using timestamp as an ID - now | tostring | split(".")[1] | |
jq '[. | | |
[ | |
keys[] as $k | .[$k] | .key=$k | |
] | .[] | | |
{ | |
"Id": [ "m", .key | tostring ] | join(""), | |
"ReturnData": false, | |
"MetricStat": { | |
"Metric": { | |
"MetricName": "CPUUtilization", | |
"Dimensions": [{ | |
"Name": "CacheClusterId", | |
"Value": .Dimensions[0].Value | |
}], | |
"Namespace": .Namespace | |
}, | |
"Period": 300, | |
"Stat": "Average" | |
} | |
}]') | |
putAlarm() | |
{ | |
slice=$(echo $1 | jq --argjson batch $2 --argjson len $3 ' | |
.[$len-$batch:$len] | . += | |
[{ | |
"Id": "e1", | |
"Label": "Expression1", | |
"ReturnData": true, | |
"Expression": "AVG(METRICS())" | |
}]') && \ | |
name="cli-script-alarm-${3}" | |
if [ $( echo $slice | jq 'length' ) -gt 1 ] | |
then | |
aws cloudwatch put-metric-alarm \ | |
--alarm-name $name \ | |
--evaluation-periods 2 \ | |
--alarm-actions arn:aws:sns:eu-west-1:037559324442:cloudwatch-sqs \ | |
--threshold 1 \ | |
--comparison-operator GreaterThanThreshold \ | |
--metrics "$slice" && | |
printf "Alarm \"$name\" has been created\n" | |
fi | |
} | |
len=$( echo $metrics | jq 'length') | |
until [ $len -lt 0 ] | |
do | |
length=$len | |
len=`expr $len - 9` | |
if [ $length -lt 9 ] | |
then | |
putAlarm "$metrics" 9 $length | |
batch=`expr 9 + $len` | |
putAlarm "$metrics" $batch $batch | |
else | |
putAlarm "$metrics" 9 $length | |
fi | |
done | |
# to delete the alarms | |
temp=$( aws cloudwatch describe-alarms --query "MetricAlarms[?contains(AlarmName,'cli-script-alarm')].AlarmName" --output text ) && | |
aws cloudwatch delete-alarms --alarm-names $temp |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment