-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
211 lines (170 loc) · 4.99 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package main
import (
"encoding/json"
"flag"
"fmt"
"os"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ssm"
"gopkg.in/yaml.v2"
)
var Version string = "dev"
var CommitHash string = "n/a"
var BuildTimestamp string = "n/a"
func main() {
format := new(string)
version := new(bool)
paramsType := new(string)
flag.StringVar(format, "format", "json", "")
flag.StringVar(format, "f", "json", "")
flag.BoolVar(version, "v", false, "")
flag.BoolVar(version, "version", false, "")
flag.StringVar(paramsType, "t", "", "")
flag.StringVar(paramsType, "type", "", "")
flag.Usage = func() {
fmt.Printf(`Recursively gather parameters stored in AWS SSM under a given path.
%[1]s [-h/--help] [-f/--format yaml|json] [-t/--type String|SecureString] [path]
Options:
-h, --help show brief help
-v, --version show the current build version
-f, --format [json|yaml] output format (default "json")
-t, --type [String|SecureString] gather parameter of specific type
`,
os.Args[0],
)
}
flag.Parse()
if *version {
fmt.Printf("Version: %v\nCommit Hash: %v\nBuild Timestamp: %v\n", Version, CommitHash, BuildTimestamp)
return
}
var path = flag.Arg(0)
if *paramsType != "" && *paramsType != "String" && *paramsType != "SecureString" {
fmt.Fprintf(
os.Stderr,
"Invalid value '%v' for 'type' argument. Accepted values: ['', 'String', 'SecureString'].\n",
*paramsType,
)
os.Exit(1)
}
if *format != "json" && *format != "yaml" {
fmt.Fprintf(
os.Stderr,
"Invalid value '%v' for 'format' option. Accepted values: ['yaml', 'json'].\n",
*format,
)
os.Exit(1)
}
path = strings.TrimPrefix(strings.TrimSuffix(path, "/"), "/")
key := fmt.Sprintf("/%s", path)
client, err := newClient()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
var types []string
switch *paramsType {
case "":
types = []string{"String", "SecureString"}
case "String":
types = []string{"String"}
case "SecureString":
types = []string{"SecureString"}
}
params, err := getParameters(client, key, types)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
var result []byte
switch *format {
case "json":
if result, err = json.Marshal(params); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
case "yaml":
if result, err = yaml.Marshal(params); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
fmt.Printf("%v\n", string(result))
}
// newClient creates a new AWS SSM client using the AWS default credentials chain
func newClient() (*ssm.SSM, error) {
sess, err := session.NewSessionWithOptions(session.Options{
Config: aws.Config{
MaxRetries: aws.Int(1),
},
SharedConfigState: session.SharedConfigEnable,
})
if err != nil {
return nil, fmt.Errorf("could not initiate the client: %v", err)
}
return ssm.New(sess), nil
}
// getParameters fetches all parameters whose names start with a given key
func getParameters(client *ssm.SSM, key string, types []string) (map[string]any, error) {
var values []*string
for _, t := range types {
values = append(values, aws.String(t))
}
var withDecryption bool = false
for _, t := range types {
if t == "SecureString" {
withDecryption = true
break
}
}
in := ssm.GetParametersByPathInput{
Path: aws.String(key),
Recursive: aws.Bool(true),
WithDecryption: aws.Bool(withDecryption),
ParameterFilters: []*ssm.ParameterStringFilter{{Key: aws.String("Type"), Values: values}},
}
var out ssm.GetParametersByPathOutput
if err := client.GetParametersByPathPages(&in, func(o *ssm.GetParametersByPathOutput, lastPage bool) bool {
if o != nil && len(o.Parameters) > 0 {
out.Parameters = append(out.Parameters, o.Parameters...)
return true
}
return false
}); err != nil {
return nil, fmt.Errorf("could not fetch parameters: %v", err)
}
return parseParameters(out.Parameters, key), nil
}
// parseParameters converts a list of ssm.Parameter into a map structure, based on the parameters' path
//
// Modified https://github.com/helmfile/vals/blob/b4e9a527ea02d24713761efa5369984beebbc9f2/pkg/providers/ssm/ssm.go#L166
func parseParameters(parameters []*ssm.Parameter, key string) map[string]any {
res := map[string]any{}
for _, param := range parameters {
name := *param.Name
if key != "/" {
name = strings.TrimPrefix(name, key)
}
if name[0] != '/' {
panic(fmt.Errorf("bug: unexpected format of parameter: %s in %s must start with a slash(/)", name, *param.Name))
}
name = name[1:]
var current map[string]any = res
parts := strings.Split(name, "/")
for i, n := range parts {
if i == len(parts)-1 {
current[n] = *param.Value
} else {
if m, ok := current[n]; !ok {
current[n] = map[string]any{}
} else if _, isMap := m.(map[string]any); !isMap {
current[n] = map[string]any{}
}
current = current[n].(map[string]any)
}
}
}
return res
}