Skip to content

Commit cd0fd51

Browse files
committed
dynamically populate from struct
1 parent 57917de commit cd0fd51

File tree

2 files changed

+47
-3
lines changed

2 files changed

+47
-3
lines changed

internal/util/util.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"os/exec"
1111
"path"
1212
"path/filepath"
13+
"reflect"
1314
"strconv"
1415
"strings"
1516
"text/template"
@@ -142,3 +143,34 @@ func ItemInSlice(slice []string, target string) bool {
142143
}
143144
return false
144145
}
146+
147+
// Given a resource of struct type as
148+
// type AWSCreds struct{
149+
// AccessKeyID string `yaml:"accessKeyId,omitempty"`
150+
// SecretAccessKey string `yaml:"accessKeyId,omitempty"`
151+
// }{
152+
// AccessKeyID: "FOO",
153+
// SecretAccessKey: "BAR",
154+
// }
155+
// It will base on the tag, fill in the value to supplied map[string]string
156+
func ReflectStructValueIntoMap(resource interface{}, tagName string, paramsToFill map[string]string) {
157+
t := reflect.ValueOf(resource)
158+
159+
for i := 0; i < t.NumField(); i++ {
160+
161+
childStruct := t.Type().Field(i)
162+
childValue := t.Field(i)
163+
if childValue.Kind().String() != "string" {
164+
continue
165+
}
166+
tag, _ := parseTag(childStruct.Tag.Get(tagName))
167+
paramsToFill[tag] = childValue.String()
168+
}
169+
}
170+
171+
func parseTag(tag string) (string, string) {
172+
if idx := strings.Index(tag, ","); idx != -1 {
173+
return tag[:idx], tag[idx+1:]
174+
}
175+
return tag, ""
176+
}

pkg/credentials/credentials.go

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"regexp"
99

1010
"github.com/aws/aws-sdk-go/aws/credentials"
11+
"github.com/commitdev/zero/internal/util"
1112
)
1213

1314
type AWSResourceConfig struct {
@@ -25,14 +26,25 @@ func awsCredsPath() string {
2526
return filepath.Join(usr.HomeDir, ".aws/credentials")
2627
}
2728

29+
func fetchAWSConfig(awsPath string, profileName string) (error, AWSResourceConfig) {
30+
31+
awsCreds, err := credentials.NewSharedCredentials(awsPath, profileName).Get()
32+
if err != nil {
33+
return err, AWSResourceConfig{}
34+
}
35+
return nil, AWSResourceConfig{
36+
AccessKeyID: awsCreds.AccessKeyID,
37+
SecretAccessKey: awsCreds.SecretAccessKey,
38+
}
39+
}
40+
2841
func FillAWSProfile(profileName string, paramsToFill map[string]string) error {
2942
awsPath := GetAWSCredsPath()
30-
awsCreds, err := credentials.NewSharedCredentials(awsPath, profileName).Get()
43+
err, awsCreds := fetchAWSConfig(awsPath, profileName)
3144
if err != nil {
3245
return err
3346
}
34-
paramsToFill["accessKeyId"] = awsCreds.AccessKeyID
35-
paramsToFill["secretAccessKey"] = awsCreds.SecretAccessKey
47+
util.ReflectStructValueIntoMap(awsCreds, "yaml", paramsToFill)
3648
return nil
3749
}
3850

0 commit comments

Comments
 (0)