From 5d83094d061448e9922700238da83f575fb05c7c Mon Sep 17 00:00:00 2001 From: Charlton Stanley Date: Tue, 15 Apr 2025 16:16:11 -0500 Subject: [PATCH] systemd: build: fix service startup failure when using IMDSv2 PR #9845 added a service dependency "sethostname.service" for Amazon Linux 2, which uses Amazon's Instance Metadata Service (IMDS) to query and set the hostname. This works for instances using the legacy IMDSv1, however it fails when admins have enforced the usage of IMDSv2. This patch is a modification of @cpandya-we comment/work on #10186. Fixes #10186 Signed-off-by: Charlton Stanley --- init/az2-sethostname.in | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/init/az2-sethostname.in b/init/az2-sethostname.in index dcce08bf2d9..14635a4dcb1 100644 --- a/init/az2-sethostname.in +++ b/init/az2-sethostname.in @@ -1,12 +1,21 @@ [Unit] -Description=Set Hostname Workaround coreos/bugs#1272 +Description=Set Hostname Workaround coreos/bugs#1272 with EC2 IMDSv2 support Wants=network-online.target After=network-online.target [Service] Type=oneshot RemainAfterExit=yes -ExecStart=/bin/sh -c "/usr/bin/hostnamectl set-hostname $(curl -s http://169.254.169.254/latest/meta-data/hostname)" + +ExecStartPre=/bin/sh -c 'curl -sX PUT "http://169.254.169.254/latest/api/token" \ + -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" > /run/imds_token' + +ExecStartPre=/bin/sh -c 'curl -s "http://169.254.169.254/latest/meta-data/hostname" \ + -H "X-aws-ec2-metadata-token: $(cat /run/imds_token)" > /run/ec2_hostname' + +ExecStart=/bin/sh -c '/usr/bin/hostnamectl set-hostname "$(cat /run/ec2_hostname)"' + +ExecStartPost=/bin/sh -c 'rm -f /run/imds_token /run/ec2_hostname' [Install] -WantedBy=multi-user.target \ No newline at end of file +WantedBy=multi-user.target