Skip to content

Instantly share code, notes, and snippets.

@myh-st
Last active March 1, 2023 08:30
Show Gist options
  • Save myh-st/c6e96b08418ea868a5bc77d4da16e80d to your computer and use it in GitHub Desktop.
Save myh-st/c6e96b08418ea868a5bc77d4da16e80d to your computer and use it in GitHub Desktop.
calculate SLA from Cloudwatch metric
#!/bin/bash
INSTANCE_ID="i-0axxxxxxxxxx"
NAMESPACE="AWS/EC2"
METRIC_NAME="StatusCheckFailed_Instance"
START_TIME=$(date -u -d '30 day ago' +%Y-%m-%dT%H:%M:%SZ)
END_TIME=$(date -u +%Y-%m-%dT%H:%M:%SZ)
AWS_PROFILE=my_profile
# Retrieve the metric data
DATA=$(aws cloudwatch get-metric-data \
--metric-data-queries '[
{
"Id": "m1",
"MetricStat": {
"Metric": {
"Namespace": "'"$NAMESPACE"'",
"MetricName": "'"$METRIC_NAME"'",
"Dimensions": [
{
"Name": "InstanceId",
"Value": "'"$INSTANCE_ID"'"
}
]
},
"Period": 300,
"Stat": "Maximum"
},
"ReturnData": true
}
]' \
--start-time "$START_TIME" \
--end-time "$END_TIME" \
--scan-by 'TimestampDescending' \
--query 'MetricDataResults[0].Values[]' \
--profile "$AWS_PROFILE" \
--output 'text')
# Calculate the SLA percentage
SUM=$(echo $DATA | tr ' ' '\n' | awk '{sum += $1} END {print sum}')
#echo "SUM=$SUM"
TOTAL=$(echo $DATA | tr ' ' '\n' | wc -l)
#echo "TOTAL=$TOTAL"
SLA=$(echo "scale=2; (100 * ($SUM * 5 - 43200)) / 43200" | bc | awk '{print ($1 < 0) ? -$1 : $1}' )
echo "SLA=$SLA"
# Print the result
echo "SLA for $METRIC_NAME on instance $INSTANCE_ID over the last 30 days: $SLA%"
@myh-st
Copy link
Author

myh-st commented Mar 1, 2023

Replace

INSTANCE_ID
AWS_PROFILE

to your aws

@myh-st
Copy link
Author

myh-st commented Mar 1, 2023

(echo "scale=2; (100 * ($SUM * 5 - 43200)) / 43200" | bc | awk '{print ($1 < 0) ? -$1 : $1}' )

$SUM = sum datapoint results
Example $SUM = 16

This command will perform the following sequence of calculations:

  1. Multiply 16 and 5 to get 80.
  2. Subtract 43200 from 80 to get -43120.
  3. Multiply -43120 and 100 to get -4312000.
  4. Divide -4312000 by 43200 to get -99.81481....
  5. The absolute value of -99.81481... is 99.81481....
  6. bc rounds the result to a scale of 2, which gives the final output of 99.81.

Therefore, the bc command will calculate the sequence of (16 * 5), 43200 - result from 1, (result from 2) * 100, and (result from 3) / 43200 as 99.81.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment