1{ curl, targetRoot, wgetExtraOptions }:
2# Note: be very cautious about dependencies, each dependency grows
3# the closure of the initrd. Ideally we would not even require curl,
4# but there is no reasonable way to send an HTTP PUT request without
5# it. Note: do not be fooled: the wget referenced in this script
6# is busybox's wget, not the fully featured one with --method support.
7#
8# Make sure that every package you depend on here is already listed as
9# a channel blocker for both the full-sized and small channels.
10# Otherwise, we risk breaking user deploys in released channels.
11#
12# Also note: OpenStack's metadata service for its instances aims to be
13# compatible with the EC2 IMDS. Where possible, try to keep the set of
14# fetched metadata in sync with ./openstack-metadata-fetcher.nix .
15''
16 metaDir=${targetRoot}etc/ec2-metadata
17 mkdir -m 0755 -p "$metaDir"
18 rm -f "$metaDir/*"
19
20 get_imds_token() {
21 # retry-delay of 1 selected to give the system a second to get going,
22 # but not add a lot to the bootup time
23 ${curl}/bin/curl \
24 -v \
25 --retry 3 \
26 --retry-delay 1 \
27 --fail \
28 -X PUT \
29 --connect-timeout 1 \
30 -H "X-aws-ec2-metadata-token-ttl-seconds: 600" \
31 http://169.254.169.254/latest/api/token
32 }
33
34 preflight_imds_token() {
35 # retry-delay of 1 selected to give the system a second to get going,
36 # but not add a lot to the bootup time
37 ${curl}/bin/curl \
38 -v \
39 --retry 3 \
40 --retry-delay 1 \
41 --fail \
42 --connect-timeout 1 \
43 -H "X-aws-ec2-metadata-token: $IMDS_TOKEN" \
44 http://169.254.169.254/1.0/meta-data/instance-id
45 }
46
47 try=1
48 while [ $try -le 3 ]; do
49 echo "(attempt $try/3) getting an EC2 instance metadata service v2 token..."
50 IMDS_TOKEN=$(get_imds_token) && break
51 try=$((try + 1))
52 sleep 1
53 done
54
55 if [ "x$IMDS_TOKEN" == "x" ]; then
56 echo "failed to fetch an IMDS2v token."
57 fi
58
59 try=1
60 while [ $try -le 10 ]; do
61 echo "(attempt $try/10) validating the EC2 instance metadata service v2 token..."
62 preflight_imds_token && break
63 try=$((try + 1))
64 sleep 1
65 done
66
67 echo "getting EC2 instance metadata..."
68
69 wget_imds() {
70 wget ${wgetExtraOptions} --header "X-aws-ec2-metadata-token: $IMDS_TOKEN" "$@";
71 }
72
73 wget_imds -O "$metaDir/ami-manifest-path" http://169.254.169.254/1.0/meta-data/ami-manifest-path
74 (umask 077 && wget_imds -O "$metaDir/user-data" http://169.254.169.254/1.0/user-data)
75 wget_imds -O "$metaDir/hostname" http://169.254.169.254/1.0/meta-data/hostname
76 wget_imds -O "$metaDir/public-keys-0-openssh-key" http://169.254.169.254/1.0/meta-data/public-keys/0/openssh-key
77''