Skip to content

Commit f97eb96

Browse files
authored
fix: build imds compute url correctly and give a default retryAttempts (#2566)
* fix: build imds compute url correctly * fix: remove httputil debug stuff
1 parent 1d36cfc commit f97eb96

File tree

2 files changed

+17
-8
lines changed

2 files changed

+17
-8
lines changed

cns/imds/client.go

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,12 +44,14 @@ func RetryAttempts(attempts uint) ClientOption {
4444
}
4545

4646
const (
47-
vmUniqueIDProperty = "vmId"
48-
imdsComputePath = "/metadata/instance/compute?api-version=2021-01-01&format=json"
49-
metadataHeaderKey = "Metadata"
50-
metadataHeaderValue = "true"
51-
defaultRetryAttempts = 10
52-
defaultIMDSEndpoint = "http://169.254.169.254"
47+
vmUniqueIDProperty = "vmId"
48+
imdsComputePath = "/metadata/instance/compute"
49+
imdsComputeAPIVersion = "api-version=2021-01-01"
50+
imdsFormatJSON = "format=json"
51+
metadataHeaderKey = "Metadata"
52+
metadataHeaderValue = "true"
53+
defaultRetryAttempts = 3
54+
defaultIMDSEndpoint = "http://169.254.169.254"
5355
)
5456

5557
var (
@@ -60,7 +62,8 @@ var (
6062
// NewClient creates a new imds client
6163
func NewClient(opts ...ClientOption) *Client {
6264
config := clientConfig{
63-
endpoint: defaultIMDSEndpoint,
65+
endpoint: defaultIMDSEndpoint,
66+
retryAttempts: defaultRetryAttempts,
6467
}
6568

6669
for _, o := range opts {
@@ -104,6 +107,7 @@ func (c *Client) getInstanceComputeMetadata(ctx context.Context) (map[string]any
104107
if err != nil {
105108
return nil, errors.Wrap(err, "unable to build path to IMDS compute metadata")
106109
}
110+
imdsComputeURL = imdsComputeURL + "?" + imdsComputeAPIVersion + "&" + imdsFormatJSON
107111

108112
req, err := http.NewRequestWithContext(ctx, http.MethodGet, imdsComputeURL, http.NoBody)
109113
if err != nil {
@@ -112,7 +116,6 @@ func (c *Client) getInstanceComputeMetadata(ctx context.Context) (map[string]any
112116

113117
// IMDS requires the "Metadata: true" header
114118
req.Header.Add(metadataHeaderKey, metadataHeaderValue)
115-
116119
resp, err := c.cli.Do(req)
117120
if err != nil {
118121
return nil, errors.Wrap(err, "error querying IMDS")

cns/imds/client_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,12 @@ func TestGetVMUniqueID(t *testing.T) {
2323
// request header "Metadata: true" must be present
2424
metadataHeader := r.Header.Get("Metadata")
2525
assert.Equal(t, "true", metadataHeader)
26+
27+
// query params should include apiversion and json format
28+
apiVersion := r.URL.Query().Get("api-version")
29+
assert.Equal(t, "2021-01-01", apiVersion)
30+
format := r.URL.Query().Get("format")
31+
assert.Equal(t, "json", format)
2632
w.WriteHeader(http.StatusOK)
2733
_, writeErr := w.Write(computeMetadata)
2834
require.NoError(t, writeErr, "error writing response")

0 commit comments

Comments
 (0)