├── .editorconfig ├── .github └── workflows │ ├── go.yml │ └── golangci-lint.yml ├── .golangci.yml ├── LICENSE ├── README.md ├── catalog-info.yaml ├── go.mod ├── go.sum ├── parameter.go ├── parameter_store_client.go ├── parameter_store_client_test.go └── parameter_test.go /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | trim_trailing_whitespace = true 6 | end_of_line = lf 7 | insert_final_newline = true 8 | 9 | [*.{yml,yaml}] 10 | indent_style = space 11 | indent_size = 2 12 | 13 | [*.{markdown,md}] 14 | trim_trailing_whitespace = false -------------------------------------------------------------------------------- /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: go 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v4 10 | - name: Set up Go 11 | uses: actions/setup-go@v4 12 | with: 13 | go-version: '^1.21' 14 | 15 | - name: Install dependencies 16 | run: go mod download 17 | 18 | - name: Build 19 | run: go build -v ./... 20 | 21 | - name: Test 22 | run: go test ./... -v -coverprofile coverage.txt -covermode atomic -coverpkg ./... -race 23 | 24 | - name: Upload coverage to Codecov 25 | uses: codecov/codecov-action@v3 26 | -------------------------------------------------------------------------------- /.github/workflows/golangci-lint.yml: -------------------------------------------------------------------------------- 1 | name: golangci-lint 2 | 3 | on: [push] 4 | 5 | permissions: 6 | contents: read 7 | 8 | jobs: 9 | golangci: 10 | name: lint 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v4 14 | - uses: actions/setup-go@v4 15 | with: 16 | go-version: '^1.21' 17 | 18 | - name: golangci-lint 19 | uses: golangci/golangci-lint-action@v3 20 | with: 21 | version: v1.54 22 | -------------------------------------------------------------------------------- /.golangci.yml: -------------------------------------------------------------------------------- 1 | run: 2 | tests: false 3 | issues: 4 | exclude-use-default: false 5 | 6 | linters: 7 | disable-all: true 8 | enable: 9 | - govet 10 | - errcheck 11 | - staticcheck 12 | - unused 13 | - gosimple 14 | - structcheck 15 | - varcheck 16 | - ineffassign 17 | - deadcode 18 | - typecheck 19 | - gosec 20 | - gocyclo 21 | - gofmt 22 | - golint -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![codecov](https://codecov.io/gh/PaddleHQ/go-aws-ssm/branch/master/graph/badge.svg)](https://codecov.io/gh/PaddleHQ/go-aws-ssm) 2 | [![Go Report Card](https://goreportcard.com/badge/github.com/PaddleHQ/go-aws-ssm)](https://goreportcard.com/report/github.com/PaddleHQ/go-aws-ssm) 3 | [![GoDoc](https://godoc.org/github.com/PaddleHQ/go-aws-ssm?status.svg)](https://pkg.go.dev/github.com/PaddleHQ/go-aws-ssm) 4 | 5 | # go-aws-ssm 6 | Go package that interfaces with [AWS System Manager](https://www.amazonaws.cn/en/systems-manager/). 7 | 8 | ## Why to use go-aws-ssm and not the aws-sdk-go? 9 | This package is wrapping the aws-sdk-go and hides the complexity dealing with the not so Go friendly AWS SDK. 10 | Perfect use case for this package is when secure parameters for an application are stored to 11 | [AWS Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html) 12 | using a path hierarchy. During application startup you can use this package to fetch them and use them in your application. 13 | 14 | ## Install 15 | 16 | ```bash 17 | go get github.com/PaddleHQ/go-aws-ssm 18 | ``` 19 | 20 | ## Examples 21 | 22 | #### Basic Usage 23 | 24 | ```go 25 | //Assuming you have the parameters in the following format: 26 | //my-service/dev/param-1 -> with value `a` 27 | //my-service/dev/param-2 -> with value `b` 28 | pmstore, err := awsssm.NewParameterStore() 29 | if err != nil { 30 | return err 31 | } 32 | //Requesting the base path 33 | params, err := pmstore.GetAllParametersByPath("/my-service/dev/", true) 34 | if err!=nil{ 35 | return err 36 | } 37 | 38 | //And getting a specific value 39 | value:=params.GetValueByName("param-1") 40 | //value should be `a` 41 | 42 | 43 | ``` 44 | 45 | #### Integrates easily with [viper](https://github.com/spf13/viper) 46 | ```go 47 | //Assuming you have the parameters in the following format: 48 | //my-service/dev/param-1 -> with value `a` 49 | //my-service/dev/param-2 -> with value `b` 50 | pmstore, err := awsssm.NewParameterStore() 51 | if err != nil { 52 | return err 53 | } 54 | //Requesting the base path 55 | params, err := pmstore.GetAllParametersByPath("/my-service/dev/", true) 56 | if err!=nil{ 57 | return err 58 | } 59 | 60 | //Configure viper to handle it as json document, nothing special here! 61 | v := viper.New() 62 | v.SetConfigType(`json`) 63 | //params object implements the io.Reader interface that is required 64 | err = v.ReadConfig(params) 65 | if err != nil { 66 | return err 67 | } 68 | value := v.Get(`param-1`) 69 | //value should be `a` 70 | ``` 71 | -------------------------------------------------------------------------------- /catalog-info.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: backstage.io/v1alpha1 2 | kind: Component 3 | metadata: 4 | name: go-aws-ssm 5 | namespace: paddlehq 6 | description: Go package that interfaces with AWS System Manager. 7 | annotations: 8 | backstage.io/techdocs-ref: dir:. 9 | github.com/project-slug: PaddleHQ/go-aws-ssm 10 | tags: 11 | - go 12 | spec: 13 | type: library 14 | owner: engineering 15 | lifecycle: production 16 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/PaddleHQ/go-aws-ssm 2 | 3 | go 1.21 4 | 5 | require ( 6 | github.com/aws/aws-sdk-go v1.48.15 7 | github.com/mitchellh/mapstructure v1.5.0 8 | ) 9 | 10 | require ( 11 | github.com/davecgh/go-spew v1.1.1 // indirect 12 | github.com/jmespath/go-jmespath v0.4.0 // indirect 13 | ) 14 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/aws/aws-sdk-go v1.48.15 h1:Gad2C4pLzuZDd5CA0Rvkfko6qUDDTOYru145gkO7w/Y= 2 | github.com/aws/aws-sdk-go v1.48.15/go.mod h1:LF8svs817+Nz+DmiMQKTO3ubZ/6IaTpq3TjupRn3Eqk= 3 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 4 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 5 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 6 | github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= 7 | github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= 8 | github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= 9 | github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= 10 | github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= 11 | github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= 12 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 13 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 14 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 15 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 16 | gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= 17 | gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 18 | -------------------------------------------------------------------------------- /parameter.go: -------------------------------------------------------------------------------- 1 | package awsssm 2 | 3 | import ( 4 | "encoding/json" 5 | "io" 6 | "strings" 7 | 8 | "github.com/mitchellh/mapstructure" 9 | ) 10 | 11 | // Parameter holds a Systems Manager parameter from AWS Parameter Store 12 | type Parameter struct { 13 | Value *string 14 | } 15 | 16 | // GetValue return the actual Value of the parameter 17 | func (p *Parameter) GetValue() string { 18 | if p.Value == nil { 19 | return "" 20 | } 21 | return *p.Value 22 | } 23 | 24 | // NewParameters creates a Parameters 25 | func NewParameters(basePath string, parameters map[string]*Parameter) *Parameters { 26 | return &Parameters{ 27 | basePath: basePath, 28 | parameters: parameters, 29 | } 30 | } 31 | 32 | // Parameters holds the output and all AWS Parameter Store that have the same base path 33 | type Parameters struct { 34 | readIndex int64 35 | bytesJSON []byte 36 | basePath string 37 | parameters map[string]*Parameter 38 | } 39 | 40 | // Read implements the io.Reader interface for the key/value pair 41 | func (p *Parameters) Read(des []byte) (n int, err error) { 42 | if p.bytesJSON == nil { 43 | p.bytesJSON, err = json.Marshal(p.getKeyValueMap()) 44 | if err != nil { 45 | return 0, err 46 | } 47 | } 48 | 49 | if p.readIndex >= int64(len(p.bytesJSON)) { 50 | p.readIndex = 0 51 | return 0, io.EOF 52 | } 53 | 54 | n = copy(des, p.bytesJSON[p.readIndex:]) 55 | p.readIndex += int64(n) 56 | 57 | return n, nil 58 | } 59 | 60 | // GetValueByName returns the value based on the name 61 | // so the AWS Parameter Store parameter name is base path + name 62 | func (p *Parameters) GetValueByName(name string) string { 63 | parameter, ok := p.parameters[p.basePath+name] 64 | if !ok { 65 | return "" 66 | } 67 | return parameter.GetValue() 68 | } 69 | 70 | // GetValueByFullPath returns the value based on the full path 71 | func (p *Parameters) GetValueByFullPath(name string) string { 72 | parameter, ok := p.parameters[name] 73 | if !ok { 74 | return "" 75 | } 76 | return parameter.GetValue() 77 | } 78 | 79 | // Decode decodes the parameters into the given struct 80 | // We are using this package to decode the values to the struct https://github.com/mitchellh/mapstructure 81 | // For more details how you can use this check the parameter_test.go file 82 | func (p *Parameters) Decode(output interface{}) error { 83 | return mapstructure.Decode(p.getKeyValueMap(), output) 84 | } 85 | 86 | func (p *Parameters) getKeyValueMap() map[string]string { 87 | keyValue := make(map[string]string, len(p.parameters)) 88 | for k, v := range p.parameters { 89 | keyValue[strings.Replace(k, p.basePath, "", 1)] = v.GetValue() 90 | } 91 | return keyValue 92 | } 93 | 94 | // GetAllValues returns a map with all the keys and values in the store. 95 | func (p *Parameters) GetAllValues() map[string]string { 96 | return p.getKeyValueMap() 97 | } 98 | -------------------------------------------------------------------------------- /parameter_store_client.go: -------------------------------------------------------------------------------- 1 | package awsssm 2 | 3 | import ( 4 | "errors" 5 | 6 | "github.com/aws/aws-sdk-go/aws" 7 | "github.com/aws/aws-sdk-go/aws/awserr" 8 | "github.com/aws/aws-sdk-go/aws/session" 9 | "github.com/aws/aws-sdk-go/service/ssm" 10 | ) 11 | 12 | var ( 13 | //ErrParameterNotFound error for when the requested Parameter Store parameter can't be found 14 | ErrParameterNotFound = errors.New("parameter not found") 15 | //ErrParameterInvalidName error for invalid parameter name 16 | ErrParameterInvalidName = errors.New("invalid parameter name") 17 | ) 18 | 19 | type ssmClient interface { 20 | GetParametersByPathPages(input *ssm.GetParametersByPathInput, fn func(*ssm.GetParametersByPathOutput, bool) bool) error 21 | GetParameter(input *ssm.GetParameterInput) (*ssm.GetParameterOutput, error) 22 | PutParameter(input *ssm.PutParameterInput) (*ssm.PutParameterOutput, error) 23 | } 24 | 25 | // ParameterStore holds all the methods tha are supported against AWS Parameter Store 26 | type ParameterStore struct { 27 | ssm ssmClient 28 | } 29 | 30 | // GetAllParametersByPath is returning all the Parameters that are hierarchy linked to this path 31 | // For example a request with path as /my-service/dev/ 32 | // Will return /my-service/dev/param-a, /my-service/dev/param-b, etc... but will not return recursive paths 33 | // the `ssm:GetAllParametersByPath` permission is required 34 | // to the `arn:aws:ssm:aws-region:aws-account-id:/my-service/dev/*` 35 | // 36 | // This will also page through and return all elements in the hierarchy, non-recursively 37 | func (ps *ParameterStore) GetAllParametersByPath(path string, decrypt bool) (*Parameters, error) { 38 | var input = &ssm.GetParametersByPathInput{} 39 | input.SetWithDecryption(decrypt) 40 | input.SetPath(path) 41 | input.SetMaxResults(10) 42 | return ps.getParameters(input) 43 | } 44 | 45 | func (ps *ParameterStore) getParameters(input *ssm.GetParametersByPathInput) (*Parameters, error) { 46 | parameters := NewParameters(*input.Path, make(map[string]*Parameter)) 47 | if err := ps.ssm.GetParametersByPathPages(input, func(result *ssm.GetParametersByPathOutput, b bool) bool { 48 | for _, v := range result.Parameters { 49 | if v.Name == nil { 50 | continue 51 | } 52 | parameters.parameters[*v.Name] = &Parameter{Value: v.Value} 53 | } 54 | return !b 55 | }); err != nil { 56 | return nil, err 57 | } 58 | return parameters, nil 59 | } 60 | 61 | // GetParameter is returning the parameter with the given name 62 | // For example a request with name as /my-service/dev/param-1 63 | // Will return the parameter value if exists or ErrParameterInvalidName if parameter cannot be found 64 | // The `ssm:GetParameter` permission is required 65 | // to the `arn:aws:ssm:aws-region:aws-account-id:/my-service/dev/param-1` resource 66 | func (ps *ParameterStore) GetParameter(name string, decrypted bool) (*Parameter, error) { 67 | if name == "" { 68 | return nil, ErrParameterInvalidName 69 | } 70 | input := &ssm.GetParameterInput{} 71 | input.SetName(name) 72 | input.SetWithDecryption(decrypted) 73 | return ps.getParameter(input) 74 | } 75 | func (ps *ParameterStore) getParameter(input *ssm.GetParameterInput) (*Parameter, error) { 76 | result, err := ps.ssm.GetParameter(input) 77 | if err != nil { 78 | if awsError, ok := err.(awserr.Error); ok && awsError.Code() == ssm.ErrCodeParameterNotFound { 79 | return nil, ErrParameterNotFound 80 | } 81 | return nil, err 82 | } 83 | return &Parameter{ 84 | Value: result.Parameter.Value, 85 | }, nil 86 | } 87 | 88 | // PutSecureParameter is setting the parameter with the given name to a passed in value. 89 | // Allow overwriting the value of the parameter already exists, otherwise an error is returned 90 | // For example a request with name as '/my-service/dev/param-1': 91 | // Will set the parameter value if exists or ErrParameterInvalidName if parameter already exists or is empty 92 | // and `overwrite` is false. The `ssm:PutParameter` permission is required to the 93 | // `arn:aws:ssm:aws-region:aws-account-id:/my-service/dev/param-1` resource 94 | func (ps *ParameterStore) PutSecureParameter(name, value string, overwrite bool) error { 95 | return ps.putSecureParameterWrapper(name, value, "", overwrite) 96 | } 97 | 98 | // PutSecureParameterWithCMK is the same as PutSecureParameter but with a passed in CMK (Customer Master Key) 99 | // For example a request with name as '/my-service/dev/param-1' and a `kmsID` of 'foo': 100 | // Will set the parameter value if exists or ErrParameterInvalidName if parameter already exists or is empty 101 | // and `overwrite` is false. The `ssm:PutParameter` permission is required to the 102 | // `arn:aws:ssm:aws-region:aws-account-id:/my-service/dev/param-1` resource 103 | // The `kms:Encrypt` permission is required to the `arn:aws:kms:us-east-1:710015040892:key/foo` 104 | func (ps *ParameterStore) PutSecureParameterWithCMK(name, value string, overwrite bool, kmsID string) error { 105 | return ps.putSecureParameterWrapper(name, value, kmsID, overwrite) 106 | } 107 | func (ps *ParameterStore) putSecureParameterWrapper(name, value, kmsID string, overwrite bool) error { 108 | if name == "" { 109 | return ErrParameterInvalidName 110 | } 111 | input := &ssm.PutParameterInput{} 112 | input.SetName(name) 113 | input.SetType("SecureString") 114 | input.SetValue(value) 115 | if kmsID != "" { 116 | input.SetKeyId(kmsID) 117 | } 118 | input.SetOverwrite(overwrite) 119 | 120 | if err := input.Validate(); err != nil { 121 | return err 122 | } 123 | 124 | return ps.putParameter(input) 125 | } 126 | func (ps *ParameterStore) putParameter(input *ssm.PutParameterInput) error { 127 | _, err := ps.ssm.PutParameter(input) 128 | if err != nil { 129 | if awsError, ok := err.(awserr.Error); ok && awsError.Code() == ssm.ErrCodeParameterAlreadyExists { 130 | return ErrParameterInvalidName 131 | } 132 | return err 133 | } 134 | return nil 135 | } 136 | 137 | // NewParameterStoreWithClient is creating a new ParameterStore with the given ssm Client 138 | func NewParameterStoreWithClient(client ssmClient) *ParameterStore { 139 | return &ParameterStore{ssm: client} 140 | } 141 | 142 | // NewParameterStore is creating a new ParameterStore by creating an AWS Session 143 | func NewParameterStore(ssmConfig ...*aws.Config) (*ParameterStore, error) { 144 | sessionAWS, err := session.NewSession(ssmConfig...) 145 | if err != nil { 146 | return nil, err 147 | } 148 | svc := ssm.New(sessionAWS) 149 | return &ParameterStore{ssm: svc}, nil 150 | } 151 | -------------------------------------------------------------------------------- /parameter_store_client_test.go: -------------------------------------------------------------------------------- 1 | package awsssm 2 | 3 | import ( 4 | "errors" 5 | "reflect" 6 | "testing" 7 | 8 | "github.com/aws/aws-sdk-go/aws/awserr" 9 | "github.com/aws/aws-sdk-go/service/ssm" 10 | ) 11 | 12 | var param1 = new(ssm.Parameter). 13 | SetName("/my-service/dev/DB_PASSWORD"). 14 | SetValue("something-secure"). 15 | SetARN("arn:aws:ssm:us-east-2:aws-account-id:/my-service/dev/DB_PASSWORD") 16 | 17 | var param2 = new(ssm.Parameter). 18 | SetName("/my-service/dev/DB_HOST"). 19 | SetValue("rds.something.aws.com"). 20 | SetARN("arn:aws:ssm:us-east-2:aws-account-id:/my-service/dev/DB_HOST") 21 | 22 | // return s.GetParametersByPathOutput, s.GetParametersByPathError 23 | var param3 = new(ssm.Parameter). 24 | SetName("/my-service/dev/DB_USERNAME"). 25 | SetValue("username"). 26 | SetARN("arn:aws:ssm:us-east-2:aws-account-id:/my-service/dev/DB_USERNAME") 27 | 28 | var errSSM = errors.New("ssm request error") 29 | 30 | type stubGetParametersByPathOutput struct { 31 | Output ssm.GetParametersByPathOutput 32 | MoreParamsLeft bool 33 | } 34 | 35 | type stubSSMClient struct { 36 | GetParametersByPathOutput []stubGetParametersByPathOutput 37 | GetParametersByPathError error 38 | GetParameterOutput *ssm.GetParameterOutput 39 | GetParameterError error 40 | PutParameterInputReceived *ssm.PutParameterInput 41 | } 42 | 43 | func (s *stubSSMClient) GetParametersByPathPages(input *ssm.GetParametersByPathInput, fn func(*ssm.GetParametersByPathOutput, bool) bool) error { 44 | if s.GetParametersByPathError == nil { 45 | for _, output := range s.GetParametersByPathOutput { 46 | done := fn(&output.Output, output.MoreParamsLeft) 47 | if done { 48 | return nil 49 | } 50 | } 51 | } 52 | return s.GetParametersByPathError 53 | } 54 | 55 | func (s *stubSSMClient) GetParameter(input *ssm.GetParameterInput) (*ssm.GetParameterOutput, error) { 56 | return s.GetParameterOutput, s.GetParameterError 57 | } 58 | 59 | // we return nothing becuase the actual response is pretty boring. Just a version number. We DO 60 | // want to track was is input because there is a _little_ business logic around that 61 | func (s *stubSSMClient) PutParameter(input *ssm.PutParameterInput) (*ssm.PutParameterOutput, error) { 62 | s.PutParameterInputReceived = input 63 | return nil, nil 64 | } 65 | 66 | func TestClient_GetParametersByPath(t *testing.T) { 67 | tests := []struct { 68 | name string 69 | ssmClient ssmClient 70 | path string 71 | expectedError error 72 | expectedOutput *Parameters 73 | }{ 74 | { 75 | name: "Success", 76 | ssmClient: &stubSSMClient{ 77 | GetParametersByPathOutput: []stubGetParametersByPathOutput{ 78 | { 79 | MoreParamsLeft: true, 80 | Output: ssm.GetParametersByPathOutput{ 81 | Parameters: getParameters(), 82 | }, 83 | }, 84 | { 85 | MoreParamsLeft: true, 86 | Output: ssm.GetParametersByPathOutput{ 87 | Parameters: getParameters2(), 88 | }, 89 | }, 90 | { 91 | MoreParamsLeft: false, 92 | Output: ssm.GetParametersByPathOutput{ 93 | Parameters: []*ssm.Parameter{ 94 | param3, 95 | }, 96 | }, 97 | }, 98 | }, 99 | }, 100 | path: "/my-service/dev/", 101 | expectedOutput: &Parameters{ 102 | basePath: "/my-service/dev/", 103 | parameters: map[string]*Parameter{ 104 | "/my-service/dev/DB_PASSWORD": {Value: param1.Value}, 105 | "/my-service/dev/DB_HOST": {Value: param2.Value}, 106 | "/my-service/dev/DB_USERNAME": {Value: param3.Value}, 107 | }, 108 | }, 109 | }, 110 | 111 | { 112 | name: "Failed SSM Request Error", 113 | ssmClient: &stubSSMClient{ 114 | GetParametersByPathError: errSSM, 115 | }, 116 | path: "/my-service/dev/", 117 | expectedError: errSSM, 118 | }, 119 | } 120 | for _, test := range tests { 121 | t.Run(test.name, func(t *testing.T) { 122 | 123 | client := NewParameterStoreWithClient(test.ssmClient) 124 | parameters, err := client.GetAllParametersByPath(test.path, true) 125 | if err != test.expectedError { 126 | t.Errorf(`Unexpected error: got %d, expected %d`, err, test.expectedError) 127 | } 128 | if !reflect.DeepEqual(parameters, test.expectedOutput) { 129 | t.Errorf(`Unexpected parameters: got: %+v, expected: %+v`, *parameters, *test.expectedOutput) 130 | } 131 | }) 132 | } 133 | } 134 | 135 | func getParameters() []*ssm.Parameter { 136 | return []*ssm.Parameter{ 137 | param1, param2, 138 | } 139 | } 140 | 141 | func getParameters2() []*ssm.Parameter { 142 | return []*ssm.Parameter{ 143 | param3, 144 | } 145 | } 146 | 147 | func TestParameterStore_GetParameter(t *testing.T) { 148 | value := "something-secure" 149 | tests := []struct { 150 | name string 151 | ssmClient ssmClient 152 | parameterName string 153 | expectedError error 154 | expectedOutput *Parameter 155 | }{ 156 | { 157 | name: "Success", 158 | ssmClient: &stubSSMClient{ 159 | GetParameterOutput: &ssm.GetParameterOutput{ 160 | Parameter: param1, 161 | }, 162 | }, 163 | parameterName: "/my-service/dev/DB_PASSWORD", 164 | expectedOutput: &Parameter{ 165 | Value: &value, 166 | }, 167 | }, 168 | { 169 | name: "Failed Empty name", 170 | ssmClient: &stubSSMClient{}, 171 | parameterName: "", 172 | expectedError: ErrParameterInvalidName, 173 | }, 174 | { 175 | name: "Failed Parameter Not Found", 176 | ssmClient: &stubSSMClient{ 177 | GetParameterError: awserr.New(ssm.ErrCodeParameterNotFound, "parameter not found", nil), 178 | }, 179 | parameterName: "/my-service/dev/NOT_FOUND", 180 | expectedError: ErrParameterNotFound, 181 | }, 182 | } 183 | for _, test := range tests { 184 | t.Run(test.name, func(t *testing.T) { 185 | 186 | client := NewParameterStoreWithClient(test.ssmClient) 187 | parameter, err := client.GetParameter(test.parameterName, true) 188 | if err != test.expectedError { 189 | t.Errorf(`Unexpected error: got %d, expected %d`, err, test.expectedError) 190 | } 191 | if !reflect.DeepEqual(parameter, test.expectedOutput) { 192 | t.Error(`Unexpected parameter`, *parameter, *test.expectedOutput) 193 | } 194 | }) 195 | } 196 | } 197 | 198 | func TestParameterStore_PutSecureParameter(t *testing.T) { 199 | paramName := "foo" 200 | paramValue := "baz" 201 | paramType := "SecureString" 202 | overwriteTrue := true 203 | overwriteFalse := false 204 | 205 | tests := []struct { 206 | name string 207 | ssmClient *stubSSMClient 208 | parameterName string 209 | parameterValue string 210 | overwrite bool 211 | expectedError error 212 | expectedInput *ssm.PutParameterInput 213 | }{ 214 | { 215 | name: "Failed Empty name", 216 | ssmClient: &stubSSMClient{}, 217 | parameterName: "", 218 | parameterValue: "", 219 | expectedError: ErrParameterInvalidName, 220 | }, 221 | { 222 | name: "Set Correct Defaults", 223 | ssmClient: &stubSSMClient{}, 224 | parameterName: paramName, 225 | parameterValue: paramValue, 226 | expectedInput: &ssm.PutParameterInput{ 227 | Name: ¶mName, 228 | Type: ¶mType, 229 | Value: ¶mValue, 230 | Overwrite: &overwriteFalse, 231 | }, 232 | }, 233 | { 234 | name: "Overwrite Changes Propagate", 235 | ssmClient: &stubSSMClient{}, 236 | parameterName: paramName, 237 | parameterValue: paramValue, 238 | overwrite: overwriteTrue, 239 | expectedInput: &ssm.PutParameterInput{ 240 | Name: ¶mName, 241 | Type: ¶mType, 242 | Value: ¶mValue, 243 | Overwrite: &overwriteTrue, 244 | }, 245 | }, 246 | } 247 | for _, test := range tests { 248 | t.Run(test.name, func(t *testing.T) { 249 | client := NewParameterStoreWithClient(test.ssmClient) 250 | err := client.PutSecureParameter(test.parameterName, test.parameterValue, test.overwrite) 251 | if err != test.expectedError { 252 | t.Errorf(`Unexpected error: got %d, expected %d`, err, test.expectedError) 253 | } 254 | if !reflect.DeepEqual(test.ssmClient.PutParameterInputReceived, test.expectedInput) { 255 | t.Errorf(`Unexpected parameter: got %v, expected %v`, test.ssmClient.PutParameterInputReceived, test.expectedInput) 256 | } 257 | }) 258 | } 259 | } 260 | 261 | func TestParameterStore_PutSecureParameterWithCMK(t *testing.T) { 262 | paramName := "foo" 263 | paramValue := "baz" 264 | paramType := "SecureString" 265 | overwriteFalse := false 266 | kmsID := "super-secret-kms" 267 | tests := []struct { 268 | name string 269 | ssmClient *stubSSMClient 270 | parameterName string 271 | parameterValue string 272 | overwrite bool 273 | kmsID string 274 | expectedError error 275 | expectedInput *ssm.PutParameterInput 276 | }{ 277 | { 278 | name: "Failed Empty name", 279 | ssmClient: &stubSSMClient{}, 280 | parameterName: "", 281 | parameterValue: "", 282 | expectedError: ErrParameterInvalidName, 283 | }, 284 | { 285 | name: "Set Correct Defaults", 286 | ssmClient: &stubSSMClient{}, 287 | parameterName: paramName, 288 | parameterValue: paramValue, 289 | expectedInput: &ssm.PutParameterInput{ 290 | Name: ¶mName, 291 | Overwrite: &overwriteFalse, 292 | Type: ¶mType, 293 | Value: ¶mValue, 294 | }, 295 | }, 296 | { 297 | name: "KMS ID Changes Propagate", 298 | ssmClient: &stubSSMClient{}, 299 | parameterName: paramName, 300 | parameterValue: paramValue, 301 | kmsID: kmsID, 302 | expectedInput: &ssm.PutParameterInput{ 303 | KeyId: &kmsID, 304 | Name: ¶mName, 305 | Overwrite: &overwriteFalse, 306 | Type: ¶mType, 307 | Value: ¶mValue, 308 | }, 309 | }, 310 | } 311 | for _, test := range tests { 312 | t.Run(test.name, func(t *testing.T) { 313 | client := NewParameterStoreWithClient(test.ssmClient) 314 | err := client.PutSecureParameterWithCMK(test.parameterName, test.parameterValue, test.overwrite, test.kmsID) 315 | if err != test.expectedError { 316 | t.Errorf(`Unexpected error: got %d, expected %d`, err, test.expectedError) 317 | } 318 | if !reflect.DeepEqual(test.ssmClient.PutParameterInputReceived, test.expectedInput) { 319 | t.Errorf(`Unexpected parameter: got %v, expected %v`, test.ssmClient.PutParameterInputReceived, test.expectedInput) 320 | } 321 | }) 322 | } 323 | } 324 | -------------------------------------------------------------------------------- /parameter_test.go: -------------------------------------------------------------------------------- 1 | package awsssm 2 | 3 | import ( 4 | "bytes" 5 | "math/rand" 6 | "reflect" 7 | "testing" 8 | "time" 9 | ) 10 | 11 | type env struct { 12 | DatabasePassword string `mapstructure:"DB_PASSWORD"` 13 | DatabaseHost string `mapstructure:"DB_HOST"` 14 | NotMappedField string `mapstructure:"NOT_THERE"` 15 | } 16 | 17 | func TestParameters_GetValueByName(t *testing.T) { 18 | tests := []struct { 19 | name string 20 | basePath string 21 | parameters map[string]*Parameter 22 | paramName string 23 | expectedValue string 24 | }{ 25 | { 26 | name: "Success Get By Name", 27 | basePath: "/my-service/dev/", 28 | parameters: getParametersMap(), 29 | paramName: "DB_PASSWORD", 30 | expectedValue: "something-secure", 31 | }, 32 | { 33 | name: "Success Get By Name That Doesn't Exist", 34 | basePath: "/my-service/dev/", 35 | parameters: getParametersMap(), 36 | paramName: "NOT_EXISTING_PARAMETER", 37 | expectedValue: "", 38 | }, 39 | } 40 | for _, test := range tests { 41 | t.Run(test.name, func(t *testing.T) { 42 | parameter := NewParameters(test.basePath, test.parameters) 43 | value := parameter.GetValueByName(test.paramName) 44 | if value != test.expectedValue { 45 | t.Errorf(`Unexpected value: got %s, expected %s`, value, test.expectedValue) 46 | } 47 | }) 48 | } 49 | } 50 | 51 | func TestParameters_GetValueByFullPath(t *testing.T) { 52 | tests := []struct { 53 | name string 54 | basePath string 55 | parameters map[string]*Parameter 56 | paramName string 57 | expectedValue string 58 | }{ 59 | { 60 | name: "Success Get By Name", 61 | basePath: "/my-service/dev/", 62 | parameters: getParametersMap(), 63 | paramName: "/my-service/dev/DB_PASSWORD", 64 | expectedValue: "something-secure", 65 | }, 66 | { 67 | name: "Success Get By Name That Doesn't Exist", 68 | basePath: "/my-service/dev/", 69 | parameters: getParametersMap(), 70 | paramName: "/my-service/dev/NOT_EXISTING_PARAMETER", 71 | expectedValue: "", 72 | }, 73 | } 74 | for _, test := range tests { 75 | t.Run(test.name, func(t *testing.T) { 76 | parameter := NewParameters(test.basePath, test.parameters) 77 | value := parameter.GetValueByFullPath(test.paramName) 78 | if value != test.expectedValue { 79 | t.Errorf(`Unexpected value: got %s, expected %s`, value, test.expectedValue) 80 | } 81 | }) 82 | } 83 | } 84 | 85 | func TestParameters_Decode(t *testing.T) { 86 | tests := []struct { 87 | name string 88 | basePath string 89 | parameters map[string]*Parameter 90 | expectedError error 91 | expectedEnvStruct *env 92 | }{ 93 | { 94 | name: "Success Decode", 95 | basePath: "/my-service/dev/", 96 | parameters: getParametersMap(), 97 | expectedEnvStruct: &env{ 98 | DatabasePassword: "something-secure", 99 | DatabaseHost: "rds.something.aws.com", 100 | NotMappedField: "", 101 | }, 102 | }, 103 | } 104 | for _, test := range tests { 105 | t.Run(test.name, func(t *testing.T) { 106 | e := new(env) 107 | parameter := NewParameters(test.basePath, test.parameters) 108 | err := parameter.Decode(e) 109 | if err != test.expectedError { 110 | t.Errorf(`Unexpected error: got %s, expected %s`, err, test.expectedError) 111 | } 112 | if !reflect.DeepEqual(e, test.expectedEnvStruct) { 113 | t.Errorf(`Unexpected value: got %s, expected %s`, e, test.expectedEnvStruct) 114 | } 115 | }) 116 | } 117 | } 118 | 119 | func TestParameters_Read(t *testing.T) { 120 | tests := []struct { 121 | name string 122 | basePath string 123 | parameters map[string]*Parameter 124 | expectedError error 125 | expectedByteCount int64 126 | }{ 127 | { 128 | name: "ReadFrom Small Byte Count", 129 | basePath: "/my-service/dev", 130 | parameters: getParametersMap(), 131 | expectedError: nil, 132 | expectedByteCount: 70, 133 | }, 134 | { 135 | name: "ReadFrom Large Byte Count", 136 | basePath: "/my-service/dev", 137 | parameters: getRandomParametersMap(1000, 10), 138 | expectedError: nil, 139 | expectedByteCount: 33001, 140 | }, 141 | } 142 | for _, test := range tests { 143 | t.Run(test.name, func(t *testing.T) { 144 | parameter := NewParameters(test.basePath, test.parameters) 145 | buf := new(bytes.Buffer) 146 | bytesRead, err := buf.ReadFrom(parameter) 147 | if err != test.expectedError { 148 | t.Errorf(`Unexpected error: got %s, expected %s`, err, test.expectedError) 149 | } 150 | if bytesRead != test.expectedByteCount { 151 | t.Errorf(`Unexpected value: got %d, expected %d`, bytesRead, test.expectedByteCount) 152 | } 153 | }) 154 | } 155 | } 156 | 157 | func TestParameters_GetAllValues(t *testing.T) { 158 | tests := []struct { 159 | name string 160 | basePath string 161 | parameters map[string]*Parameter 162 | }{ 163 | { 164 | name: "GetAllValues default map", 165 | basePath: "/my-service/dev/", 166 | parameters: getParametersMap(), 167 | }, 168 | { 169 | name: "GetAllValues random map", 170 | basePath: "/my-service/dev/", 171 | parameters: getRandomParametersMap(1000, 10), 172 | }, 173 | } 174 | for _, test := range tests { 175 | t.Run(test.name, func(t *testing.T) { 176 | parameter := NewParameters(test.basePath, test.parameters) 177 | 178 | mp := parameter.GetAllValues() 179 | if len(mp) != len(test.parameters) { 180 | t.Errorf(`Unexpected value: got %v, expected %v`, len(mp), len(test.parameters)) 181 | } 182 | }) 183 | } 184 | } 185 | 186 | func getParametersMap() map[string]*Parameter { 187 | return map[string]*Parameter{ 188 | "/my-service/dev/DB_PASSWORD": {Value: param1.Value}, 189 | "/my-service/dev/DB_HOST": {Value: param2.Value}, 190 | } 191 | } 192 | 193 | var seededRand = rand.New( 194 | rand.NewSource(time.Now().UnixNano())) 195 | 196 | const charset = "abcdefghijklmnopqrstuvwxyz" + 197 | "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 198 | 199 | func getRandomParametersMap(n int, l int) map[string]*Parameter { 200 | m := make(map[string]*Parameter) 201 | for i := 0; i < n; i++ { 202 | s := "/my-service/dev/" 203 | for j := 0; j < l; j++ { 204 | char := charset[seededRand.Intn(int(^uint(0)>>1))%len(charset)] 205 | s += string(char) 206 | } 207 | m[s] = &Parameter{ 208 | Value: param1.Value, 209 | } 210 | } 211 | return m 212 | } 213 | --------------------------------------------------------------------------------