forked from remind101/ssm-env
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
99 lines (80 loc) · 1.98 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
package main
import (
"flag"
"fmt"
"os"
"os/exec"
"strings"
"syscall"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ssm"
)
// Prefix is used to determine if an environment variable should be obtained
// from AWS Parameter Store.
const Prefix = "ssm://"
var client = ssm.New(session.New())
func main() {
var (
decrypt = flag.Bool("with-decryption", false, "Will attempt to decrypt the parameter, and set the env var as plaintext")
)
flag.Parse()
args := flag.Args()
path, err := exec.LookPath(args[0])
must(err)
must(expandEnviron(*decrypt))
must(syscall.Exec(path, args[0:], os.Environ()))
}
type ssmVar struct {
envvar string
parameter string
}
func expandEnviron(decrypt bool) error {
// Environment variables that point to some SSM parameters.
var ssmVars []ssmVar
input := &ssm.GetParametersInput{
WithDecryption: aws.Bool(decrypt),
}
for _, envvar := range os.Environ() {
k, v := splitVar(envvar)
if strings.HasPrefix(v, Prefix) {
// The name of the SSM parameter.
parameter := v[len(Prefix):]
input.Names = append(input.Names, aws.String(parameter))
ssmVars = append(ssmVars, ssmVar{k, parameter})
}
}
if len(input.Names) == 0 {
// Nothing to do, no SSM parameters.
return nil
}
resp, err := client.GetParameters(input)
if err != nil {
return err
}
if len(resp.InvalidParameters) > 0 {
var parameters []string
for _, p := range resp.InvalidParameters {
parameters = append(parameters, aws.StringValue(p))
}
return fmt.Errorf("invalid parameters: %v", parameters)
}
values := make(map[string]string)
for _, p := range resp.Parameters {
values[*p.Name] = *p.Value
}
for _, v := range ssmVars {
os.Setenv(v.envvar, values[v.parameter])
}
return nil
}
func splitVar(v string) (key, val string) {
parts := strings.Split(v, "=")
return parts[0], parts[1]
}
func must(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "ssm-env: %v\n", err)
os.Exit(1)
}
}