/
import.go
87 lines (74 loc) · 2.09 KB
/
import.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
package main
import (
"fmt"
"io"
"os"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ssm"
"github.com/goccy/go-yaml"
"github.com/nabeken/psadm"
"github.com/pkg/errors"
)
type ImportCommand struct {
Dryrun bool `long:"dryrun" description:"Perform dryrun"`
Overwrite bool `long:"overwrite" description:"Overwrite the value in the key if it exists"`
SkipExist bool `long:"skip-exist" description:"Skip the existing key"`
DefaultKMSKeyID string `long:"default-kms-key-id" description:"Specify a default KMS Key ID"`
}
func (cmd *ImportCommand) Execute(args []string) error {
if len(args) == 0 {
return errors.New("You must specify a YAML file to be imported.")
}
f, err := os.Open(args[0])
if err != nil {
return errors.Wrapf(err, "failed to open %s", args[0])
}
defer f.Close()
data, err := io.ReadAll(f)
if err != nil {
return errors.Wrapf(err, "failed to read data from %s", args[0])
}
var params []*psadm.Parameter
if err := yaml.Unmarshal(data, ¶ms); err != nil {
return errors.Wrap(err, "failed to unmarshal from YAML")
}
client := psadm.NewClient(session.Must(session.NewSession()))
// function to update
actualRun := func(p *psadm.Parameter) error {
if err := client.PutParameter(p, cmd.Overwrite); err != nil {
if awsErr, ok := errors.Cause(err).(awserr.Error); ok {
if awsErr.Code() == ssm.ErrCodeParameterAlreadyExists && cmd.SkipExist {
return nil
}
}
return err
}
return nil
}
dryRun := func(p *psadm.Parameter) error {
fmt.Printf("dryrun: '%s' will be updated\n", p.Name)
return nil
}
runF := actualRun
if cmd.Dryrun {
runF = dryRun
}
for _, p := range params {
if p.Type == ssm.ParameterTypeSecureString && p.KMSKeyID == "" {
p.KMSKeyID = cmd.DefaultKMSKeyID
}
if err := runF(p); err != nil {
return errors.Wrapf(err, "failed to update '%s'", p.Name)
}
}
return nil
}
func init() {
parser.AddCommand(
"import",
"Import parameters",
"The import command imports parameters from exported YAML file.",
&ImportCommand{},
)
}