-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
85 lines (66 loc) · 1.84 KB
/
config.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
package main
import (
"errors"
"fmt"
"os/user"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/go-ini/ini"
)
var profileName string
// GetSessionWithProfile will return a new aws session with optional profile
func GetSessionWithProfile(profile string) (*session.Session, error) {
config := aws.NewConfig()
// Get and save profile
if profile != "" {
profileName = profile
config = config.WithCredentials(credentials.NewSharedCredentials("", profileName))
// Debug creds...
// fmt.Println(config.Credentials.Get())
}
return getSessionWithConfig(config)
}
// GetSession starts an AWS session with region auto-detection
func GetSession() (*session.Session, error) {
config := aws.NewConfig()
return getSessionWithConfig(config)
}
// getSessionWithConfig grabs the region and appends to the current config
func getSessionWithConfig(config *aws.Config) (*session.Session, error) {
region, err := getAWSRegion()
if profileName != "" {
fmt.Println("Profile: ", *profile)
} else {
fmt.Println("Profile: default")
}
if region != "" {
fmt.Println("Region: ", region)
config = config.WithRegion(region)
}
fmt.Println()
return session.New(config), err
}
func getAWSRegion() (string, error) {
currentUser, err := user.Current()
if err != nil {
return "", err
}
cfgPath := fmt.Sprintf("%s/.aws/config", currentUser.HomeDir)
cfg, err := ini.Load(cfgPath)
if err != nil {
return "", err
}
var sectionName string
if profileName != "" {
sectionName = fmt.Sprintf("profile %s", profileName)
} else {
sectionName = "default"
}
section := cfg.Section(sectionName)
if err != nil || !section.HasKey("region") {
return "", errors.New("Did not find AWS region from config file")
}
region := section.Key("region").String()
return region, nil
}