Skip to content

Instantly share code, notes, and snippets.

@thomsh
Last active January 7, 2020 23:49
Show Gist options
  • Save thomsh/3ff3ac574553c8fe73a5b282cc9e6ce6 to your computer and use it in GitHub Desktop.
Save thomsh/3ff3ac574553c8fe73a5b282cc9e6ce6 to your computer and use it in GitHub Desktop.
Get CPU credits Usage and remaining via local metadata on EC2 instance
#!/usr/bin/env bash
echo "Get CPU credits Usage and remaining via local metadata on EC2"
set -euo pipefail
AWS_DEFAULT_REGION="$(curl -s 169.254.169.254/latest/meta-data/placement/availability-zone)"
AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION::-1}" # strip char from az
INSTANCE="$(curl -s 169.254.169.254/latest/meta-data/instance-id )"
FREQUENCY=600 # Get a point every 10 min
LAST="180 minutes ago"
START="$(date +'%Y-%m-%dT%H:%M:59Z' --utc -d "${LAST}" )"
END="$(date +'%Y-%m-%dT%H:%M:59Z' --utc )"
DIMENSION="{\"Name\":\"InstanceId\",\"Value\":\"${INSTANCE}\"}"
RED='\033[0;31m'
NC='\033[0m' # No Color
# http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/viewing_metrics_with_cloudwatch.html
for m in CPUCreditBalance CPUCreditUsage; do
echo "---------------------------------------------"
echo -e "${RED}$m for ${INSTANCE} (last ${LAST::-4})${NC}"
aws cloudwatch get-metric-statistics \
--namespace 'AWS/EC2' \
--region "$AWS_DEFAULT_REGION" \
--period "$FREQUENCY" \
--start-time "$START" \
--end-time "$END" \
--metric-name "$m" \
--dimensions "$DIMENSION" \
--statistic Average \
--query 'Datapoints[*].[Timestamp,Average,Unit]' \
--output text \
| awk '{printf("%s %.2f\n", $1,$2)}' \
| sort \
| column -t
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment