forked from fujiwara/stretcher
/
aws.go
69 lines (63 loc) · 1.66 KB
/
aws.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
package stretcher
import (
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"github.com/crowdmob/goamz/aws"
)
const (
AWSDefaultRegionName = "us-east-1"
AWSDefaultProfileName = "default"
)
func LoadAWSConfigFile(fileName string, profileName string) error {
if profileName == "" {
profileName = "default"
}
f, err := os.Open(fileName)
if err != nil {
return fmt.Errorf("Cannot open %s %s", fileName, err)
}
defer f.Close()
body, err := ioutil.ReadAll(f)
if err != nil {
return fmt.Errorf("Cannot read %s %s", fileName, err)
}
profiles := map[string]map[string]string{}
currentProfile := ""
for _, line := range strings.Split(string(body), "\n") {
if strings.Index(line, "[profile ") == 0 {
p := strings.Split(line, " ")
if len(p) < 2 {
continue
}
currentProfile = strings.Replace(p[1], "]", "", 1)
} else if strings.Index(line, "[default]") == 0 {
currentProfile = "default"
} else if strings.Index(line, "=") != -1 {
pair := strings.Split(line, "=")
key := strings.Trim(pair[0], " ")
val := strings.Trim(pair[1], " ")
if _, ok := profiles[currentProfile]; !ok {
profiles[currentProfile] = map[string]string{}
}
profiles[currentProfile][key] = val
}
}
profile, ok := profiles[profileName]
if !ok {
return fmt.Errorf("profile [%s] not found in %s", profileName, fileName)
}
AWSAuth = aws.Auth{
AccessKey: profile["aws_access_key_id"],
SecretKey: profile["aws_secret_access_key"],
}
if profile["region"] == "" {
profile["region"] = AWSDefaultRegionName
}
AWSRegion = aws.GetRegion(profile["region"])
log.Printf("aws_access_key_id=%s", AWSAuth.AccessKey)
log.Printf("region=%s", AWSRegion.Name)
return nil
}