Skip to content

Instantly share code, notes, and snippets.

@mahrous-amer
Last active January 7, 2025 06:22
Show Gist options
  • Save mahrous-amer/32a169e72b1e9dffe92a063e12c046d3 to your computer and use it in GitHub Desktop.
Save mahrous-amer/32a169e72b1e9dffe92a063e12c046d3 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Define variables
REGION="eu-west-1"
PROFILE="default"
OUTPUT_FORMAT="json"
PERIOD_IN_SECONDS=3600
STATISTIC="Maximum"
END_TIME=$(date -u "+%Y-%m-%dT%H:%M:%SZ")
START_TIME=$(date -u -v-7d "+%Y-%m-%dT%H:%M:%SZ")
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text --profile $PROFILE)
# Color definitions
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
CYAN=$(tput setaf 6)
RESET=$(tput sgr0)
# Helper function for visual output
function print_header {
echo -e "${CYAN}==========================================${RESET}"
echo -e "${CYAN}$1${RESET}"
echo -e "${CYAN}==========================================${RESET}"
}
function print_error {
echo -e "${RED}Error: $1${RESET}"
}
function print_success {
echo -e "${GREEN}$1${RESET}"
}
function fetch_and_print {
local description=$1
local command=$2
print_header "$description"
result=$(eval "$command --profile $PROFILE --region $REGION --output $OUTPUT_FORMAT")
if [ $? -eq 0 ]; then
echo "$result" | jq
else
print_error "Failed to fetch $description."
fi
echo ""
}
# Fetch EBS Volumes
print_header "Fetching EBS Volumes"
EBS_VOLUME_ARNS=$(aws ec2 describe-volumes \
--profile $PROFILE --region $REGION \
--query 'Volumes[*].VolumeId' --output text | \
awk -v region=$REGION -v account_id="$ACCOUNT_ID" '{print "arn:aws:ec2:" region ":" account_id ":volume/" $1}')
if [ -z "$EBS_VOLUME_ARNS" ]; then
print_error "No EBS volumes found in the region $REGION."
else
for VOLUME_ARN in $EBS_VOLUME_ARNS; do
fetch_and_print "EBS Volume Recommendations for $VOLUME_ARN" \
"aws compute-optimizer get-ebs-volume-recommendations --volume-arns $VOLUME_ARN"
done
fi
# Fetch EC2 Instance Recommendations
print_header "Fetching EC2 Instance Recommendations"
INSTANCE_ARNS=$(aws compute-optimizer get-ec2-instance-recommendations \
--profile $PROFILE --region $REGION \
--query 'instanceRecommendations[*].instanceArn' --output text)
if [ -z "$INSTANCE_ARNS" ]; then
print_error "No EC2 instances found for recommendations."
else
for INSTANCE_ARN in $INSTANCE_ARNS; do
fetch_and_print "EC2 Recommendation Projected Metrics for $INSTANCE_ARN" \
"aws compute-optimizer get-ec2-recommendation-projected-metrics \
--instance-arn $INSTANCE_ARN \
--stat $STATISTIC \
--period $PERIOD_IN_SECONDS \
--start-time \"$START_TIME\" \
--end-time \"$END_TIME\""
done
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment