Skip to content

Commit 9a40f16

Browse files
Use IMDSv2 to get instance metadata -ELB
Issue #, if available: This is similar to other PR on elbv2 aws-samples#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
1 parent 7b2c0d6 commit 9a40f16

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

load-balancing/elb/common_functions.sh

+4-4
Original file line numberDiff line numberDiff line change
@@ -97,9 +97,8 @@ exec_with_fulljitter_retry() {
9797
# Writes to STDOUT the AWS region as known by the local instance.
9898
get_instance_region() {
9999
if [ -z "$AWS_REGION" ]; then
100-
AWS_REGION=$(curl -s http://169.254.169.254/latest/dynamic/instance-identity/document \
101-
| grep -i region \
102-
| awk -F\" '{print $4}')
100+
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
101+
AWS_REGION=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -s http://169.254.169.254/latest/meta-data/placement/region)
103102
fi
104103

105104
echo $AWS_REGION
@@ -706,6 +705,7 @@ error_exit() {
706705
# Writes to STDOUT the EC2 instance ID for the local instance. Returns non-zero if the local
707706
# instance metadata URL is inaccessible.
708707
get_instance_id() {
709-
curl -s http://169.254.169.254/latest/meta-data/instance-id
708+
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
709+
curl -H "X-aws-ec2-metadata-token: $TOKEN" -s http://169.254.169.254/latest/meta-data/instance-id
710710
return $?
711711
}

0 commit comments

Comments
 (0)