/
aws.go
211 lines (186 loc) · 4.92 KB
/
aws.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package aws
import (
"context"
"fmt"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ssm"
"gopkg.in/yaml.v2"
"k8s.io/klog"
)
const (
awsDetectionTimeout = 1 * time.Second
awsTimeout = 10 * time.Second
ssmMaxChunks = 10
ssmParameterBaseName = "config"
)
type AWSParameters struct {
base string
ssm *ssm.SSM
}
func detectRegion() string {
session, err := session.NewSession()
if err != nil {
klog.Warningf("creating session to autodetect AWS region: %v", err)
return ""
}
client := ec2metadata.New(session)
ctx, cancel := context.WithTimeout(aws.BackgroundContext(), awsDetectionTimeout)
defer cancel()
region, err := client.RegionWithContext(ctx)
if err != nil {
klog.Warningf("trying to autodetect AWS region: %v", err)
return ""
}
klog.V(2).Infof("detected AWS region: %q", region)
return region
}
func detectInstanceID() string {
session, err := session.NewSession()
if err != nil {
klog.Warningf("creating session to autodetect AWS region: %v", err)
return ""
}
client := ec2metadata.New(session)
ctx, cancel := context.WithTimeout(aws.BackgroundContext(), awsDetectionTimeout)
defer cancel()
instanceID, err := client.GetMetadataWithContext(ctx, "instance-id")
if err != nil {
klog.Warningf("trying to autodetect AWS instance ID: %v", err)
return ""
}
klog.V(2).Infof("detected AWS instance ID: %q", instanceID)
return instanceID
}
func getAWSConfig() (*aws.Config, error) {
region := os.Getenv("AWS_REGION")
if region == "" {
region = os.Getenv("AWS_DEFAULT_REGION")
}
if region == "" {
region = detectRegion()
}
if region == "" {
return nil, fmt.Errorf("failed to detect AWS region")
}
httpClient := &http.Client{
Timeout: awsTimeout,
}
config := aws.NewConfig().WithHTTPClient(httpClient).WithRegion(region)
return config, nil
}
func NewAWSParameters(base string, config *aws.Config) (*AWSParameters, error) {
if config == nil {
var err error
config, err = getAWSConfig()
if err != nil {
return nil, fmt.Errorf("creating AWS config: %v", err)
}
}
instanceID := detectInstanceID()
if instanceID == "" {
return nil, fmt.Errorf("failed to detect AWS instance ID, not running on AWS?")
}
sess, err := session.NewSession()
if err != nil {
return nil, err
}
ssmClient := ssm.New(sess, config)
return &AWSParameters{
base: filepath.Join(base, instanceID),
ssm: ssmClient,
}, nil
}
func unmarshalParameters(params map[string]string) (map[string]string, error) {
// This is either one single SSM parameter if it fit (<=4096 bytes), or
// chunks of the serialized config e.g. "config-0", "config-1", etc. We
// need to assemble the chunks in order, de-serialize and re-create the
// original config map.
if len(params) == 0 {
return nil, fmt.Errorf("got no SSM parameters")
}
// The whole map in one parameter.
if len(params) == 1 {
for k, v := range params {
configMap := make(map[string]string)
klog.V(2).Infof("unmarshaling SSM parameter %q", k)
err := yaml.Unmarshal([]byte(v), &configMap)
if err != nil {
return nil, err
}
return configMap, nil
}
}
// Multiple chunks.
paramList := make([]string, len(params))
for k, v := range params {
parts := strings.SplitN(k, "-", 2)
if len(parts) < 2 {
return nil, fmt.Errorf("invalid SSM parameter chunk key: %s", k)
}
n, err := strconv.ParseUint(parts[1], 10, 32)
if err != nil {
return nil, err
}
if int(n) >= len(paramList) {
return nil, fmt.Errorf("invalid SSM parameter chunk key: %s", k)
}
paramList[n] = v
}
yml := ""
for i := range paramList {
yml = yml + paramList[i]
}
configMap := make(map[string]string)
klog.V(2).Infof("unmarshaling %d SSM parameter chunks, %d bytes", len(paramList), len(yml))
err := yaml.Unmarshal([]byte(yml), &configMap)
if err != nil {
return nil, err
}
return configMap, nil
}
func (a *AWSParameters) getParameter(name string) string {
path := filepath.Join(a.base, name)
in := &ssm.GetParameterInput{
Name: aws.String(path),
WithDecryption: aws.Bool(true),
}
out, err := a.ssm.GetParameter(in)
if err != nil {
klog.V(2).Infof("getting SSM parameter %s: %v", name, err)
return ""
}
if out.Parameter == nil {
klog.V(2).Infof("got nil SSM parameter value for %s", name)
return ""
}
return aws.StringValue(out.Parameter.Value)
}
func (a *AWSParameters) GetAllParameters() (map[string]string, error) {
params := make(map[string]string)
name := ssmParameterBaseName
value := a.getParameter(name)
if value != "" {
params[name] = value
}
for i := 0; i < ssmMaxChunks; i++ {
name = fmt.Sprintf("%s-%d", ssmParameterBaseName, i)
value = a.getParameter(name)
if value == "" {
break
}
params[name] = value
}
configMap, err := unmarshalParameters(params)
if err != nil {
return nil, err
}
return configMap, nil
}