This repository was archived by the owner on Nov 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 255
Expand file tree
/
Copy pathcontext.go
More file actions
441 lines (399 loc) · 10.9 KB
/
context.go
File metadata and controls
441 lines (399 loc) · 10.9 KB
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
/*
Copyright 2020 Docker Compose CLI authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ecs
import (
"context"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"github.com/AlecAivazis/survey/v2/terminal"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/defaults"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/docker/compose/v2/pkg/api"
"github.com/docker/compose/v2/pkg/prompt"
"github.com/pkg/errors"
"gopkg.in/ini.v1"
"github.com/docker/compose-cli/api/context/store"
)
func getEnvVars() ContextParams {
c := ContextParams{
Profile: os.Getenv("AWS_PROFILE"),
Region: os.Getenv("AWS_REGION"),
}
if c.Region == "" {
defaultRegion := os.Getenv("AWS_DEFAULT_REGION")
if defaultRegion == "" {
defaultRegion = "us-east-1"
}
c.Region = defaultRegion
}
p := credentials.EnvProvider{}
creds, err := p.Retrieve()
if err != nil {
return c
}
c.AccessKey = creds.AccessKeyID
c.SecretKey = creds.SecretAccessKey
c.SessionToken = creds.SessionToken
return c
}
type contextCreateAWSHelper struct {
user prompt.UI
availableRegions func(opts *ContextParams) ([]string, error)
}
func newContextCreateHelper() contextCreateAWSHelper {
return contextCreateAWSHelper{
user: prompt.User{},
availableRegions: listAvailableRegions,
}
}
func (h contextCreateAWSHelper) createContextData(_ context.Context, opts ContextParams) (interface{}, string, error) {
if opts.CredsFromEnv {
// Explicit creation from ENV variables
ecsCtx, descr := h.createContext(&opts)
return ecsCtx, descr, nil
} else if opts.AccessKey != "" && opts.SecretKey != "" {
// Explicit creation using keys
err := h.createProfileFromCredentials(&opts)
if err != nil {
return nil, "", err
}
} else if opts.Profile != "" {
// Excplicit creation by selecting a profile
// check profile exists
profilesList, err := getProfiles()
if err != nil {
return nil, "", err
}
if !contains(profilesList, opts.Profile) {
return nil, "", errors.Wrapf(api.ErrNotFound, "profile %q not found", opts.Profile)
}
} else {
// interactive
var options []string
var actions []func(params *ContextParams) error
if _, err := os.Stat(getAWSConfigFile()); err == nil {
// User has .aws/config file, so we can offer to select one of his profiles
options = append(options, "An existing AWS profile")
actions = append(actions, h.selectFromLocalProfile)
}
options = append(options, "AWS secret and token credentials")
actions = append(actions, h.createProfileFromCredentials)
options = append(options, "AWS environment variables")
actions = append(actions, func(params *ContextParams) error {
opts.CredsFromEnv = true
return nil
})
selected, err := h.user.Select("Create a Docker context using:", options)
if err != nil {
if err == terminal.InterruptErr {
return nil, "", api.ErrCanceled
}
return nil, "", err
}
err = actions[selected](&opts)
if err != nil {
return nil, "", err
}
}
ecsCtx, descr := h.createContext(&opts)
return ecsCtx, descr, nil
}
func (h contextCreateAWSHelper) createContext(c *ContextParams) (interface{}, string) {
var description string
if c.CredsFromEnv {
if c.Description == "" {
description = "credentials read from environment"
}
return store.EcsContext{
CredentialsFromEnv: c.CredsFromEnv,
Profile: c.Profile,
}, description
}
if c.Region != "" {
description = strings.TrimSpace(
fmt.Sprintf("%s (%s)", c.Description, c.Region))
}
return store.EcsContext{
Profile: c.Profile,
}, description
}
func (h contextCreateAWSHelper) selectFromLocalProfile(opts *ContextParams) error {
profilesList, err := getProfiles()
if err != nil {
return err
}
opts.Profile, err = h.chooseProfile(profilesList)
return err
}
func (h contextCreateAWSHelper) createProfileFromCredentials(opts *ContextParams) error {
if opts.AccessKey == "" || opts.SecretKey == "" {
fmt.Println("Retrieve or create AWS Access Key and Secret on https://console.aws.amazon.com/iam/home?#security_credential")
accessKey, secretKey, sessionToken, err := h.askCredentials()
if err != nil {
return err
}
opts.AccessKey = accessKey
opts.SecretKey = secretKey
opts.SessionToken = sessionToken
}
if opts.Region == "" {
err := h.chooseRegion(opts)
if err != nil {
return err
}
}
// save as a profile
if opts.Profile == "" {
opts.Profile = "default"
}
// context name used as profile name
err := h.saveCredentials(opts.Profile, opts.AccessKey, opts.SecretKey, opts.SessionToken)
if err != nil {
return err
}
return h.saveRegion(opts.Profile, opts.Region)
}
func (h contextCreateAWSHelper) saveCredentials(profile string, accessKeyID string, secretAccessKey string, sessionToken string) error {
file := getAWSCredentialsFile()
err := os.MkdirAll(filepath.Dir(file), 0700)
if err != nil {
return err
}
credentials, err := ini.Load(file)
if err != nil {
if !os.IsNotExist(err) {
return err
}
credentials = ini.Empty()
}
section, err := credentials.NewSection(profile)
if err != nil {
return err
}
_, err = section.NewKey("aws_access_key_id", accessKeyID)
if err != nil {
return err
}
_, err = section.NewKey("aws_secret_access_key", secretAccessKey)
if err != nil {
return err
}
if sessionToken != "" {
_, err = section.NewKey("aws_session_token", sessionToken)
if err != nil {
return err
}
}
return credentials.SaveTo(file)
}
func (h contextCreateAWSHelper) saveRegion(profile, region string) error {
if region == "" {
return nil
}
// loads ~/.aws/config
awsConfig := getAWSConfigFile()
configIni, err := ini.Load(awsConfig)
if err != nil {
if !os.IsNotExist(err) {
return err
}
configIni = ini.Empty()
}
profile = fmt.Sprintf("profile %s", profile)
section, err := configIni.GetSection(profile)
if err != nil {
if !strings.Contains(err.Error(), "does not exist") {
return err
}
section, err = configIni.NewSection(profile)
if err != nil {
return err
}
}
// save region under profile section in ~/.aws/config
_, err = section.NewKey("region", region)
if err != nil {
return err
}
return configIni.SaveTo(awsConfig)
}
func getProfiles() ([]string, error) {
profiles := []string{}
// parse both .aws/credentials and .aws/config for profiles
configFiles := map[string]bool{
getAWSCredentialsFile(): false,
getAWSConfigFile(): true,
}
for f, prefix := range configFiles {
sections, err := loadIniFile(f, prefix)
if err != nil {
if os.IsNotExist(err) {
continue
}
return nil, err
}
for key := range sections {
name := strings.ToLower(key)
if !contains(profiles, name) {
profiles = append(profiles, name)
}
}
}
sort.Slice(profiles, func(i, j int) bool {
return profiles[i] < profiles[j]
})
return profiles, nil
}
func (h contextCreateAWSHelper) chooseProfile(profiles []string) (string, error) {
options := []string{}
options = append(options, profiles...)
selected, err := h.user.Select("Select AWS Profile", options)
if err != nil {
if err == terminal.InterruptErr {
return "", api.ErrCanceled
}
return "", err
}
profile := options[selected]
return profile, nil
}
func getRegion(profile string) (string, error) {
if profile == "" {
profile = "default"
}
// only load ~/.aws/config
awsConfig := defaults.SharedConfigFilename()
configIni, err := ini.Load(awsConfig)
if err != nil {
if !os.IsNotExist(err) {
return "", err
}
configIni = ini.Empty()
}
getProfileRegion := func(p string) string {
r := ""
section, err := configIni.GetSection(p)
if err == nil {
reg, err := section.GetKey("region")
if err == nil {
r = reg.Value()
}
}
return r
}
if profile != "default" {
profile = fmt.Sprintf("profile %s", profile)
}
region := getProfileRegion(profile)
if region == "" {
region = getProfileRegion("default")
}
if region == "" {
// fallback to AWS default
region = "us-east-1"
}
return region, nil
}
func (h contextCreateAWSHelper) chooseRegion(opts *ContextParams) error {
regions, err := h.availableRegions(opts)
if err != nil {
return err
}
// promp user for region
selected, err := h.user.Select("Region", regions)
if err != nil {
return err
}
opts.Region = regions[selected]
return nil
}
func listAvailableRegions(opts *ContextParams) ([]string, error) {
// Setup SDK with credentials, will also validate those
session, err := session.NewSessionWithOptions(session.Options{
Config: aws.Config{
Credentials: credentials.NewStaticCredentials(opts.AccessKey, opts.SecretKey, opts.SessionToken),
Region: aws.String("us-east-1"),
},
})
if err != nil {
return nil, err
}
desc, err := ec2.New(session).DescribeRegions(&ec2.DescribeRegionsInput{})
if err != nil {
return nil, err
}
var regions []string
for _, r := range desc.Regions {
regions = append(regions, aws.StringValue(r.RegionName))
}
return regions, nil
}
func (h contextCreateAWSHelper) askCredentials() (string, string, string, error) {
accessKeyID, err := h.user.Input("AWS Access Key ID", "")
if err != nil {
return "", "", "", err
}
secretAccessKey, err := h.user.Password("Enter AWS Secret Access Key")
if err != nil {
return "", "", "", err
}
sessionToken, err := h.user.Password("AWS Session Token (optional)")
// validate access ID and password
if len(accessKeyID) < 3 || len(secretAccessKey) < 3 {
return "", "", "", fmt.Errorf("AWS Access/Secret Access Key must have more than 3 characters")
}
return accessKeyID, secretAccessKey, sessionToken, nil
}
func contains(values []string, value string) bool {
for _, v := range values {
if v == value {
return true
}
}
return false
}
func loadIniFile(path string, prefix bool) (map[string]ini.Section, error) {
profiles := map[string]ini.Section{}
credIni, err := ini.Load(path)
if err != nil {
return nil, err
}
for _, section := range credIni.Sections() {
if prefix && strings.HasPrefix(section.Name(), "profile ") {
profiles[section.Name()[len("profile "):]] = *section
} else if !prefix || section.Name() == "default" {
profiles[section.Name()] = *section
}
}
return profiles, nil
}
func getAWSConfigFile() string {
awsConfig, ok := os.LookupEnv("AWS_CONFIG_FILE")
if !ok {
awsConfig = defaults.SharedConfigFilename()
}
return awsConfig
}
func getAWSCredentialsFile() string {
awsConfig, ok := os.LookupEnv("AWS_SHARED_CREDENTIALS_FILE")
if !ok {
awsConfig = defaults.SharedCredentialsFilename()
}
return awsConfig
}