-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
199 lines (165 loc) · 4.78 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
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"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"
"gopkg.in/yaml.v2"
)
type Config struct {
Secrets map[string]struct {
KeyValue map[string]string `yaml:"key_value,omitempty"`
PlainText string `yaml:"plaintext,omitempty"`
File string `yaml:"file,omitempty"`
Tags map[string]string `yaml:"tags"`
} `yaml:"secrets"`
}
type CLIOpts struct {
Profile string
Config string
Region string
KMSKey string
}
func main() {
cli := parseFlags()
data, err := ioutil.ReadFile(cli.Config)
if err != nil {
log.Fatalf("Failed to read config: %v", err)
}
var config Config
err = yaml.Unmarshal(data, &config)
if err != nil {
log.Printf("Failed to parse config: %v", err)
}
err = validateConfig(config)
if err != nil {
log.Fatalf("Invalid config: %v", err)
}
sess, err := createAWSSession(cli.Profile, cli.Region)
svc := secretsmanager.New(sess)
manageSecrets(svc, config, &cli.KMSKey)
}
func parseFlags() CLIOpts {
profile := flag.String("profile", "default", "AWS profile to use")
configPath := flag.String("config", "", "Path to the config file")
region := flag.String("region", "us-east-1", "AWS region")
kms := flag.String("kms", "", "KMS key ID or alias to use for encrypting the secrets")
flag.Parse()
return CLIOpts{
Profile: *profile,
Config: *configPath,
Region: *region,
KMSKey: *kms,
}
}
func validateConfig(config Config) error {
for name, secret := range config.Secrets {
if secret.KeyValue != nil && secret.File != "" {
return fmt.Errorf("secret '%s' has both KeyValue and File set, which is not allowed", name)
}
if secret.KeyValue == nil && secret.File == "" && secret.PlainText == "" {
return fmt.Errorf("secret '%s' must have either KeyValue, File, or PlainText set", name)
}
for tagKey, tagValue := range secret.Tags {
if tagKey == "" || tagValue == "" {
return fmt.Errorf("secret '%s' has invalid tag. Tags must not be empty", name)
}
}
}
return nil
}
func createAWSSession(profile, region string) (*session.Session, error) {
sessOpts := session.Options{
Profile: profile,
Config: aws.Config{
Region: aws.String(region),
},
}
return session.NewSessionWithOptions(sessOpts)
}
func manageSecrets(svc *secretsmanager.SecretsManager, config Config, kms *string) {
for name, secret := range config.Secrets {
var secretValue string
if secret.KeyValue != nil {
marshaledValue, err := json.Marshal(secret.KeyValue)
if err != nil {
log.Printf("Failed to marshal secret %s: %v", name, err)
continue
}
secretValue = string(marshaledValue)
} else if secret.File != "" {
content, err := ioutil.ReadFile(secret.File)
if err != nil {
log.Printf("Failed to read file %s: %v", secret.File, err)
continue
}
secretValue = string(content)
} else {
secretValue = secret.PlainText
}
tags := make([]*secretsmanager.Tag, 0, len(secret.Tags))
for k, v := range secret.Tags {
tags = append(tags, &secretsmanager.Tag{
Key: aws.String(k),
Value: aws.String(v),
})
}
// this is to avoid updating the secret if the value is the same
currentValue, err := svc.GetSecretValue(&secretsmanager.GetSecretValueInput{
SecretId: aws.String(name),
})
switch {
case err == nil:
// If current value is the same as new value, skip update
if currentValue.SecretString != nil && *currentValue.SecretString == string(secretValue) {
fmt.Printf("Secret %s has no changes, skipping update\n", name)
continue
}
updateInput := &secretsmanager.UpdateSecretInput{
SecretId: aws.String(name),
SecretString: aws.String(string(secretValue)),
KmsKeyId: kms,
}
if *kms != "" {
updateInput.KmsKeyId = kms
}
_, err = svc.UpdateSecret(updateInput)
if err != nil {
log.Printf("Failed to update secret %s: %v", name, err)
} else {
fmt.Printf("Secret %s updated successfully\n", name)
}
case isAWSError(err, secretsmanager.ErrCodeResourceNotFoundException):
createInput := &secretsmanager.CreateSecretInput{
Name: aws.String(name),
SecretString: aws.String(string(secretValue)),
KmsKeyId: kms,
Tags: tags,
}
if *kms != "" {
createInput.KmsKeyId = kms
}
_, err := svc.CreateSecret(createInput)
if err != nil {
log.Printf("Failed to create secret %s: %v", name, err)
} else {
fmt.Printf("Secret %s created successfully\n", name)
}
default:
log.Printf("Failed to describe secret %s: %v", name, err)
}
}
}
func isAWSError(err error, code string) bool {
if aerr, ok := err.(awserr.Error); ok {
if aerr.Code() == code {
return true
}
}
return false
}