@@ -6,7 +6,6 @@ package imds
6
6
import (
7
7
"context"
8
8
"encoding/json"
9
- "fmt"
10
9
"net/http"
11
10
"net/url"
12
11
@@ -28,17 +27,17 @@ type clientConfig struct {
28
27
retryAttempts uint
29
28
}
30
29
31
- type clientOption func (* clientConfig )
30
+ type ClientOption func (* clientConfig )
32
31
33
32
// Endpoint overrides the default endpoint for a Client
34
- func Endpoint (url string ) clientOption {
33
+ func Endpoint (endpoint string ) ClientOption {
35
34
return func (c * clientConfig ) {
36
- c .endpoint = url
35
+ c .endpoint = endpoint
37
36
}
38
37
}
39
38
40
39
// RetryAttempts overrides the default retry attempts for the client
41
- func RetryAttempts (attempts uint ) clientOption {
40
+ func RetryAttempts (attempts uint ) ClientOption {
42
41
return func (c * clientConfig ) {
43
42
c .retryAttempts = attempts
44
43
}
@@ -53,10 +52,13 @@ const (
53
52
defaultIMDSEndpoint = "http://169.254.169.254"
54
53
)
55
54
56
- var ErrVMUniqueIDNotFound = errors .New ("vm unique ID not found" )
55
+ var (
56
+ ErrVMUniqueIDNotFound = errors .New ("vm unique ID not found" )
57
+ ErrUnexpectedStatusCode = errors .New ("imds returned an unexpected status code" )
58
+ )
57
59
58
60
// NewClient creates a new imds client
59
- func NewClient (opts ... clientOption ) * Client {
61
+ func NewClient (opts ... ClientOption ) * Client {
60
62
config := clientConfig {
61
63
endpoint : defaultIMDSEndpoint ,
62
64
}
@@ -98,12 +100,12 @@ func (c *Client) GetVMUniqueID(ctx context.Context) (string, error) {
98
100
}
99
101
100
102
func (c * Client ) getInstanceComputeMetadata (ctx context.Context ) (map [string ]any , error ) {
101
- url , err := url .JoinPath (c .config .endpoint , imdsComputePath )
103
+ imdsComputeURL , err := url .JoinPath (c .config .endpoint , imdsComputePath )
102
104
if err != nil {
103
105
return nil , errors .Wrap (err , "unable to build path to IMDS compute metadata" )
104
106
}
105
107
106
- req , err := http .NewRequestWithContext (ctx , http .MethodGet , url , nil )
108
+ req , err := http .NewRequestWithContext (ctx , http .MethodGet , imdsComputeURL , http . NoBody )
107
109
if err != nil {
108
110
return nil , errors .Wrap (err , "error building IMDS http request" )
109
111
}
@@ -115,9 +117,10 @@ func (c *Client) getInstanceComputeMetadata(ctx context.Context) (map[string]any
115
117
if err != nil {
116
118
return nil , errors .Wrap (err , "error querying IMDS" )
117
119
}
120
+ defer resp .Body .Close ()
118
121
119
122
if resp .StatusCode != http .StatusOK {
120
- return nil , fmt . Errorf ( "received unexpected status code %d from IMDS " , resp .StatusCode )
123
+ return nil , errors . Wrapf ( ErrUnexpectedStatusCode , " unexpected status code %d" , resp .StatusCode )
121
124
}
122
125
123
126
var m map [string ]any
0 commit comments