Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions cns/imds/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,14 @@ func RetryAttempts(attempts uint) ClientOption {
}

const (
vmUniqueIDProperty = "vmId"
imdsComputePath = "/metadata/instance/compute?api-version=2021-01-01&format=json"
metadataHeaderKey = "Metadata"
metadataHeaderValue = "true"
defaultRetryAttempts = 10
defaultIMDSEndpoint = "http://169.254.169.254"
vmUniqueIDProperty = "vmId"
imdsComputePath = "/metadata/instance/compute"
imdsComputeAPIVersion = "api-version=2021-01-01"
imdsFormatJSON = "format=json"
metadataHeaderKey = "Metadata"
metadataHeaderValue = "true"
defaultRetryAttempts = 3
defaultIMDSEndpoint = "http://169.254.169.254"
)

var (
Expand All @@ -60,7 +62,8 @@ var (
// NewClient creates a new imds client
func NewClient(opts ...ClientOption) *Client {
config := clientConfig{
endpoint: defaultIMDSEndpoint,
endpoint: defaultIMDSEndpoint,
retryAttempts: defaultRetryAttempts,
}

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

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

// IMDS requires the "Metadata: true" header
req.Header.Add(metadataHeaderKey, metadataHeaderValue)

resp, err := c.cli.Do(req)
if err != nil {
return nil, errors.Wrap(err, "error querying IMDS")
Expand Down
6 changes: 6 additions & 0 deletions cns/imds/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ func TestGetVMUniqueID(t *testing.T) {
// request header "Metadata: true" must be present
metadataHeader := r.Header.Get("Metadata")
assert.Equal(t, "true", metadataHeader)

// query params should include apiversion and json format
apiVersion := r.URL.Query().Get("api-version")
assert.Equal(t, "2021-01-01", apiVersion)
format := r.URL.Query().Get("format")
assert.Equal(t, "json", format)
w.WriteHeader(http.StatusOK)
_, writeErr := w.Write(computeMetadata)
require.NoError(t, writeErr, "error writing response")
Expand Down