forked from RiotGames/key-conjurer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
awsconfig.go
87 lines (73 loc) · 2.06 KB
/
awsconfig.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
package main
import (
"os"
"path/filepath"
"strings"
"github.com/go-ini/ini"
homedir "github.com/mitchellh/go-homedir"
)
// Intentionally missing the `ini` notation sections,keys, and values are being handled by the ini library
type CloudCliEntry struct {
profileName string
keyID string
key string
token string
}
func NewCloudCliEntry(c CloudCredentials, a *Account) CloudCliEntry {
name := a.Name
if a.Alias != "" {
name = a.Alias
}
return CloudCliEntry{
profileName: name,
keyID: c.AccessKeyID,
key: c.SecretAccessKey,
token: c.SessionToken,
}
}
func TouchFile(path string) (*os.File, error) {
return os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0664)
}
func getCloudCliCredentialsFile(path string) (*ini.File, error) {
f, err := TouchFile(path)
if err != nil {
return nil, err
}
defer f.Close()
return ini.Load(f)
}
func ResolveAWSCredentialsPath(rootPath string) string {
rootPath = filepath.Join(rootPath, "credentials")
if fullPath, err := homedir.Expand(rootPath); err == nil {
return fullPath
}
return rootPath
}
func saveCredentialEntry(file *ini.File, entry CloudCliEntry, cloud string) error {
section := file.Section(entry.profileName)
if cloud == cloudAws {
section.Key("aws_access_key_id").SetValue(entry.keyID)
section.Key("aws_secret_access_key").SetValue(entry.key)
section.Key("aws_session_token").SetValue(entry.token)
} else if cloud == cloudTencent {
section.Key("tencent_access_key_id").SetValue(entry.keyID)
section.Key("tencent_secret_access_key").SetValue(entry.key)
section.Key("tencent_session_token").SetValue(entry.token)
}
return nil
}
func SaveCloudCredentialInCLI(cloudCliPath string, entry CloudCliEntry) error {
path := ResolveAWSCredentialsPath(cloudCliPath)
file, err := getCloudCliCredentialsFile(path)
if err != nil {
return err
}
cloud := cloudAws
if strings.Contains(strings.ToLower(path), cloudTencent) {
cloud = cloudTencent
}
if err := saveCredentialEntry(file, entry, cloud); err != nil {
return err
}
return file.SaveTo(path)
}