Skip to content

Instantly share code, notes, and snippets.

@cpswan
Created August 4, 2015 19:38
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cpswan/59ece85a1f7c231d5cb2 to your computer and use it in GitHub Desktop.
Save cpswan/59ece85a1f7c231d5cb2 to your computer and use it in GitHub Desktop.
Extract VPC DNS IP from AWS instance metadata
#!/bin/bash
MAC="$(curl -s http://169.254.169.254/latest/meta-data/network/interfaces/macs/)"
VPCCIDR="$(curl -s http://169.254.169.254/latest/meta-data/network/interfaces/macs/"$MAC"/vpc-ipv4-cidr-block)"
VPCNET="${VPCCIDR%%/*}"
VPCBASE="$(echo "$VPCNET" | cut -d"." -f1-3)"
VPCDNS="$VPCBASE"'.2'
echo "$VPCDNS"
@cpswan
Copy link
Author

cpswan commented Aug 4, 2015

Or just:

grep -m 1 nameserver /etc/resolv.conf | sed s/'nameserver '//

@mrPsycho
Copy link

or only awk:
awk 'BEGIN{ORS=" "} $1=="nameserver" {print $2; exit}' /etc/resolv.conf

@coofercat
Copy link

Just to say, the /etc/resolv.conf trick doesn't work on systems with systemd-resolver (eg. Ubuntu 18), or on systems such as a Mac (Mojave or later).

On Ubuntu, you may be able to do something like: systemd-resolve --status | awk '/DNS Servers:/ { print $3 }'

I haven't tried, but on other systems, resolvectl status may also give similar information that you may be able to use.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment