@@ -20,6 +20,31 @@ SKIP_CREDENTIALS=${SKIP_CREDENTIALS:-""}
2020USE_CURRENT_USER=${USE_CURRENT_USER:- " " }
2121AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID:- " " } # We check the access key
2222
23+ # If no credentials are configured, attempt to retrieve them from EC2 IMDSv2
24+ if [ -z " $AWS_ACCESS_KEY_ID " ] && [ -z " $SKIP_CREDENTIALS " ]; then
25+ IMDS_TOKEN=$( curl -s --connect-timeout 2 -X PUT " http://169.254.169.254/latest/api/token" \
26+ -H " X-aws-ec2-metadata-token-ttl-seconds: 21600" 2> /dev/null) || true
27+
28+ if [ -n " $IMDS_TOKEN " ]; then
29+ IMDS_ROLE=$( curl -s --connect-timeout 2 \
30+ -H " X-aws-ec2-metadata-token: $IMDS_TOKEN " \
31+ " http://169.254.169.254/latest/meta-data/iam/security-credentials/" 2> /dev/null) || true
32+
33+ if [ -n " $IMDS_ROLE " ]; then
34+ IMDS_CREDS=$( curl -s --connect-timeout 2 \
35+ -H " X-aws-ec2-metadata-token: $IMDS_TOKEN " \
36+ " http://169.254.169.254/latest/meta-data/iam/security-credentials/${IMDS_ROLE} " 2> /dev/null) || true
37+
38+ if [ -n " $IMDS_CREDS " ]; then
39+ export AWS_ACCESS_KEY_ID=$( echo " $IMDS_CREDS " | grep -o ' "AccessKeyId" *: *"[^"]*"' | cut -d' "' -f4)
40+ export AWS_SECRET_ACCESS_KEY=$( echo " $IMDS_CREDS " | grep -o ' "SecretAccessKey" *: *"[^"]*"' | cut -d' "' -f4)
41+ export AWS_SESSION_TOKEN=$( echo " $IMDS_CREDS " | grep -o ' "Token" *: *"[^"]*"' | cut -d' "' -f4)
42+ echo " Retrieved credentials from EC2 IMDSv2 (role: ${IMDS_ROLE} )"
43+ fi
44+ fi
45+ fi
46+ fi
47+
2348if [ -z " $SKIP_CREDENTIALS " ]; then
2449 ACCOUNT_ID=$( aws sts get-caller-identity --query Account --output text)
2550
0 commit comments