#!/bin/bash set -u # This is the cheater's trick to get the AWS EC2 Instance ID. EC2_InstanceID=$(readlink /var/lib/cloud/instance) EC2_InstanceID=${EC2_InstanceID##*/} [[ -n "$EC2_InstanceID" ]] && echo "$EC2_InstanceID" # For reference, this is a more "official" way to get an AWS EC2 Instance ID. ### TOKEN=$(curl -sS -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600") 2>/dev/null ### EC2_InstanceID=$(curl -sS -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/instance-id) ### echo "$EC2_InstanceID" # Tip: The /var/lib/cloud/instances directory does not get cleaned up during AMI # create/restore process. It can contain multiple obsolete instance IDs.