From 9a40f1636ac1d2edc7f91b62342bcd14dbd7c84c Mon Sep 17 00:00:00 2001 From: Rajesh Karunakaran <84339500+rajeshfinix@users.noreply.github.com> Date: Sat, 17 Sep 2022 10:47:23 -0700 Subject: [PATCH] Use IMDSv2 to get instance metadata -ELB Issue #, if available: This is similar to other PR on elbv2 https://github.com/aws-samples/aws-codedeploy-samples/pull/102 Current version of script breaks when IMDSv2 is enforced on EC2 instances( "InstanceMetadataOptions": { "HttpTokens": "required", } ) Description of changes: To improve security, AWS recommend to use IMDSv2, the session-oriented communication to get instance metadata.https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html. This change is backward compatible with IMDSv1. Also updated the request to get the region using placement/region this feature was released by AWS on 2020-08-24 - https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-categories.html --- load-balancing/elb/common_functions.sh | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/load-balancing/elb/common_functions.sh b/load-balancing/elb/common_functions.sh index 2c65b4d..108a13c 100644 --- a/load-balancing/elb/common_functions.sh +++ b/load-balancing/elb/common_functions.sh @@ -97,9 +97,8 @@ exec_with_fulljitter_retry() { # Writes to STDOUT the AWS region as known by the local instance. get_instance_region() { if [ -z "$AWS_REGION" ]; then - AWS_REGION=$(curl -s http://169.254.169.254/latest/dynamic/instance-identity/document \ - | grep -i region \ - | awk -F\" '{print $4}') + TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600") + AWS_REGION=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -s http://169.254.169.254/latest/meta-data/placement/region) fi echo $AWS_REGION @@ -706,6 +705,7 @@ error_exit() { # Writes to STDOUT the EC2 instance ID for the local instance. Returns non-zero if the local # instance metadata URL is inaccessible. get_instance_id() { - curl -s http://169.254.169.254/latest/meta-data/instance-id + TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600") + curl -H "X-aws-ec2-metadata-token: $TOKEN" -s http://169.254.169.254/latest/meta-data/instance-id return $? }