Created
September 5, 2024 22:49
-
-
Save duttonw/44c9d2d9c832b97bd3d151710e2fb3c7 to your computer and use it in GitHub Desktop.
Ability to set instances IMDS secret key access on servers which have software not ready for V2 security. (Tagged- Environment: PROD)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Default settings | |
IMDSV2_SETTING="required" # Change to "optional" if you want to revert back | |
DRYRUN=false | |
# Parse arguments | |
while [[ "$#" -gt 0 ]]; do | |
case $1 in | |
--setting) IMDSV2_SETTING="$2"; shift ;; | |
--dryrun) DRYRUN=true ;; | |
*) echo "Unknown parameter passed: $1"; exit 1 ;; | |
esac | |
shift | |
done | |
# Fetch the IMDSv2 token | |
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600") | |
if [ -z "$TOKEN" ]; then | |
echo "Failed to fetch IMDSv2 token." | |
exit 1 | |
fi | |
# Get the current region using the token | |
REGION=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -s http://169.254.169.254/latest/dynamic/instance-identity/document | jq -r '.region') | |
if [ -z "$REGION" ]; then | |
echo "Could not determine the AWS region." | |
exit 1 | |
fi | |
# Function to update IMDSv2 setting for a given instance | |
update_instance_metadata() { | |
local instance_id=$1 | |
local setting=$2 | |
local dryrun_flag="" | |
if [ "$DRYRUN" = true ]; then | |
dryrun_flag="--dry-run" | |
echo "Dry run: Would update IMDSv2 setting to '$setting' for instance $instance_id" | |
else | |
aws ec2 modify-instance-metadata-options \ | |
--instance-id "$instance_id" \ | |
--http-tokens "$setting" \ | |
--http-endpoint enabled \ | |
--region "$REGION" \ | |
$dryrun_flag | |
if [ $? -eq 0 ]; then | |
echo "Successfully updated IMDSv2 setting to '$setting' for instance $instance_id" | |
else | |
echo "Failed to update IMDSv2 setting for instance $instance_id" | |
fi | |
fi | |
} | |
# Fetch all EC2 instances with the tag Environment: PROD | |
instance_ids=$(aws ec2 describe-instances \ | |
--filters "Name=tag:Environment,Values=PROD" \ | |
--query "Reservations[*].Instances[*].InstanceId" \ | |
--output text \ | |
--region "$REGION") | |
if [ -z "$instance_ids" ]; then | |
echo "No instances found with the tag Environment: PROD" | |
exit 1 | |
fi | |
# Loop through each instance ID and update the IMDSv2 setting | |
for instance_id in $instance_ids; do | |
update_instance_metadata "$instance_id" "$IMDSV2_SETTING" | |
done | |
echo "IMDSv2 setting update process completed." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment