-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
263 lines (213 loc) · 6.06 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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package main
// Use this code snippet in your app.
// If you need more information about configurations or implementing the sample code, visit the AWS docs:
// https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/setting-up.html
import (
"encoding/json"
"errors"
"fmt"
"os"
"strconv"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/secretsmanager"
)
var (
region string
secretsPath string
fileMode os.FileMode = 0440
)
const (
ignoreTag = "aws_sm_loader_ignore"
)
type Secret struct {
Key string
Value string
}
func getSecret(secretName string) *string {
//Create a Secrets Manager client
s, err := session.NewSession()
if err != nil {
panic(err)
}
svc := secretsmanager.New(s,
aws.NewConfig().WithRegion(region))
input := &secretsmanager.GetSecretValueInput{
SecretId: aws.String(secretName),
VersionStage: aws.String("AWSCURRENT"), // VersionStage defaults to AWSCURRENT if unspecified
}
// In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
// See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
result, err := svc.GetSecretValue(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case secretsmanager.ErrCodeDecryptionFailure:
// Secrets Manager can't decrypt the protected secret text using the provided KMS key.
fmt.Println(secretsmanager.ErrCodeDecryptionFailure)
panic(aerr.Error())
case secretsmanager.ErrCodeInternalServiceError:
// An error occurred on the server side.
fmt.Println(secretsmanager.ErrCodeInternalServiceError, aerr.Error())
panic(aerr.Error())
case secretsmanager.ErrCodeInvalidParameterException:
// You provided an invalid value for a parameter.
fmt.Println(secretsmanager.ErrCodeInvalidParameterException, aerr.Error())
panic(aerr.Error())
case secretsmanager.ErrCodeInvalidRequestException:
// You provided a parameter value that is not valid for the current state of the resource.
fmt.Println(secretsmanager.ErrCodeInvalidRequestException, aerr.Error())
panic(aerr.Error())
case secretsmanager.ErrCodeResourceNotFoundException:
// We can't find the resource that you asked for.
fmt.Println(secretsmanager.ErrCodeResourceNotFoundException, aerr.Error())
panic(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
panic(err.Error())
}
fmt.Println(err.Error())
panic(err.Error())
}
// Decrypts secret using the associated KMS CMK.
// Depending on whether the secret is a string or binary, one of these fields will be populated.
if result.SecretString != nil {
return result.SecretString
} else {
secretName := strings.Split(*result.Name, "/")
f, err := os.Create(secretsPath + secretName[len(secretName)-1])
if err != nil {
panic(err)
}
defer f.Close()
if _, err := f.Write(result.SecretBinary); err != nil {
panic(err)
}
if err := f.Sync(); err != nil {
panic(err)
}
f.Chmod(fileMode)
return nil
}
}
func listAllSecrets() []*secretsmanager.ListSecretsOutput {
s, err := session.NewSession()
if err != nil {
panic(err)
}
svc := secretsmanager.New(s,
aws.NewConfig().WithRegion(region))
result := &secretsmanager.ListSecretsOutput{
NextToken: nil,
}
var results []*secretsmanager.ListSecretsOutput
for {
input := &secretsmanager.ListSecretsInput{
MaxResults: aws.Int64(100),
NextToken: result.NextToken,
}
result, err = svc.ListSecrets(input)
if err != nil {
fmt.Println(err.Error())
}
results = append(results, result)
if result.NextToken == nil {
break
}
}
return results
}
func filterSecrets(targetTags map[string]string) []string {
allSecrets := listAllSecrets()
var filteredSecrets []string
for _, secretOutput := range allSecrets {
for _, secret := range secretOutput.SecretList {
// If secret has no tags, skip it
if len(secret.Tags) == 0 {
continue
}
// Convert tags on resource into map
resourceTags := make(map[string]string)
ignored := false
for _, tag := range secret.Tags {
if *tag.Key == ignoreTag && *tag.Value == "true" {
ignored = true
break
}
resourceTags[*tag.Key] = *tag.Value
}
if ignored {
continue
}
// Check if resource has all required tags specified in env
hasAllTags := true
for key, value := range targetTags {
if resourceTags[key] != value {
hasAllTags = false
break
}
}
if hasAllTags {
filteredSecrets = append(filteredSecrets, *secret.Name)
}
}
}
return filteredSecrets
}
func filterEnvVars(targetPrefix string) map[string]string {
var result map[string]string
allVars := os.Environ()
result = make(map[string]string)
for _, env := range allVars {
if strings.HasPrefix(env, targetPrefix) {
trimmed := strings.TrimPrefix(env, targetPrefix)
pair := strings.SplitN(trimmed, "=", 2)
result[pair[0]] = pair[1]
}
}
return result
}
func parseSecrets(secretsNames []string) []string {
var secrets []string
for _, secret := range secretsNames {
var parsedSecret map[string]string
s := getSecret(secret)
if s == nil {
continue
}
err := json.Unmarshal([]byte(*s), &parsedSecret)
if err != nil {
fmt.Println(err)
}
for key, value := range parsedSecret {
secrets = append(secrets, "export "+key+"='"+value+"'")
}
}
return secrets
}
func main() {
region = os.Getenv("AWS_REGION")
secretsPath = os.Getenv("SM_SECRETS_PATH")
sm_tags := filterEnvVars("SM_TAG_")
if os.Getenv("SM_SECRETS_FILEMODE") != "" {
fm, err := strconv.ParseInt(os.Getenv("SM_SECRETS_FILEMODE"), 0, 32)
if err != nil {
panic(err)
}
fileMode = os.FileMode(int(fm))
}
if len(sm_tags) == 0 {
err := errors.New("No tags for secrets filtering specified")
panic(err)
}
filteredSecretsNames := filterSecrets(sm_tags)
parsedSecrets := parseSecrets(filteredSecretsNames)
for _, s := range parsedSecrets {
fmt.Println(s)
}
}