Last active
March 1, 2023 08:30
-
-
Save myh-st/c6e96b08418ea868a5bc77d4da16e80d to your computer and use it in GitHub Desktop.
calculate SLA from Cloudwatch metric
This file contains hidden or 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
| #!/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%" |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(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:
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.