AMI Age Calculator of Running AWS EC2 Instances and Generate CSV Report
Tags: aws, amazon, devops, bash
Published: 2023-10-01 10:32:51

Instances running on outdated AMIs pose a security risk. Keeping our infrastructure secure requires us to regularly update these instances with the latest AMIs. Manually identifying and updating instances can be a time-consuming process, especially in large AWS accounts.
 
How does the automation work?
 
Our automation script leverages AWS CLI and the power of scripting to identify instances using older AMIs automatically. 
Account and Region Selection: We can specify the AWS account ID and region you want to scan when executing the Jenkins Job.
 
AMI Age Assessment: The script checks every instance in the selected account and region and determines the age of the associated AMI based on its creation date.
 
Automated Reporting: It generates a CSV report with details of instances using AMIs that are 4 months or older. This report includes the Account ID, Region, Instance ID, AMI ID, and AMI Age (Months).
 
Actionable Insights: With this report, we can easily identify which instances require updates. This information can be used to patch instances with the latest AMIs, ensuring they remain secure and optimized.
 
How can we use it?
 
Running this automation is simple. we can execute the script filling the AWS account ID and region as parameters. script will do the rest providing us with a detailed report.
 
What are the benefits?
 
Enhanced Security: We can proactively identify and patch instances with older AMIs, reducing security vulnerabilities.
 
Efficiency: Manual instance assessment is time-consuming, but this automation speeds up the process, allowing us to focus on other critical tasks.
 
Consistency: By automating this process, we ensure that all instances are assessed uniformly and regularly.


`#!/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`