vuls: init at 0.27.0
[NixPkgs.git] / nixos / modules / virtualisation / ec2-metadata-fetcher.sh
blob66a05e7a436ffe2e579bde7b0a4ce475712814e6
1 metaDir=/etc/ec2-metadata
2 mkdir -p "$metaDir"
3 chmod 0755 "$metaDir"
4 rm -f "$metaDir/*"
6 get_imds_token() {
7 # retry-delay of 1 selected to give the system a second to get going,
8 # but not add a lot to the bootup time
9 curl \
10 --silent \
11 --show-error \
12 --retry 3 \
13 --retry-delay 1 \
14 --fail \
15 -X PUT \
16 --connect-timeout 1 \
17 -H "X-aws-ec2-metadata-token-ttl-seconds: 600" \
18 http://169.254.169.254/latest/api/token
21 preflight_imds_token() {
22 # retry-delay of 1 selected to give the system a second to get going,
23 # but not add a lot to the bootup time
24 curl \
25 --silent \
26 --show-error \
27 --retry 3 \
28 --retry-delay 1 \
29 --fail \
30 --connect-timeout 1 \
31 -H "X-aws-ec2-metadata-token: $IMDS_TOKEN" \
32 -o /dev/null \
33 http://169.254.169.254/1.0/meta-data/instance-id
36 try=1
37 while [ $try -le 3 ]; do
38 echo "(attempt $try/3) getting an EC2 instance metadata service v2 token..."
39 IMDS_TOKEN=$(get_imds_token) && break
40 try=$((try + 1))
41 sleep 1
42 done
44 if [ "$IMDS_TOKEN" == "" ]; then
45 echo "failed to fetch an IMDS2v token."
48 try=1
49 while [ $try -le 10 ]; do
50 echo "(attempt $try/10) validating the EC2 instance metadata service v2 token..."
51 preflight_imds_token && break
52 try=$((try + 1))
53 sleep 1
54 done
56 echo "getting EC2 instance metadata..."
58 get_imds() {
59 # --fail to avoid populating missing files with 404 HTML response body
60 # || true to allow the script to continue even when encountering a 404
61 curl --silent --show-error --fail --header "X-aws-ec2-metadata-token: $IMDS_TOKEN" "$@" || true
64 get_imds -o "$metaDir/ami-manifest-path" http://169.254.169.254/1.0/meta-data/ami-manifest-path
65 (umask 077 && get_imds -o "$metaDir/user-data" http://169.254.169.254/1.0/user-data)
66 get_imds -o "$metaDir/hostname" http://169.254.169.254/1.0/meta-data/hostname
67 get_imds -o "$metaDir/public-keys-0-openssh-key" http://169.254.169.254/1.0/meta-data/public-keys/0/openssh-key