-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
88 lines (73 loc) · 2.09 KB
/
main.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
package main
import (
"log"
"os"
"path/filepath"
"github.com/manifoldco/promptui"
"gopkg.in/ini.v1"
)
func getFilePath() string {
home, err := os.UserHomeDir()
if err != nil {
log.Fatal(err)
}
// Joining the home directory path with the path of the file
filePath := filepath.Join(home, ".aws/credentials")
return filePath
}
func loadFile() *ini.File {
// Load the INI file
cfg, err := ini.Load(getFilePath())
if err != nil {
log.Fatal(err)
}
return cfg
}
func getProfiles(ini *ini.File) []string {
var profiles []string
for _, section := range ini.Sections() {
if section.Name() == "default" && section.Key("created_by_go").String() == "" {
panic("Please change default profile to something else")
} else if section.Name() != "DEFAULT" && (section.Name() != "default" && section.Key("created_by_go").String() != "true") {
profiles = append(profiles, section.Name())
}
}
return profiles
}
func chooseProfile(profiles []string) string {
// Create a new promptui Select
prompt := promptui.Select{
Label: "Select Profile",
Items: profiles,
}
// Show the prompt and get the result
_, result, err := prompt.Run()
if err != nil {
log.Fatalf("Prompt failed %v\n", err)
}
return result
}
func updateDefaultProfile(ini *ini.File, profile string) {
// fmt.Println(profile)
section := ini.Section(profile)
// Get the access key ID and secret access key for the selected profile
accessKeyID := section.Key("aws_access_key_id").String()
secretAccessKey := section.Key("aws_secret_access_key").String()
region := section.Key("region").String()
// Set these credentials for the default profile
defaultSection := ini.Section("default")
defaultSection.Key("aws_access_key_id").SetValue(accessKeyID)
defaultSection.Key("aws_secret_access_key").SetValue(secretAccessKey)
defaultSection.Key("created_by_go").SetValue("true")
if region != "" {
defaultSection.Key("region").SetValue(region)
}
// Save the INI file
ini.SaveTo(getFilePath())
}
func main() {
cfg := loadFile()
profiles := getProfiles(cfg)
result := chooseProfile(profiles)
updateDefaultProfile(cfg, result)
}