-
Notifications
You must be signed in to change notification settings - Fork 787
/
common.go
74 lines (61 loc) · 1.86 KB
/
common.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
package amazon
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"os"
"path"
"runtime"
)
const DefaultRegion = "us-west-2"
func NewAwsSession(profileOption string, regionOption string) (*session.Session, error) {
config := aws.Config{}
if regionOption != "" {
config.Region = aws.String(regionOption)
}
if _, err := os.Stat(path.Join(UserHomeDir(), ".aws", "credentials")); !os.IsNotExist(err) {
config.Credentials = credentials.NewChainCredentials(
[]credentials.Provider{
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{Filename: "", Profile: profileOption},
})
}
sessionOptions := session.Options{
SharedConfigState: session.SharedConfigEnable,
Config: config,
}
if profileOption != "" {
sessionOptions.Profile = profileOption
}
awsSession, err := session.NewSessionWithOptions(sessionOptions)
if *awsSession.Config.Region == "" {
awsSession.Config.Region = aws.String(DefaultRegion)
}
if err != nil {
return nil, err
}
return awsSession, nil
}
func NewAwsSessionWithoutOptions() (*session.Session, error) {
return NewAwsSession("", "")
}
func ResolveRegion(profileOption string, regionOption string) (string, error) {
session, err := NewAwsSession(profileOption, regionOption)
if err != nil {
return "", err
}
return *session.Config.Region, nil
}
func ResolveRegionWithoutOptions() (string, error) {
return ResolveRegion("", "")
}
// UserHomeDir returns the home directory for the user the process is running under.
// This is a copy of shareddefaults.UserHomeDir in the internal AWS package.
// We can't user user.Current().HomeDir as we want to override this during testing. :-|
func UserHomeDir() string {
if runtime.GOOS == "windows" { // Windows
return os.Getenv("USERPROFILE")
}
// *nix
return os.Getenv("HOME")
}