Skip to content

Commit

Permalink
fix: discover public address via imdsv2 (#5456)
Browse files Browse the repository at this point in the history
  • Loading branch information
emosbaugh authored Nov 5, 2024
1 parent 81937f6 commit fa9b40e
Showing 1 changed file with 39 additions and 8 deletions.
47 changes: 39 additions & 8 deletions scripts/common/discover.sh
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ function get_docker_version() {
docker -v | awk '{gsub(/,/, "", $3); print $3}'
}

discover_public_ip() {
function discover_public_ip() {
if [ "$AIRGAP" == "1" ]; then
return
fi
Expand All @@ -202,8 +202,18 @@ discover_public_ip() {
fi

# ec2
PUBLIC_ADDRESS=$(discover_public_ip_ec2_imdsv2)
if [ -n "$PUBLIC_ADDRESS" ]; then
return
fi
PUBLIC_ADDRESS=$(discover_public_ip_ec2_imdsv1)
if [ -n "$PUBLIC_ADDRESS" ]; then
return
fi

# azure
set +e
_out=$(curl --noproxy "*" --max-time 5 --connect-timeout 2 -qSfs http://169.254.169.254/latest/meta-data/public-ipv4 2>/dev/null)
_out=$(curl --noproxy "*" --max-time 5 --connect-timeout 2 -qSfs -H Metadata:true "http://169.254.169.254/metadata/instance/network/interface/0/ipv4/ipAddress/0/publicIpAddress?api-version=2017-08-01&format=text" 2>/dev/null)
_status=$?
set -e
if [ "$_status" -eq "0" ] && [ -n "$_out" ]; then
Expand All @@ -212,18 +222,39 @@ discover_public_ip() {
fi
return
fi
}

function discover_public_ip_ec2_imdsv1() {
local public_address status

# azure
set +e
_out=$(curl --noproxy "*" --max-time 5 --connect-timeout 2 -qSfs -H Metadata:true "http://169.254.169.254/metadata/instance/network/interface/0/ipv4/ipAddress/0/publicIpAddress?api-version=2017-08-01&format=text" 2>/dev/null)
_status=$?
public_address=$(curl --noproxy "*" --max-time 5 --connect-timeout 2 -qSfs http://169.254.169.254/latest/meta-data/public-ipv4 2>/dev/null)
status=$?
set -e
if [ "$_status" -eq "0" ] && [ -n "$_out" ]; then
if isValidIpv4 "$_out" || isValidIpv6 "$_out"; then
PUBLIC_ADDRESS=$_out
if [ "$status" -eq 0 ] && [ -n "$public_address" ]; then
if isValidIpv4 "$public_address" || isValidIpv6 "$public_address"; then
echo "$public_address"
fi
fi
}

function discover_public_ip_ec2_imdsv2() {
local token public_address status

token=$(curl --noproxy "*" --max-time 5 --connect-timeout 2 -qSfs -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" 2>/dev/null)
if [ -z "$token" ]; then
return
fi

set +e
public_address=$(curl --noproxy "*" --max-time 5 --connect-timeout 2 -qSfs -H "X-aws-ec2-metadata-token: $token" http://169.254.169.254/latest/meta-data/public-ipv4 2>/dev/null)
status=$?
set -e
if [ "$status" -eq 0 ] && [ -n "$public_address" ]; then
if isValidIpv4 "$public_address" || isValidIpv6 "$public_address"; then
echo "$public_address"
fi
fi
}

function discover_private_ip() {
Expand Down

0 comments on commit fa9b40e

Please sign in to comment.