forked from Droplr/aws-env
-
Notifications
You must be signed in to change notification settings - Fork 0
/
aws-env.go
87 lines (69 loc) · 1.93 KB
/
aws-env.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 (
"flag"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ssm"
"log"
"os"
"strings"
)
const (
formatExports = "exports"
formatDotenv = "dotenv"
)
func main() {
if os.Getenv("AWS_ENV_PATH") == "" {
log.Println("aws-env running locally, without AWS_ENV_PATH")
return
}
recursivePtr := flag.Bool("recursive", false, "recursively process parameters on path")
format := flag.String("format", formatExports, "output format")
flag.Parse()
if *format == formatExports || *format == formatDotenv {
} else {
log.Fatal("Unsupported format option. Must be 'exports' or 'dotenv'")
}
sess := CreateSession()
client := CreateClient(sess)
ExportVariables(client, os.Getenv("AWS_ENV_PATH"), *recursivePtr, *format, "")
}
func CreateSession() *session.Session {
return session.Must(session.NewSession())
}
func CreateClient(sess *session.Session) *ssm.SSM {
return ssm.New(sess)
}
func ExportVariables(client *ssm.SSM, path string, recursive bool, format string, nextToken string) {
input := &ssm.GetParametersByPathInput{
Path: &path,
WithDecryption: aws.Bool(true),
Recursive: aws.Bool(recursive),
}
if nextToken != "" {
input.SetNextToken(nextToken)
}
output, err := client.GetParametersByPath(input)
if err != nil {
log.Panic(err)
}
for _, element := range output.Parameters {
OutputParameter(path, element, format)
}
if output.NextToken != nil {
ExportVariables(client, path, recursive, format, *output.NextToken)
}
}
func OutputParameter(path string, parameter *ssm.Parameter, format string) {
name := *parameter.Name
value := *parameter.Value
env := strings.Replace(strings.Trim(name[len(path):], "/"), "/", "_", -1)
value = strings.Replace(value, "\n", "\\n", -1)
switch format {
case formatExports:
fmt.Printf("export %s=$'%s'\n", env, value)
case formatDotenv:
fmt.Printf("%s=\"%s\"\n", env, value)
}
}