├── .gitignore ├── main_test.go ├── main.go ├── Gopkg.toml ├── .travis.yml ├── client ├── load_test.go ├── load.go └── client.go ├── Gopkg.lock ├── cmd ├── root.go └── load.go ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | bin 3 | vendor -------------------------------------------------------------------------------- /main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestMainFunc(t *testing.T) { 8 | t.Skip("SkipMain") 9 | } -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 NAME HERE 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package main 15 | 16 | import "github.com/hajimeni/aws-parameter-store-helper/cmd" 17 | 18 | func main() { 19 | cmd.Execute() 20 | } 21 | -------------------------------------------------------------------------------- /Gopkg.toml: -------------------------------------------------------------------------------- 1 | # Gopkg.toml example 2 | # 3 | # Refer to https://golang.github.io/dep/docs/Gopkg.toml.html 4 | # for detailed Gopkg.toml documentation. 5 | # 6 | # required = ["github.com/user/thing/cmd/thing"] 7 | # ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] 8 | # 9 | # [[constraint]] 10 | # name = "github.com/user/project" 11 | # version = "1.0.0" 12 | # 13 | # [[constraint]] 14 | # name = "github.com/user/project2" 15 | # branch = "dev" 16 | # source = "github.com/myfork/project2" 17 | # 18 | # [[override]] 19 | # name = "github.com/x/y" 20 | # version = "2.4.0" 21 | # 22 | # [prune] 23 | # non-go = false 24 | # go-tests = true 25 | # unused-packages = true 26 | 27 | 28 | [[constraint]] 29 | name = "github.com/aws/aws-sdk-go" 30 | version = "1.13.8" 31 | 32 | [[constraint]] 33 | name = "github.com/pkg/errors" 34 | version = "0.8.0" 35 | 36 | [[constraint]] 37 | name = "github.com/spf13/cobra" 38 | version = "0.0.1" 39 | 40 | [prune] 41 | go-tests = true 42 | unused-packages = true 43 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | go: 3 | - 1.8.3 4 | before_deploy: 5 | - ./build.sh 6 | before_install: 7 | - go get -t -v ./... 8 | script: 9 | - go test -race -coverprofile=coverage.txt -covermode=atomic 10 | deploy: 11 | provider: releases 12 | api_key: 13 | secure: SH0LQIKGGwZv72EBw8hknIiHGe/qh096BhgsqyLiWMGOrnydvSJWD4oxRC6y9p4/D8FqLnBHoUpYgZtk2uGsjOmkjUZRkIe2vwonZOQ61cqbRZr8LNON+KnZmlOO4gcoK8ajRul7Jqm6kDGPln1u37c8ODuugBsdk/AmBVoO17GASt+s1yDxR6cjFEfpQtzZECrByfJzo0GfEeuoFicpNdQPIKdFuW3Z4fgYpQ9UA7YBVCCBTYvdgjEuwFAjlReNSF8u9RkfjABBC7PXTDRt7UwqgyggWdFeMH5/zEx5BudRABBCzFGkuuGLduniQlNFO3pvDA93OxeMalNrLiMTJsD+Z1xww94HLNkEbgk1qQ9OQWeIPEJvoJcxP9WCIBH7xWfhs05Pp14qPOv7mYwr9VJMwePOmMXkHQjEazRxYGe1eczn6sq8scHQ08SGWcsOA0JJ2pJqCP2IU2Yzpp0z9iVoTVE2U1lCJ9g1aVwArkMcRH9xHJ8KMLKdUN4IekXnZVKbdSyTQFZ0YmshOPj6xz6YJ35JgU0vy9JsaXptormZpKUbRhPyhHLw9MVVguJHiK7gHAte1NJsrkptbZg3qjPhd7FxFZo+QGPg6mO8gG5c9ihnD/AqJXBsgcwXiQTLdMVljb7ECseEKzNa3Pfg+qyIuXqd6mO5ijwhXGtTjJA= 14 | file_glob: true 15 | file: "$TRAVIS_BUILD_DIR/bin/**/*.{tar.gz,zip}" 16 | on: 17 | tags: true 18 | all_branches: true 19 | repo: hajimeni/aws-parameter-store-helper 20 | after_success: 21 | - bash <(curl -s https://codecov.io/bash) -------------------------------------------------------------------------------- /client/load_test.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestRenderTemplate(t *testing.T) { 8 | t.Log("Start TestRenderTamplate") 9 | variables := []KeyValue { 10 | KeyValue{"key_1", "value_1"}, 11 | KeyValue{"path/hoge-key_2", "value\"_2"}, 12 | KeyValue{"path/hoge-key_3", `a[b+c="$\`}, 13 | } 14 | 15 | flag := LoadFlag{} 16 | flag.Template = "export {{ .Name }}=\"{{ .Value }}\"" 17 | flag.ReplaceKeyValue = "_" 18 | flag.ReplaceKeys = "-/" 19 | flag.UpperCaseKey = true 20 | flag.QuoteShell = true 21 | flag.Delimiter = ";" 22 | 23 | result1 := renderTemplate(&variables, &flag) 24 | 25 | if result1 != `export KEY_1="value_1";export PATH_HOGE_KEY_2="value\"_2";export PATH_HOGE_KEY_3="a\[b+c=\"\$\\"` { 26 | t.Fatalf("Default rendering error: %s", result1) 27 | } 28 | 29 | flag.Template = "-" 30 | result2 := renderTemplate(&variables, &flag) 31 | if result2 != "-;-;-" { 32 | t.Fatalf("Template no variables: %s", result2) 33 | } 34 | 35 | flag.Template = "export {{ .Name }}=\"{{ .Value }}\"" 36 | flag.QuoteShell = false 37 | result3 := renderTemplate(&variables, &flag) 38 | if result3 != `export KEY_1="value_1";export PATH_HOGE_KEY_2="value"_2";export PATH_HOGE_KEY_3="a[b+c="$\"` { 39 | t.Fatalf("No Unquote: %s", result3) 40 | } 41 | 42 | flag.Template = "-D{{ .Name }}={{ .Value }}" 43 | flag.Delimiter = " " 44 | flag.NoQuoteShell = true 45 | result4 := renderTemplate(&variables, &flag) 46 | if result4 != `-DKEY_1=value_1 -DPATH_HOGE_KEY_2=value"_2 -DPATH_HOGE_KEY_3=a[b+c="$\` { 47 | t.Fatalf("Java args: %s", result4) 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /client/load.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | "text/template" 7 | "log" 8 | "bytes" 9 | "strconv" 10 | "github.com/kballard/go-shellquote" 11 | ) 12 | 13 | type LoadFlag struct { 14 | Path []string 15 | Prefix []string 16 | Delimiter string 17 | Template string 18 | Region string 19 | Recursive bool 20 | UpperCaseKey bool 21 | ReplaceKeys string 22 | ReplaceKeyValue string 23 | QuoteShell bool 24 | NoQuoteShell bool 25 | } 26 | 27 | type Loader struct { 28 | Client Client 29 | } 30 | 31 | func LoadParameterStore(client Client, flag *LoadFlag) { 32 | var variables []KeyValue 33 | if len(flag.Path) > 0 { 34 | variables = append(variables, client.LoadVariablesByPaths(flag.Path, flag.Recursive)...) 35 | } 36 | if len(flag.Prefix) > 0 { 37 | variables = append(variables, client.LoadVariablesByPrefixes(flag.Prefix)...) 38 | } 39 | 40 | fmt.Print(renderTemplate(&variables, flag)) 41 | } 42 | 43 | func renderTemplate(variables *[]KeyValue, flag *LoadFlag) string { 44 | krs := []string{} 45 | for _, rv := range strings.Split(flag.ReplaceKeys, "") { 46 | krs = append(krs, rv, flag.ReplaceKeyValue) 47 | } 48 | kr := strings.NewReplacer(krs...) 49 | 50 | t, err := template.New("v").Parse(flag.Template) 51 | if err != nil { 52 | log.Fatal("Template Rendering Error", err) 53 | } 54 | values := []string{} 55 | for _, kv := range *variables { 56 | buf := &bytes.Buffer{} 57 | 58 | k := kr.Replace(kv.Key) 59 | v := kv.Value 60 | if flag.UpperCaseKey { 61 | k = strings.ToUpper(k) 62 | } 63 | if flag.QuoteShell && !flag.NoQuoteShell { 64 | v = shellquote.Join(v) 65 | } 66 | t.Execute(buf, map[string]string{"Name": k, "Value": v}) 67 | values = append(values, buf.String()) 68 | } 69 | s, err := strconv.Unquote("\"" + flag.Delimiter + "\"") 70 | if err != nil { 71 | s = flag.Delimiter 72 | } 73 | return strings.Join(values, s) 74 | } 75 | -------------------------------------------------------------------------------- /Gopkg.lock: -------------------------------------------------------------------------------- 1 | # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. 2 | 3 | 4 | [[projects]] 5 | name = "github.com/aws/aws-sdk-go" 6 | packages = [ 7 | "aws", 8 | "aws/awserr", 9 | "aws/awsutil", 10 | "aws/client", 11 | "aws/client/metadata", 12 | "aws/corehandlers", 13 | "aws/credentials", 14 | "aws/credentials/ec2rolecreds", 15 | "aws/credentials/endpointcreds", 16 | "aws/credentials/stscreds", 17 | "aws/defaults", 18 | "aws/ec2metadata", 19 | "aws/endpoints", 20 | "aws/request", 21 | "aws/session", 22 | "aws/signer/v4", 23 | "internal/sdkrand", 24 | "internal/shareddefaults", 25 | "private/protocol", 26 | "private/protocol/json/jsonutil", 27 | "private/protocol/jsonrpc", 28 | "private/protocol/query", 29 | "private/protocol/query/queryutil", 30 | "private/protocol/rest", 31 | "private/protocol/xml/xmlutil", 32 | "service/ssm", 33 | "service/sts" 34 | ] 35 | revision = "aace5875a5c3b85a3902c6d72b9caed301d64cce" 36 | version = "v1.13.8" 37 | 38 | [[projects]] 39 | name = "github.com/go-ini/ini" 40 | packages = ["."] 41 | revision = "32e4c1e6bc4e7d0d8451aa6b75200d19e37a536a" 42 | version = "v1.32.0" 43 | 44 | [[projects]] 45 | name = "github.com/inconshreveable/mousetrap" 46 | packages = ["."] 47 | revision = "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75" 48 | version = "v1.0" 49 | 50 | [[projects]] 51 | name = "github.com/jmespath/go-jmespath" 52 | packages = ["."] 53 | revision = "0b12d6b5" 54 | 55 | [[projects]] 56 | branch = "master" 57 | name = "github.com/kballard/go-shellquote" 58 | packages = ["."] 59 | revision = "95032a82bc518f77982ea72343cc1ade730072f0" 60 | 61 | [[projects]] 62 | name = "github.com/spf13/cobra" 63 | packages = ["."] 64 | revision = "7b2c5ac9fc04fc5efafb60700713d4fa609b777b" 65 | version = "v0.0.1" 66 | 67 | [[projects]] 68 | name = "github.com/spf13/pflag" 69 | packages = ["."] 70 | revision = "e57e3eeb33f795204c1ca35f56c44f83227c6e66" 71 | version = "v1.0.0" 72 | 73 | [solve-meta] 74 | analyzer-name = "dep" 75 | analyzer-version = 1 76 | inputs-digest = "4bca163f12f49dd745a71a22d89c41b5b5cd5666a7e0ecc5ca327518179bd924" 77 | solver-name = "gps-cdcl" 78 | solver-version = 1 79 | -------------------------------------------------------------------------------- /cmd/root.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 NAME HERE 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package cmd 15 | 16 | import ( 17 | "fmt" 18 | "os" 19 | 20 | //homedir "github.com/mitchellh/go-homedir" 21 | "github.com/spf13/cobra" 22 | //"github.com/spf13/viper" 23 | ) 24 | 25 | var cfgFile string 26 | 27 | // RootCmd represents the base command when called without any subcommands 28 | var RootCmd = &cobra.Command{ 29 | Use: "aws-ps [command] [option]", 30 | Short: "AWS parameter store export helper", 31 | Long: `AWS parameter store export helper: 32 | 33 | ex) 34 | $ aws-ps load -p /path/to/key 35 | > export ENV_KEY=value;ENV_KEY_2=value2 36 | 37 | usage) 38 | $ $(AWS_REGION=ap-northeast-1 aws-ps load -p /path/to/key) && run.sh 39 | then aws-ps will export environment parameters fetched from AWS Parameter Store: 40 | `, 41 | } 42 | 43 | // Execute adds all child commands to the root command and sets flags appropriately. 44 | // This is called by main.main(). It only needs to happen once to the rootCmd. 45 | func Execute() { 46 | if err := RootCmd.Execute(); err != nil { 47 | fmt.Println(err) 48 | os.Exit(1) 49 | } 50 | } 51 | 52 | func init() { 53 | cobra.OnInitialize(initConfig) 54 | 55 | // Here you will define your flags and configuration settings. 56 | // Cobra supports persistent flags, which, if defined here, 57 | // will be global for your application. 58 | // RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.aws-ssm-load-helper.yaml)") 59 | 60 | // Cobra also supports local flags, which will only run 61 | // when this action is called directly. 62 | } 63 | 64 | // initConfig reads in config file and ENV variables if set. 65 | func initConfig() { 66 | //if cfgFile != "" { 67 | // // Use config file from the flag. 68 | // viper.SetConfigFile(cfgFile) 69 | //} else { 70 | // // Find home directory. 71 | // home, err := homedir.Dir() 72 | // if err != nil { 73 | // fmt.Println(err) 74 | // os.Exit(1) 75 | // } 76 | // 77 | // // Search config in home directory with name ".aws-ssm-load-helper" (without extension). 78 | // viper.AddConfigPath(home) 79 | // viper.SetConfigName(".aws-ps") 80 | //} 81 | // 82 | //viper.AutomaticEnv() // read in environment variables that match 83 | // 84 | //// If a config file is found, read it in. 85 | //if err := viper.ReadInConfig(); err == nil { 86 | // fmt.Println("Using config file:", viper.ConfigFileUsed()) 87 | //} 88 | } 89 | -------------------------------------------------------------------------------- /cmd/load.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2017 hajimeni 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | package cmd 15 | 16 | import ( 17 | "github.com/spf13/cobra" 18 | "github.com/hajimeni/aws-parameter-store-helper/client" 19 | "os" 20 | "errors" 21 | ) 22 | 23 | // loadCmd represents the load command 24 | var loadCmd = &cobra.Command{ 25 | Use: "load", 26 | Short: "load stored parameter then export formatted string", 27 | Run: func(cmd *cobra.Command, args []string) { 28 | c, _ := client.NewClient(loadFlag.Region) 29 | client.LoadParameterStore(c, &loadFlag) 30 | }, 31 | PreRunE: func(cmd *cobra.Command, args []string) error { 32 | if (len(loadFlag.Path) == 0 && len(loadFlag.Prefix) == 0) { 33 | return errors.New("Required Path or Prefix") 34 | } 35 | return nil 36 | }, 37 | } 38 | 39 | var loadFlag client.LoadFlag 40 | 41 | func init() { 42 | RootCmd.AddCommand(loadCmd) 43 | loadCmd.SetOutput(os.Stderr) 44 | 45 | loadCmd.Flags().StringSliceVarP(&loadFlag.Path, "path", "p", []string{}, "Parameter Store Path, must starts with '/' ") 46 | loadCmd.Flags().StringSliceVar(&loadFlag.Prefix, "prefix", []string{}, "Parameter Store Prefix. export KEY is removed prefix") 47 | loadCmd.Flags().StringVarP(&loadFlag.Template, "template", "t", "export {{ .Name }}=\"{{ .Value }}\"", "export format template(Go Template)") 48 | loadCmd.Flags().StringVarP(&loadFlag.Delimiter,"delimiter", "d", ";", "Delimiter each keys") 49 | loadCmd.Flags().StringVarP(&loadFlag.Region, "region", "r", "", "AWS SDK region") 50 | loadCmd.Flags().BoolVar(&loadFlag.Recursive, "recursive",false, "Load recursive Parameter Store Path, '/' is escaped by escape-slash parameter") 51 | loadCmd.Flags().BoolVarP(&loadFlag.UpperCaseKey, "uppercase-key", "u", false, "To upper case each parameter key") 52 | loadCmd.Flags().StringVar(&loadFlag.ReplaceKeys, "replace-keys", "-/", "Replace parameter key characters to replace-key-value") 53 | loadCmd.Flags().StringVar(&loadFlag.ReplaceKeyValue, "replace-key-value", "_", "Replace parameter key each replace-keys characters to this value") 54 | loadCmd.Flags().BoolVar(&loadFlag.QuoteShell, "quote-shell", true,"Quote shell characters") 55 | loadCmd.Flags().BoolVar(&loadFlag.NoQuoteShell, "no-quote-shell", false, "No quote shell characters") 56 | // Here you will define your flags and configuration settings. 57 | 58 | // Cobra supports Persistent Flags which will work for this command 59 | // and all subcommands, e.g.: 60 | // loadCmd.PersistentFlags().String("foo", "", "A help for foo") 61 | 62 | // Cobra supports local flags which will only run when this command 63 | // is called directly, e.g.: 64 | // loadCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") 65 | } 66 | -------------------------------------------------------------------------------- /client/client.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "github.com/aws/aws-sdk-go/aws" 5 | "github.com/aws/aws-sdk-go/service/ssm" 6 | "github.com/aws/aws-sdk-go/aws/session" 7 | "log" 8 | "os" 9 | "strings" 10 | ) 11 | 12 | type KeyValue struct { 13 | Key string 14 | Value string 15 | } 16 | 17 | func newKeyValue(key string, value string) KeyValue { 18 | return KeyValue{ 19 | key, 20 | value, 21 | } 22 | } 23 | 24 | type Client interface { 25 | LoadVariablesByPaths(paths []string, recursive bool) []KeyValue 26 | LoadVariablesByPrefixes(prefixes []string) []KeyValue 27 | } 28 | 29 | 30 | type AwsSsmClient struct { 31 | client *ssm.SSM 32 | } 33 | 34 | type stdErrLogger struct { 35 | logger *log.Logger 36 | } 37 | 38 | func newStdErrLogger() aws.Logger { 39 | return &stdErrLogger{ 40 | logger: log.New(os.Stderr, "", log.LstdFlags), 41 | } 42 | } 43 | 44 | func (l stdErrLogger) Log(args ...interface{}) { 45 | l.logger.Println(args...) 46 | } 47 | 48 | func NewClient(region string) (Client, error) { 49 | log.SetOutput(os.Stderr) 50 | 51 | sess := session.Must(session.NewSession()) 52 | logLevel := sess.Config.LogLevel 53 | if os.Getenv("DEBUG") != "" { 54 | logLevel = aws.LogLevel(aws.LogDebug) 55 | } 56 | if os.Getenv("DEBUG_SIGNING") != "" { 57 | logLevel = aws.LogLevel(aws.LogDebugWithSigning) 58 | } 59 | if os.Getenv("DEBUG_BODY") != "" { 60 | logLevel = aws.LogLevel(aws.LogDebugWithSigning | aws.LogDebugWithHTTPBody) 61 | } 62 | 63 | config := aws.NewConfig().WithLogger(newStdErrLogger()).WithLogLevel(*logLevel) 64 | if region != "" { 65 | config = config.WithRegion(region) 66 | } 67 | c := AwsSsmClient{ 68 | ssm.New(sess, config), 69 | } 70 | 71 | return c, nil 72 | } 73 | 74 | func (c AwsSsmClient) LoadVariablesByPaths(paths []string, recursive bool) []KeyValue { 75 | res := []KeyValue{} 76 | for _, path := range paths { 77 | r := c.loadVariablesByPath(path, recursive, []KeyValue{}, nil) 78 | res = append(res, r...) 79 | } 80 | return res 81 | } 82 | 83 | func (c AwsSsmClient) loadVariablesByPath(path string, recursive bool, acc []KeyValue, nextToken *string) []KeyValue { 84 | input := &ssm.GetParametersByPathInput{ 85 | Path: aws.String(path), 86 | WithDecryption: aws.Bool(true), 87 | Recursive: aws.Bool(recursive), 88 | } 89 | 90 | if nextToken != nil { 91 | input.SetNextToken(*nextToken) 92 | } 93 | output, err := c.client.GetParametersByPath(input) 94 | 95 | if err != nil { 96 | log.Fatal("GetParametersByPath Error:\n", err) 97 | } 98 | for _, element := range output.Parameters { 99 | name := *element.Name 100 | key := strings.Trim(strings.Replace(name, path, "", 1), "/") 101 | acc = append(acc, newKeyValue(key, *element.Value)) 102 | } 103 | 104 | if output.NextToken == nil { 105 | return acc 106 | } else { 107 | return c.loadVariablesByPath(path, recursive, acc, output.NextToken) 108 | } 109 | } 110 | 111 | func (c AwsSsmClient) LoadVariablesByPrefixes(prefixes []string) []KeyValue { 112 | res := []KeyValue{} 113 | for _, prefix := range prefixes { 114 | r := c.loadVariables(prefix, res, nil) 115 | res = append(res, r...) 116 | } 117 | return res 118 | } 119 | 120 | func (c AwsSsmClient) loadVariables(prefix string, acc []KeyValue, nextToken *string) []KeyValue { 121 | input := &ssm.DescribeParametersInput{ 122 | MaxResults: aws.Int64(10), 123 | } 124 | if nextToken != nil { 125 | input.SetNextToken(*nextToken) 126 | } 127 | output, err := c.client.DescribeParameters(input) 128 | 129 | if err != nil { 130 | log.Fatal("DescribeParameters Error", err) 131 | } 132 | names := []*string{} 133 | for _, v := range output.Parameters { 134 | names = append(names, v.Name) 135 | } 136 | pintput := &ssm.GetParametersInput{ 137 | Names: names, 138 | WithDecryption: aws.Bool(true), 139 | } 140 | poutput, err := c.client.GetParameters(pintput) 141 | if err != nil { 142 | log.Fatal("GetParameters Error", err) 143 | } 144 | for _, element := range poutput.Parameters { 145 | name := *element.Name 146 | if strings.Index(name, prefix) == 0 { 147 | key := strings.Replace(name, prefix, "",1) 148 | acc = append(acc, newKeyValue(key, *element.Value)) 149 | } 150 | } 151 | 152 | if output.NextToken == nil { 153 | return acc 154 | } else { 155 | return c.loadVariables(prefix, acc, output.NextToken) 156 | } 157 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | aws-parameter-store-helper 2 | ---------------- 3 | [![Build Status](https://travis-ci.org/hajimeni/aws-parameter-store-helper.svg?branch=master)](https://travis-ci.org/hajimeni/aws-parameter-store-helper) 4 | 5 | ## Latest version 6 | 7 | - `v0.4.0` 8 | - [![Build Status](https://travis-ci.org/hajimeni/aws-parameter-store-helper.svg?branch=v0.4.0)](https://travis-ci.org/hajimeni/aws-parameter-store-helper) 9 | - [Download(for mac OS X)](https://github.com/hajimeni/aws-parameter-store-helper/releases/download/v0.4.0/aws-ps-darwin-amd64.tar.gz) 10 | - [Download(for Linux)](https://github.com/hajimeni/aws-parameter-store-helper/releases/download/v0.4.0/aws-ps-linux-amd64.tar.gz) 11 | 12 | ## Usage 13 | 14 | 1. Add parameter to [Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-paramstore.html) using hierarchy in names: 15 | ``` 16 | $ aws ssm put-parameter --name /path/to/key/ENV_KEY_1 --value "value1" --type SecureString --key-id "alias/aws/ssm" --region ap-northeast-1 17 | $ aws ssm put-parameter --name /path/to/key/ENV_KEY_2 --value "value2" --type SecureString --key-id "alias/aws/ssm" --region ap-northeast-1 18 | ``` 19 | 20 | 2. Go to the [Releases Page](https://github.com/hajimeni/aws-parameter-store-helper/releases) and download the binary for your OS. 21 | ``` 22 | $ wget https://github.com/hajimeni/aws-parameter-store-helper/releases/download/v0.4.0/aws-parameter-store-helper-linux-amd64.tar.gz 23 | $ tar xfz aws-parameter-store-helper-linux-amd64.tar.gz 24 | $ chmod +x aws-ps 25 | ``` 26 | 27 | 3. Start your application with aws-ps 28 | ``` 29 | $(aws-ps load -p /path/to/key -r ap-norhteast-1) && run.sh 30 | ``` 31 | or 32 | ``` 33 | eval $(aws-ps load -p /path/to/key -r ap-northeast-1) 34 | ./run.sh 35 | ``` 36 | 37 | ## Example Dockerfile 38 | 39 | - run.sh 40 | ``` 41 | #!/bin/sh 42 | env 43 | 44 | echo "OK" 45 | ``` 46 | - Dockerfile 47 | ``` 48 | FROM amazonlinux:2017.09 49 | 50 | RUN yum -y install wget tar 51 | 52 | ADD run.sh /run.sh 53 | 54 | RUN chmod +x /run.sh 55 | 56 | RUN wget https://github.com/hajimeni/aws-parameter-store-helper/releases/download/v0.4.0/aws-parameter-store-helper-linux-amd64.tar.gz \ 57 | && tar xfz aws-parameter-store-helper-linux-amd64.tar.gz \ 58 | && chmod +x aws-ps 59 | 60 | CMD $(aws-ps load -p $AWS_PS_PATH -r $AWS_REGION) && run.sh 61 | ``` 62 | - build and run 63 | ``` 64 | docker build -t app . 65 | docker run -e AWS_ACCESSK_KEY_ID=xxxx -e AWS_SECRET_ACCESS_KEY=yyyy -e AWS_PS_PATH=/path/to/key -e $AWS_REGION=ap-northeast-1 app 66 | ``` 67 | - then you can watch environment values such as below 68 | ``` 69 | ... 70 | ENV_KEY_1=value1 71 | ENV_KEY_2=value2 72 | ... 73 | OK 74 | ``` 75 | 76 | ## Commands 77 | 78 | - load 79 | load aws ssm parameter stored values 80 | - help 81 | help command 82 | 83 | ``` 84 | $ aws-ps help 85 | AWS parameter store export helper: 86 | 87 | ex) 88 | $ aws-ps load -p /path/to/key 89 | > export ENV_KEY=value;ENV_KEY_2=valu2 90 | 91 | usage) 92 | $ eval $(AWS_REGION=ap-northeast-1 aws-ps load -p /path/to/key) 93 | then aws-pws will export environment parameters fetched from AWS Parameter Store: 94 | 95 | Usage: 96 | aws-ps [command] 97 | 98 | Available Commands: 99 | help Help about any command 100 | load load stored parameter then export formatted string 101 | 102 | Flags: 103 | -h, --help help for aws-ps 104 | 105 | Use "aws-ps [command] --help" for more information about a command. 106 | ``` 107 | 108 | ### `load` command Options 109 | 110 | ``` 111 | $ aws-ps load --help 112 | load stored parameter then export formatted string 113 | 114 | Usage: 115 | aws-ps load [flags] 116 | 117 | Flags: 118 | -d, --delimiter string Delimiter each keys (default ";") 119 | -h, --help help for load 120 | --no-quote-shell No quote shell characters 121 | -p, --path stringSlice Parameter Store Path, must starts with '/' 122 | --prefix stringSlice Parameter Store Prefix. export KEY is removed prefix 123 | --quote-shell Quote shell characters (default true) 124 | --recursive Load recursive Parameter Store Path, '/' is escaped by escape-slash parameter 125 | -r, --region string AWS SDK region 126 | --replace-key-value string Replace parameter key each replace-keys characters to this value (default "_") 127 | --replace-keys string Replace parameter key characters to replace-key-value (default "-/") 128 | -t, --template string export format template(Go Template) (default "export {{ .Name }}=\"{{ .Value }}\"") 129 | -u, --uppercase-key To upper case each parameter key 130 | ``` 131 | 132 | #### `-d` delimiter 133 | 134 | ex) 135 | ``` 136 | $ aws-ps load -p /path/to/key -d ':' 137 | export KEY_1=value1:export KEY_2=value2 138 | ``` 139 | 140 | #### `-t` template 141 | 142 | ex) 143 | ``` 144 | $ aws-ps load -p /path/to/key -t '-D{{ .Name }}={{ .Value }}' -d ' ' 145 | -DKEY_1=value1 -DKEY_2=value2 146 | ``` 147 | 148 | #### `-p` path (multiple) 149 | 150 | starts with `/` 151 | 152 | ex) 153 | ``` 154 | # paramete store 155 | /path/to/key/KEY_1 -> value1 156 | /path/to/key/KEY_2 -> value2 157 | /path/to/hoge/KEY_3 -> value3 158 | /path/to/hoge/KEY_4 -> value4 159 | /path/to/hoge/KEY_1 -> value5 160 | 161 | $ aws-ps load -p /path/to/key 162 | export KEY_1=value1;export KEY_2=value2 163 | 164 | # multiple path 165 | $ aws-ps load -p /path/to/key -p /path/to/hoge 166 | export KEY_1=value5;export KEY_2=value2;export KEY_3=value3;export KEY_4=value4 167 | 168 | ``` 169 | 170 | #### `--prefix` prefix (multiple) 171 | 172 | `aws-ps` exports removed prefix keys. 173 | 174 | ex) 175 | ``` 176 | # paramete store 177 | path.to.key.KEY_1 -> value1 178 | path.to.key.KEY_2 -> value2 179 | 180 | $ aws-ps load --prefix path.to.key. 181 | export KEY_1=value1;export KEY_2=value2 182 | ``` 183 | 184 | #### `-u` uppercase-key 185 | 186 | To upper case each parameter keys 187 | 188 | ex) 189 | ``` 190 | # paramete store 191 | path.to.key.key_1 -> value1 192 | path.to.key.KEY_2 -> value2 193 | 194 | $ aws-ps load --prefix path.to.key. -u 195 | export KEY_1=value1;export KEY_2=value2 196 | ``` 197 | 198 | #### `--recursive` recursive 199 | 200 | load parameter store recursive by path 201 | use with `--path` parameter 202 | 203 | ex) 204 | ``` 205 | # paramete store 206 | /path/to/key/KEY_1 -> value1 207 | /path/to/key/recursive/KEY_2 -> value2 208 | 209 | # recurisve 210 | $ aws-ps load -p /path/to/key --recursive 211 | export KEY_1=value1;export recursive_KEY_2=value2 212 | 213 | # no-recursive(default) 214 | $ aws-ps load -p /path/to/key 215 | export KEY_1=value1 216 | 217 | ``` 218 | 219 | #### `--quote-shell` (default=true) `--no-quote-shell` (default=false) 220 | 221 | quote variable shell specific characters. 222 | 223 | ex) 224 | ``` 225 | # paramete store 226 | /path/to/key/KEY_1 -> value1 227 | /path/to/key/KEY_2 -> a[b+c="$\ 228 | 229 | ## --quote-shell 230 | $ aws-ps load -p /path/to/key 231 | export KEY1="value1";export KEY2="a\[b+c=\"\$\\" 232 | 233 | ## --no-quote-shell 234 | $ aws-ps load -p /path/to/key --no-quote-shell 235 | export KEY1="value1";export KEY2="a[b+c="$\" 236 | ``` 237 | 238 | ## How to build 239 | 240 | 1. Clone this repository 241 | 1. `go get -u github.com/golang/dep/cmd/dep` 242 | 1. `dep ensure` 243 | 1. run `./build.sh` 244 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | --------------------------------------------------------------------------------