From e79920f725cc3334f0934f43c41ebc0a9718ced9 Mon Sep 17 00:00:00 2001 From: Marcelo Bartsch Date: Thu, 11 Mar 2021 16:54:27 +0100 Subject: [PATCH] update doHealthcheck to support IMDSv2 --- server/server.go | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/server/server.go b/server/server.go index 15578f90..018de0b3 100644 --- a/server/server.go +++ b/server/server.go @@ -241,12 +241,31 @@ func (s *Server) doHealthcheck() { metrics.HealthcheckStatus.Set(healthcheckResult) }() - resp, err := http.Get(fmt.Sprintf("http://%s/latest/meta-data/instance-id", s.MetadataAddress)) + tokenReq, _ := http.NewRequest("PUT", + fmt.Sprintf("http://%s/latest/api/token", s.MetadataAddress), + nil) + tokenReq.Header.Add("X-aws-ec2-metadata-token-ttl-seconds", "60") + tokenResp, err := http.DefaultClient.Do(tokenReq) + + token, err := ioutil.ReadAll(tokenResp.Body) + + if err != nil { + errMsg = fmt.Sprintf("Error getting token %+v", err) + log.Errorf(errMsg) + return + } + + req, _ := http.NewRequest("GET", + fmt.Sprintf("http://%s/latest/meta-data/instance-id", s.MetadataAddress), nil) + req.Header.Add("X-aws-ec2-metadata-token", fmt.Sprintf("%s", token)) + resp, err := http.DefaultClient.Do(req) + if err != nil { errMsg = fmt.Sprintf("Error getting instance id %+v", err) log.Errorf(errMsg) return } + if resp.StatusCode != 200 { errMsg = fmt.Sprintf("Error getting instance id, got status: %+s", resp.Status) log.Error(errMsg)