-
Notifications
You must be signed in to change notification settings - Fork 458
/
metadata.go
99 lines (77 loc) · 2.41 KB
/
metadata.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package aws
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"github.com/aws/aws-sdk-go-v2/feature/ec2/imds"
smithyhttp "github.com/aws/smithy-go/transport/http"
)
// MetadataConfig represents a metadata AWS instance.
type MetadataConfig struct {
Hostname string `json:"hostname,omitempty"`
InstanceID string `json:"instance-id,omitempty"`
InstanceType string `json:"instance-type,omitempty"`
InstanceLifeCycle string `json:"instance-life-cycle,omitempty"`
PublicIPv4 string `json:"public-ipv4,omitempty"`
PublicIPv6 string `json:"ipv6,omitempty"`
Region string `json:"region,omitempty"`
Zone string `json:"zone,omitempty"`
}
//nolint:gocyclo
func (a *AWS) getMetadata(ctx context.Context) (*MetadataConfig, error) {
getMetadataKey := func(key string) (string, error) {
resp, err := a.metadataClient.GetMetadata(ctx, &imds.GetMetadataInput{
Path: key,
})
if err != nil {
if isNotFoundError(err) {
return "", nil
}
return "", fmt.Errorf("failed to fetch %q from IMDS: %w", key, err)
}
defer resp.Content.Close() //nolint:errcheck
v, err := io.ReadAll(resp.Content)
return string(v), err
}
var (
metadata MetadataConfig
err error
)
if metadata.Hostname, err = getMetadataKey("hostname"); err != nil {
return nil, err
}
if metadata.InstanceType, err = getMetadataKey("instance-type"); err != nil {
return nil, err
}
if metadata.InstanceLifeCycle, err = getMetadataKey("instance-life-cycle"); err != nil {
return nil, err
}
if metadata.InstanceID, err = getMetadataKey("instance-id"); err != nil {
return nil, err
}
if metadata.PublicIPv4, err = getMetadataKey("public-ipv4"); err != nil {
return nil, err
}
if metadata.PublicIPv6, err = getMetadataKey("ipv6"); err != nil {
return nil, err
}
if metadata.Region, err = getMetadataKey("placement/region"); err != nil {
return nil, err
}
if metadata.Zone, err = getMetadataKey("placement/availability-zone"); err != nil {
return nil, err
}
return &metadata, nil
}
func isNotFoundError(err error) bool {
var awsErr *smithyhttp.ResponseError
if errors.As(err, &awsErr) {
return awsErr.HTTPStatusCode() == http.StatusNotFound
}
return false
}