IMDSv2 Mastery: Simplifying AWS EC2 Metadata Retrieval with Bash

IMDSv2 Mastery: Simplifying AWS EC2 Metadata Retrieval with Bash

Secure Metadata Retrieval: A Step-by-Step Guide

Table of contents

No heading

No headings in the article.

#!/bin/bash
#
# Script Name: retrieve_instance_metadata.sh
# Description: This Bash script retrieves metadata from an AWS EC2 instance using the EC2 instance metadata service.
#
# Usage:
#   - Ensure that the script has execute permissions: chmod +x retrieve_instance_metadata.sh
#   - Run the script: ./retrieve_instance_metadata.sh
#
# Author: Praveen HA
# Date: January 1, 2023
# Version: 1.0
#
# Dependencies:
#   - Requires curl to be installed. Install it using your package manager (e.g., sudo apt-get install curl).
#
# Notes:
#   - The script uses the Instance Metadata Service (IMDSv1) to obtain information about the EC2 instance.
#   - It retrieves specific metadata attributes such as instance ID, AWS region, AMI ID, and local IPv4 address.
#   - Errors are logged to /path/to/your/error/log/file.log.
#
# Helper Functions:
#   - log_error(): Logs errors with a timestamp to the specified log file.
#   - get_metadata(): Retrieves metadata from the specified value using the IMDSv1 token-based approach.
#
# Example Usage:
#   - INSTANCE_ID=$(get_metadata "instance-id")
#   - AWS_REGION=$(get_metadata "placement/availability-zone" | sed 's/.$//')
#   - AMI_ID=$(get_metadata "ami-id")
#   - IP=$(get_metadata "local-ipv4")
# Function to log errors
log_error() {
    local timestamp=$(date +"[%Y-%m-%d %H:%M:%S]")
    echo "$timestamp [ERROR]: $1" >> /path/to/your/error/log/file.log
}

# Function to retrieve metadata dynamically
get_metadata() {
    local value="$1"
    metadata=$(curl -sSfX PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" | xargs -I{} curl --silent -sSfH "X-aws-ec2-metadata-token: {}" "http://169.254.169.254/latest/meta-data/$value/")
    # Check if metadata retrieval was successful
    if [ $? -ne 0 ]; then
        log_error "Failed to retrieve metadata for $value."
        exit 1
    fi
    echo "$metadata"
}
# Example: Get instance ID
INSTANCE_ID=$(get_metadata "instance-id")
echo "Instance ID: $INSTANCE_ID"
# Example: Get AWS region
AWS_REGION=$(get_metadata "placement/availability-zone" | sed 's/.$//')
echo "AWS Region: $AWS_REGION"
AMI_ID=$(get_metadata "ami-id")
IP=$(get_metadata "local-ipv4")
echo "AMI_ID : $AMI_ID"
echo "IP : $IP"