AMI Age Calculator of Running AWS EC2 Instances and Generate CSV Report

#!/bin/bash

# Initialize variables with default values
ACCOUNTID="<Your AccountID>"
REGION="<Your Region>"
 
OUTPUT_CSV="$ACCOUNTID-$REGION-ami_age_report.csv"  # Define the CSV file name
rm -rf $OUTPUT_CSV

# Parse command line options
while getopts "a:b:" option; do
  case $option in
    a) ACCOUNTID=${OPTARG} ;;
    b) REGION=${OPTARG} ;;
    *) echo "usage: $0 [-a ACCOUNTID] [-b REGION]" >&2
       exit 1 ;;
  esac
done

# List instances and AMI IDs in the specified region
instances_json=$(aws ec2 describe-instances --region "$REGION" --query 'Reservations[*].Instances[*].[InstanceId,ImageId]' --output json) # For local


# Get the current timestamp
current_time=$(date -u +%s)

# Initialize the CSV file with headers
echo "AccountID,Region,InstanceID,AMIID,AMIAge (months)" > "$OUTPUT_CSV"

# Iterate through instances and append to the CSV file
for row in $(echo "$instances_json" | jq -r '.[][] | @base64'); do
  _jq() {
    echo "$row" | base64 --decode | jq -r "$1"
  }

  instance_id=$(_jq '.[0]')
  ami_id=$(_jq '.[1]')

  # Get the creation date of the AMI in the specified region
  ami_create_time=$(aws ec2 describe-images --region "$REGION" --image-ids "$ami_id" --query 'Images[0].CreationDate' --output text) # For local
  

  # Calculate the age in months based on the AMI creation time
  ami_create_timestamp=$(date -u -d "$ami_create_time" +%s)
  months_diff=$(( (current_time - ami_create_timestamp) / 60 / 60 / 24 / 30 ))

  # Check if the AMI is older than 4 months
  if [ "$months_diff" -ge 4 ]; then
    # Append to the CSV file
    echo "$ACCOUNTID,$REGION,$instance_id,$ami_id,$months_diff" >> "$OUTPUT_CSV"
  fi
done

echo "CSV report saved to $OUTPUT_CSV"
cat $OUTPUT_CSV

Comments

Popular posts from this blog

AWS CLI Get Security Group ID with Name.[ wild card support] Bash Script

AWS CLI Get Security Group ID with Name. Python Boto3 [ wild card support] Python Boto3