From 89d65439ff9cd43d44deb9e60ef9a784981931af Mon Sep 17 00:00:00 2001 From: Rajesh Karunakaran <84339500+rajeshfinix@users.noreply.github.com> Date: Sat, 17 Sep 2022 10:34:40 -0700 Subject: [PATCH] Use IMDSv2 to get instance metadata 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-v2/common_functions.sh | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/load-balancing/elb-v2/common_functions.sh b/load-balancing/elb-v2/common_functions.sh index f5fc226..fc9f9e8 100644 --- a/load-balancing/elb-v2/common_functions.sh +++ b/load-balancing/elb-v2/common_functions.sh @@ -107,9 +107,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 @@ -728,6 +727,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 $? }