github.com/wuhuizuo/gomplate@v3.5.0+incompatible/docs/content/datasources.md (about) 1 --- 2 title: Datasources 3 weight: 13 4 menu: main 5 --- 6 7 Datasources are an optional, but central concept in gomplate. While the basic flow of template rendering is taking an input template and rendering it into an output, there often is need to include data from one or more sources external to the template itself. 8 9 Some common use-cases include injecting sensitive material like passwords (which should not be stored unencrypted in source-control with the templates), or providing simplified configuration formats that can be fed to a template to provide a much more complex output. 10 11 Datasources can be defined with the [`--datasource`/`-d`][] command-line flag or the [`defineDatasource`][] function, and referenced via an _alias_ inside the template, using a function such as [`datasource`][] or [`include`][]. Datasources can additionally be loaded into the [context][] with the [`--context`/`-c`][] command-line flag. 12 13 Since datasources are defined separately from the template, the same templates can be used with different datasources and even different datasource types. For example, gomplate could be run on a developer machine with a `file` datasource pointing to a JSON file containing test data, where the same template could be used in a production environment using a `consul` datasource with the real production data. 14 15 ## URL Format 16 17 All datasources are defined with a [URL][]. As a refresher, a URL is made up of the following components: 18 19 ```pre 20 foo://example.com:8042/over/there?name=ferret#nose 21 \_/ \______________/\_________/ \_________/ \__/ 22 | | | | | 23 scheme authority path query fragment 24 ``` 25 26 For our purposes, the _scheme_ and the _path_ components are especially important, though the other components are used by certain datasources for particular purposes. 27 28 | component | purpose | 29 |-----------|---------| 30 | _scheme_ | Identifies which [datasource](#supported-datasources) to access. All datasources require a scheme (except for `file` when using relative paths), and some datasources allow multiple different schemes to clarify access modes, such as `consul+https` | 31 | _authority_ | Used only by networked datasources, and can be omitted in some of those cases | 32 | _path_ | Can be omitted, but usually used as the basis of the locator for the datasource. If the path ends with a `/` character, [directory](#directory-datasources) semantics are used. | 33 | _query_ | Used rarely for datasources where information must be provided in order to get a reasonable reply (such as generating dynamic secrets with Vault), or for [overriding MIME types](#overriding-mime-types) | 34 | _fragment_ | Used rarely for accessing a subset of the given path (such as a bucket name in a BoltDB database) | 35 36 ### Opaque URIs 37 38 For some more advanced datasources, such as the [`merge` scheme](#using-merge-datasources), opaque URIs are used (rather than a hierarchical URL): 39 40 ```pre 41 scheme path query fragment 42 | _____________________|__ _______|_ _| 43 / \ / \ / \ / \ 44 urn:example:animal:ferret:nose?name=ferret#nose 45 ``` 46 47 The semantics of the different URI components are essentially the same as for hierarchical URLs (see above), 48 but the _path_ component may not start with a `/` character. In gomplate's usage, opaque URIs sometimes contain 49 characters such as `|`, which require escaping with most shells. You may need to surround the datasource definition 50 in quotes, or use the `\` escape character. 51 52 ## Supported datasources 53 54 Gomplate supports a number of datasources, each specified with a particular URL scheme. The table below describes these datasources. The names in the _Type_ column link to further documentation for each specific datasource. 55 56 | Type | URL Scheme(s) | Description | 57 |------|---------------|-------------| 58 | [AWS Systems Manager Parameter Store](#using-aws-smp-datasources) | `aws+smp` | [AWS Systems Manager Parameter Store][AWS SMP] is a hierarchically-organized key/value store which allows storage of text, lists, or encrypted secrets for retrieval by AWS resources | 59 | [AWS Secrets Manager](#using-aws-sm-datasource) | `aws+sm` | [AWS Secrets Manager][] helps you protect secrets needed to access your applications, services, and IT resources. | 60 | [BoltDB](#using-boltdb-datasources) | `boltdb` | [BoltDB][] is a simple local key/value store used by many Go tools | 61 | [Consul](#using-consul-datasources) | `consul`, `consul+http`, `consul+https` | [HashiCorp Consul][] provides (among many other features) a key/value store | 62 | [Environment](#using-env-datasources) | `env` | Environment variables can be used as datasources - useful for testing | 63 | [File](#using-file-datasources) | `file` | Files can be read in any of the [supported formats](#mime-types), including by piping through standard input (`Stdin`). [Directories](#directory-datasources) are also supported. | 64 | [HTTP](#using-http-datasources) | `http`, `https` | Data can be sourced from HTTP/HTTPS sites in many different formats. Arbitrary HTTP headers can be set with the [`--datasource-header`/`-H`][] flag | 65 | [Merged Datasources](#using-merge-datasources) | `merge` | Merge two or more datasources together to produce the final value - useful for resolving defaults. Uses [`coll.Merge`][] for merging. | 66 | [Stdin](#using-stdin-datasources) | `stdin` | A special case of the `file` datasource; allows piping through standard input (`Stdin`) | 67 | [Vault](#using-vault-datasources) | `vault`, `vault+http`, `vault+https` | [HashiCorp Vault][] is an industry-leading open-source secret management tool. [List support](#directory-datasources) is also available. | 68 69 ## Directory Datasources 70 71 When the _path_ component of the URL ends with a `/` character, the datasource is read with _directory_ semantics. Not all datasource types support this, and for those that don't support the notion of a directory, the behaviour is currently undefined. See each documentation section for details. 72 73 Currently the following datasources support directory semantics: 74 75 - [File](#using-file-datasources) 76 - [Vault](#using-vault-datasources) - translates to Vault's [LIST](https://www.vaultproject.io/api/index.html#reading-writing-and-listing-secrets) method 77 - [Consul](#using-consul-datasources) 78 When accessing a directory datasource, an array of key names is returned, and can be iterated through to access each individual value contained within. 79 80 For example, a group of configuration key/value pairs (named `one`, `two`, and `three`, with values `v1`, `v2`, and `v3` respectively) could be rendered like this: 81 82 _template.tmpl:_ 83 ``` 84 {{ range (datasource "config") -}} 85 {{ . }} = {{ (datasource "config" .).value }} 86 {{- end }} 87 ``` 88 89 ```console 90 $ gomplate -d config=vault:///secret/configs/ -f template.tmpl 91 one = v1 92 two = v2 93 three = v3 94 ``` 95 96 ## MIME Types 97 98 Gomplate will read and parse a number of data formats. The appropriate type will be set automatically, if possible, either based on file extension (for the `file` and `http` datasources), or the [HTTP Content-Type][] header, if available. If an unsupported type is detected, gomplate will exit with an error. 99 100 These are the supported types: 101 102 | Format | MIME Type | Extension(s) | Notes | 103 |--------|-----------|-------|------| 104 | CSV | `text/csv` | `.csv` | Uses the [`data.CSV`][] function to present the file as a 2-dimensional row-first string array | 105 | JSON | `application/json` | `.json` | [JSON][] _objects_ are assumed, and arrays or other values are not parsed with this type. Uses the [`data.JSON`][] function for parsing. [EJSON][] (encrypted JSON) is supported and will be decrypted. | 106 | JSON Array | `application/array+json` | | A special type for parsing datasources containing just JSON arrays. Uses the [`data.JSONArray`][] function for parsing | 107 | Plain Text | `text/plain` | | Unstructured, and as such only intended for use with the [`include`][] function | 108 | TOML | `application/toml` | `.toml` | Parses [TOML][] with the [`data.TOML`][] function | 109 | YAML | `application/yaml` | `.yml`, `.yaml` | Parses [YAML][] with the [`data.YAML`][] function | 110 | [.env](#the-env-file-format) | `application/x-env` | `.env` | Basically just a file of `key=value` pairs separated by newlines, usually intended for sourcing into a shell. Common in [Docker Compose](https://docs.docker.com/compose/env-file/), [Ruby](https://github.com/bkeepers/dotenv), and [Node.js](https://github.com/motdotla/dotenv) applications. See [below](#the-env-file-format) for more information. | 111 112 ### Overriding MIME Types 113 114 On occasion it's necessary to override the detected (via file extension or `Content-Type` header) MIME type. To accomplish this, gomplate supports a `type` query string parameter on datasource URLs. This can contain the same value as a standard [HTTP Content-Type][] header. 115 116 For example, to force a file named `data.txt` to be parsed as a JSON document: 117 118 ```console 119 $ echo '{"foo": "bar"}' > /tmp/data.txt 120 $ gomplate -d data=file:///tmp/data.txt?type=application/json -i '{{ (ds "data").foo }}' 121 bar 122 ``` 123 124 ### The `.env` file format 125 126 Many applications and frameworks support the use of a ".env" file for providing environment variables. It can also be considerd a simple key/value file format, and as such can be used as a datasource in gomplate. 127 128 To [override](#overriding-mime-types), use the unregistered `application/x-env` MIME type. 129 130 Here's a sample explaining the syntax: 131 132 ```bash 133 FOO=a regular unquoted value 134 export BAR=another value, exports are ignored 135 136 # comments are totally ignored, as are blank lines 137 FOO.BAR = "values can be double-quoted, and\tshell\nescapes are supported" 138 139 BAZ="variable expansion: ${FOO}" 140 QUX='single quotes ignore $variables and newlines' 141 ``` 142 143 The [`github.com/joho/godotenv`](https://github.com/joho/godotenv) package is used for parsing - see the full details there. 144 145 146 ## Using `aws+smp` datasources 147 148 The `aws+smp://` scheme can be used to retrieve data from the [AWS Systems Manager](https://aws.amazon.com/systems-manager/) (née AWS EC2 Simple Systems Manager) [Parameter Store](https://aws.amazon.com/systems-manager/features/#Parameter_Store). This hierarchically organized key/value store allows you to store text, lists or encrypted secrets for easy retrieval by AWS resources. See [the AWS Systems Manager documentation](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-su-create.html#sysman-paramstore-su-create-about) for details on creating these parameters. 149 150 151 You must grant `gomplate` permission via IAM credentials for the [`ssm:GetParameter` action](https://docs.aws.amazon.com/systems-manager/latest/userguide/auth-and-access-control-permissions-reference.html). <!-- List support further requires `ssm.GetParameters` permissions. --> 152 153 See details on how to configure gomplate's AWS support in [_Configuring AWS_](../functions/aws/#configuring-aws). 154 155 ### URL Considerations 156 157 For `aws+smp`, only the _scheme_ and _path_ components are necessary to be defined. Other URL components are ignored. 158 159 ### Output 160 161 The output will be a single `Parameter` object from the 162 [AWS SDK for Go](https://docs.aws.amazon.com/sdk-for-go/api/service/ssm/#Parameter): 163 164 | name | description | 165 |--------|-------| 166 | `Name` | full Parameter name | 167 | `Type` | `String`, `StringList` or `SecureString` | 168 | `Value` | textual value, comma-separated single string if StringList | 169 | `Version` | incrementing integer version | 170 171 If the Parameter key specified is not found (or not allowed to be read due to missing permissions) an error will be generated. There is no default. 172 173 ### Examples 174 175 Given your [AWS account's Parameter Store](https://eu-west-1.console.aws.amazon.com/ec2/v2/home#Parameters:sort=Name) has the following data: 176 177 - `/foo/first/others` - `Bill,Ben` (a StringList) 178 - `/foo/first/password` - `super-secret` (a SecureString) 179 - `/foo/second/p1` - `aaa` 180 181 ```console 182 $ echo '{{ ds "foo" }}' | gomplate -d foo=aws+smp:///foo/first/password 183 map[Name:/foo/first/password Type:SecureString Value:super-secret Version:1] 184 185 $ echo '{{ (ds "foo").Value }}' | gomplate -d foo=aws+smp:///foo/first/password 186 super-secret 187 188 $ echo '{{ (ds "foo" "/foo/first/others").Value }}' | gomplate -d foo=aws+smp: 189 Bill,Ben 190 191 $ echo '{{ (ds "foo" "/second/p1").Value }}' | gomplate -d foo=aws+smp:///foo/ 192 aaa 193 ``` 194 195 ## Using `aws+sm` datasource 196 197 ### URL Considerations 198 For `aws+sm`, only the _scheme_ and _path_ components are necessary to be defined. Other URL components are ignored. 199 200 ### Output 201 202 The output will be the SecretString from the `GetSecretValueOutput` object from the [AWS SDK for Go](https://docs.aws.amazon.com/sdk-for-go/api/service/secretsmanager/#GetSecretValueOutput) 203 204 ### Examples 205 206 Given your [AWS account's Secret Manager](https://eu-central-1.console.aws.amazon.com/secretsmanager/home?region=eu-central-1#/listSecrets) has the following data: 207 208 - `/foo/bar/password` - `super-secret` 209 210 ```console 211 $ echo '{{ (ds "foo") }}' | gomplate -d foo=aws+sm:///foo/bar/password 212 super-secret 213 214 $ echo '{{ (ds "foo" "/foo/bar/password") }}' | gomplate -d foo=aws+sm: 215 super-secret 216 217 $ echo '{{ (ds "foo" "/bar/password") }}' | gomplate -d foo=aws+sm:///foo/ 218 super-secret 219 ``` 220 221 ## Using `boltdb` datasources 222 223 [BoltDB](https://github.com/boltdb/bolt) is a simple local key/value store used by many Go tools. The `boltdb://` scheme can be used to access values stored in a BoltDB database file. The full path is provided in the URL, and the bucket name can be specified using a URL fragment (e.g. `boltdb:///tmp/database.db#bucket`). 224 225 **Note:** Access is implemented through [`libkv`](https://github.com/docker/libkv), and as such, the first 8 bytes of all values are used as an incrementing last modified index value. All values must therefore be at least 9 bytes long, with the first 8 being ignored. 226 227 The following environment variables can be set: 228 229 | name | usage | 230 |------|-------| 231 | `BOLTDB_TIMEOUT` | Timeout (in seconds) to wait for a lock on the database file when opening. | 232 | `BOLTDB_PERSIST` | If set keep the database open instead of closing after each read. Any value acceptable to [`strconv.ParseBool`](https://golang.org/pkg/strconv/#ParseBool) can be provided. | 233 234 ### URL Considerations 235 236 For `boltdb`, the _scheme_, _path_, and _fragment_ are used. 237 238 The _path_ must point to a BoltDB database on the local file system, while the _fragment_ must provide the name of the bucket to use. 239 240 ### Example 241 242 ```console 243 $ gomplate -d config=boltdb:///tmp/config.db#Bucket1 -i '{{(datasource "config" "foo")}}' 244 bar 245 ``` 246 247 ## Using `consul` datasources 248 249 Gomplate supports retrieving data from [HashiCorp Consul][]'s [KV Store](https://www.consul.io/api/kv.html). 250 251 ### URL Considerations 252 253 For `consul`, the _scheme_, _authority_, and _path_ components are used. 254 255 - the _scheme_ URL component can be one of three values: `consul`, `consul+http`, and `consul+https`. The first two are equivalent, while the third instructs the client to connect to Consul over an encrypted HTTPS connection. Encryption can alternately be enabled by use of the `$CONSUL_HTTP_SSL` environment variable. 256 - the _authority_ is used to specify the server to connect to (e.g. `consul://localhost:8500`), but if not specified, the `$CONSUL_HTTP_ADDR` environment variable will be used. 257 - the _path_ can be provided to select a specific key, or a key prefix 258 259 ### Consul Environment Variables 260 261 The following optional environment variables are understood by the Consul datasource: 262 263 | name | usage | 264 |------|-------| 265 | `CONSUL_HTTP_ADDR` | Hostname and optional port for connecting to Consul. Defaults to `http://localhost:8500` | 266 | `CONSUL_TIMEOUT` | Timeout (in seconds) when communicating to Consul. Defaults to 10 seconds. | 267 | `CONSUL_HTTP_TOKEN` | The Consul token to use when connecting to the server. | 268 | `CONSUL_HTTP_AUTH` | Should be specified as `<username>:<password>`. Used to authenticate to the server. | 269 | `CONSUL_HTTP_SSL` | Force HTTPS if set to `true` value. Disables if set to `false`. Any value acceptable to [`strconv.ParseBool`](https://golang.org/pkg/strconv/#ParseBool) can be provided. | 270 | `CONSUL_TLS_SERVER_NAME` | The server name to use as the SNI host when connecting to Consul via TLS. | 271 | `CONSUL_CACERT` | Path to CA file for verifying Consul server using TLS. | 272 | `CONSUL_CAPATH` | Path to directory of CA files for verifying Consul server using TLS. | 273 | `CONSUL_CLIENT_CERT` | Client certificate file for certificate authentication. If this is set, `$CONSUL_CLIENT_KEY` must also be set. | 274 | `CONSUL_CLIENT_KEY` | Client key file for certificate authentication. If this is set, `$CONSUL_CLIENT_CERT` must also be set. | 275 | `CONSUL_HTTP_SSL_VERIFY` | Set to `false` to disable Consul TLS certificate checking. Any value acceptable to [`strconv.ParseBool`](https://golang.org/pkg/strconv/#ParseBool) can be provided. <br/> _Recommended only for testing and development scenarios!_ | 276 | `CONSUL_VAULT_ROLE` | Set to the name of the role to use for authenticating to Consul with [Vault's Consul secret backend](https://www.vaultproject.io/docs/secrets/consul/index.html). | 277 | `CONSUL_VAULT_MOUNT` | Used to override the mount-point when using Vault's Consul secret back-end for authentication. Defaults to `consul`. | 278 279 ### Authentication 280 281 Instead of using a non-authenticated Consul connection, you can authenticate with these methods: 282 283 - provide an [ACL Token](https://www.consul.io/docs/guides/acl.html#acl-tokens) in the `CONSUL_HTTP_TOKEN` environment variable 284 - use HTTP Basic Auth by setting the `CONSUL_HTTP_AUTH` environment variable 285 - dynamically generate an ACL token with Vault. This requires Vault to be configured to use the [Consul secret backend](https://www.vaultproject.io/docs/secrets/consul/index.html) and is enabled by passing the name of the role to use in the `CONSUL_VAULT_ROLE` environment variable. 286 287 ### Examples 288 289 ```console 290 $ gomplate -d consul=consul:// -i '{{(datasource "consul" "foo")}}' 291 value for foo key 292 293 $ gomplate -d consul=consul+https://my-consul-server.com:8533/foo -i '{{(datasource "consul" "bar")}}' 294 value for foo/bar key 295 296 $ gomplate -d consul=consul:///foo -i '{{(datasource "consul" "bar/baz")}}' 297 value for foo/bar/baz key 298 ``` 299 300 ## Using `env` datasources 301 302 The `env` datasource type provides access to environment variables. This can be useful for rendering templates that would normally use a different sort of datasource, in test and development scenarios. 303 304 No hierarchy or directory semantics are currently supported. 305 306 **Note:** Variable names are _case-sensitive!_ 307 308 ### URL Considerations 309 310 The _scheme_ and either the _path_ or the _opaque_ part are used, and the _query_ component can be used to [override the MIME type](#overriding-mime-types). 311 312 - the _scheme_ must be `env` 313 - one of the _path_ or _opaque_ component is required, and is interpreted as the environment variable's name. Leading `/` characters are stripped from the _path_. 314 315 ### Examples 316 317 ```console 318 $ gomplate -d user=env:USER -i 'Hello {{ include "user" }}!' 319 Hello hairyhenderson! 320 321 $ gomplate -d homedir=env:///HOME -i '{{ files.IsDir (ds "homedir") }}' 322 true 323 324 $ export foo='{"one":1, "two":2}' 325 $ gomplate -d foo=env:/foo?type=application/json -i '{{ (ds "foo").two }}' 326 2 327 ``` 328 329 ## Using `file` datasources 330 331 The `file` datasource type provides access to files in any of the [supported formats](#mime-types). [Directory datasource](#directory-datasources) semantics are supported. 332 333 ### URL Considerations 334 335 The _scheme_ and _path_ are used, and the _query_ component can be used to [override the MIME type](#overriding-mime-types). 336 337 - the _scheme_ must be `file` for absolute URLs, but may be omitted to allow setting relative paths 338 - the _path_ component is required, and can be an absolute or relative path, and if the file being referenced is in the current working directory, the file's base name (without extension) is used as the datasource alias in absence of an explicit alias. [Directory](#directory-datasources) semantics are available when the path ends with a `/` character. 339 340 ### Examples 341 342 _`person.json`:_ 343 ```json 344 { 345 "name": "Dave" 346 } 347 ``` 348 349 _implicit alias:_ 350 ```console 351 $ gomplate -d person.json -i 'Hello {{ (datasource "person").name }}' 352 Hello Dave 353 ``` 354 355 _explicit alias:_ 356 ```console 357 $ gomplate -d person=./person.json -i 'Hello {{ (datasource "person").name }}' 358 Hello Dave 359 360 $ gomplate -d person=../path/to/person.json -i 'Hello {{ (datasource "person").name }}' 361 Hello Dave 362 363 $ gomplate -d person=file:///tmp/person.json -i 'Hello {{ (datasource "person").name }}' 364 Hello Dave 365 ``` 366 367 ## Using `http` datasources 368 369 To access datasources from HTTP sites or APIs, simply use a `http` or `https` URL: 370 371 ```console 372 $ gomplate -d foo=https://httpbin.org/get -i 'Hello there, {{ (ds "foo").headers.Host }}...' 373 Hello there, httpbin.org... 374 $ gomplate -d foo=https://httpbin.org/get -i '{{ $d := ds "foo" }}Hello there, {{ $d.headers.Host }}, you are looking very {{ index $d.headers "User-Agent" }} today...' 375 Hello there, httpbin.org, you are looking very Go-http-client/1.1 today... 376 ``` 377 378 ### Sending HTTP headers 379 380 Additional headers can be provided with the `--datasource-header`/`-H` option: 381 382 ```console 383 $ gomplate -d foo=https://httpbin.org/get -H 'foo=Foo: bar' -i '{{(datasource "foo").headers.Foo}}' 384 bar 385 ``` 386 387 This can be useful for providing API tokens to authenticated HTTP-based APIs. 388 389 ## Using `merge` datasources 390 391 The `merge` scheme can be used to merge two or more other datasources together. 392 393 `merge:` uses an [_opaque_ URI](#opaque-uris) format, where the _path_ component 394 is a list of datasource aliases or URLs, separated by the `|` character. The 395 datasources are read and merged together from right to left (i.e. the left-most 396 datasource values _override_ those to the right). 397 398 Multiple different formats can be mixed, as long as they produce maps with string 399 keys as their data type. 400 401 The [`coll.Merge`][] function is used to perform the merge operation. 402 403 ### Merging separately-defined datasources 404 405 Consider this example: 406 407 ```console 408 $ gomplate -d "foo=merge:foo|bar|baz" -d foo=... -d bar=... -d baz=... ... 409 ``` 410 411 This will read the `foo`, `bar`, and `baz` datasources (which must be otherwise 412 defined), and then overlay `bar`'s values on top of `baz`'s, then `foo`'s values 413 on top of those. 414 415 The disadvantage with this option is verbosity, but the advantage is that the 416 individual datasources can still be referenced. 417 418 ### Merging datasources defined in-line 419 420 Here's an example using URLs instead of aliases: 421 422 ```console 423 $ gomplate -d "foo=merge:./config/main.yaml|http://example.com/defaults.json" ... 424 ``` 425 426 This has the advantage of being slightly less verbose. Note that relative URLs 427 in a subdirectory are supported in this context, as well as any other supported 428 datasource URL. 429 430 A caveat to defining datasources in-line is that the _query_ and _fragment_ 431 components of the URI are interpreted as part of the `merge:` URI. To merge 432 datasources with query strings or fragments, define separate sources first and 433 use the aliases. Similarly, extra HTTP headers can only be defined for separately- 434 defined datasources. 435 436 ## Using `stdin` datasources 437 438 Normally _Stdin_ is used as the input for the template, but it can also be used 439 to stream a datasource. To do this, specify a URL with the `stdin:` scheme. 440 441 In order for structured input to be correctly parsed, the URL can be given a "fake" file name with a supported extension, or the [MIME type can be explicitly set](#overriding-mime-types). If the input is unstructured (i.e. if the data is being included verbatim with the [`include`][] function), the scheme alone is enough. 442 443 ```console 444 $ echo 'foo: bar' | gomplate -i '{{(ds "data").foo}}' -d data=stdin:///foo.yaml 445 bar 446 $ echo 'foo' | gomplate -i '{{ include "data" }}' -d data=stdin: 447 foo 448 $ echo '["one", "two"]' | gomplate -i '{{index (ds "data") 1 }}' -d data=stdin:?type=application/array%2Bjson 449 two 450 ``` 451 452 ## Using `vault` datasources 453 454 Gomplate can retrieve secrets and other data from [HashiCorp Vault][]. 455 456 ### URL Considerations 457 458 The _scheme_, _authority_, _path_, and _query_ URL components are used by this datasource. 459 460 - the _scheme_ must be one of `vault`, `vault+https` (same as `vault`), or `vault+http`. The latter can be used to access [dev mode](https://www.vaultproject.io/docs/concepts/dev-server.html) Vault servers, for test purposes. Otherwise, all connections to Vault are encrypted with TLS. 461 - the _authority_ component can optionally be used to specify the Vault server's hostname and port. This overrides the value of `$VAULT_ADDR`. 462 - the _path_ component can optionally be used to specify a full or partial path to a secret. The second argument to the [`datasource`][] function is appended to provide the full secret path. [Directory](#directory-datasources) semantics are available when the path ends with a `/` character. 463 - the _query_ component is used to provide parameters to dynamic secret back-ends that require these. The values are included in the JSON body of the `PUT` request. 464 465 These are all valid `vault` URLs: 466 467 - `vault:`, `vault://`, `vault:///` - these all require the [`datasource`][] function to provide the secret path 468 - `vault://vault.example.com:8200` - connect to `vault.example.com` over HTTPS at port `8200`. The path will be provided by [`datasource`][] 469 - `vault:///ssh/creds/foo?ip=10.1.2.3&username=user` - create a dynamic secret with the parameters `ip` and `username` provided in the body 470 - `vault:///secret/configs/` - returns a list of key names with the prefix of `secret/configs/` 471 472 ### Vault Authentication 473 474 This table describes the currently-supported authentication mechanisms and how to use them, in order of precedence: 475 476 | auth back-end | configuration | 477 |-------------:|---------------| 478 | [`approle`](https://www.vaultproject.io/docs/auth/approle.html) | Environment variables `$VAULT_ROLE_ID` and `$VAULT_SECRET_ID` must be set to the appropriate values.<br/> If the back-end is mounted to a different location, set `$VAULT_AUTH_APPROLE_MOUNT`. | 479 | [`app-id`](https://www.vaultproject.io/docs/auth/app-id.html) | Environment variables `$VAULT_APP_ID` and `$VAULT_USER_ID` must be set to the appropriate values.<br/> If the back-end is mounted to a different location, set `$VAULT_AUTH_APP_ID_MOUNT`. | 480 | [`github`](https://www.vaultproject.io/docs/auth/github.html) | Environment variable `$VAULT_AUTH_GITHUB_TOKEN` must be set to an appropriate value.<br/> If the back-end is mounted to a different location, set `$VAULT_AUTH_GITHUB_MOUNT`. | 481 | [`userpass`](https://www.vaultproject.io/docs/auth/userpass.html) | Environment variables `$VAULT_AUTH_USERNAME` and `$VAULT_AUTH_PASSWORD` must be set to the appropriate values.<br/> If the back-end is mounted to a different location, set `$VAULT_AUTH_USERPASS_MOUNT`. | 482 | [`token`](https://www.vaultproject.io/docs/auth/token.html) | Determined from either the `$VAULT_TOKEN` environment variable, or read from the file `~/.vault-token` | 483 | [`aws`](https://www.vaultproject.io/docs/auth/aws.html) | The env var `$VAULT_AUTH_AWS_ROLE` defines the [role](https://www.vaultproject.io/api/auth/aws/index.html#role-4) to log in with - defaults to the AMI ID of the EC2 instance. Usually a [Client Nonce](https://www.vaultproject.io/docs/auth/aws.html#client-nonce) should be used as well. Set `$VAULT_AUTH_AWS_NONCE` to the nonce value. The nonce can be generated and stored by setting `$VAULT_AUTH_AWS_NONCE_OUTPUT` to a path on the local filesystem.<br/>If the back-end is mounted to a different location, set `$VAULT_AUTH_AWS_MOUNT`.| 484 485 _**Note:**_ The secret values listed in the above table can either be set in environment variables or provided in files. This can increase security when using [Docker Swarm Secrets](https://docs.docker.com/engine/swarm/secrets/), for example. To use files, specify the filename by appending `_FILE` to the environment variable, (i.e. `VAULT_USER_ID_FILE`). If the non-file variable is set, this will override any `_FILE` variable and the secret file will be ignored. 486 487 ### Vault Permissions 488 489 The correct capabilities must be allowed for the [authenticated](#vault-authentication) credentials. See the [Vault documentation](https://www.vaultproject.io/docs/concepts/policies.html#capabilities) for full details. 490 491 - regular secret read operations require the `read` capability 492 - dynamic secret generation requires the `create` and `update` capabilities 493 - list support requires the `list` capability 494 495 ### Vault Environment variables 496 497 In addition to the variables documented [above](#vault-authentication), a number of environment variables are interpreted by the Vault client, and are documented in the [official Vault documentation](https://www.vaultproject.io/docs/commands/index.html#environment-variables). 498 499 ### Examples 500 501 ```console 502 $ gomplate -d vault=vault:///secret/sneakers -i 'My voice is my passport. {{(datasource "vault").value}}' 503 My voice is my passport. Verify me. 504 ``` 505 506 You can also specify the secret path in the template by omitting the path portion of the URL: 507 508 ```console 509 $ gomplate -d vault=vault:/// -i 'My voice is my passport. {{(datasource "vault" "secret/sneakers").value}}' 510 My voice is my passport. Verify me. 511 ``` 512 513 And the two can be mixed to scope secrets to a specific namespace: 514 515 ```console 516 $ gomplate -d vault=vault:///secret/production -i 'db_password={{(datasource "vault" "db/pass").value}}' 517 db_password=prodsecret 518 ``` 519 520 If you are unable to set the `VAULT_ADDR` environment variable, or need to 521 specify multiple Vault datasources connecting to different servers, you can set 522 the address as part of the URL: 523 524 ```console 525 $ gomplate -d v=vault://vaultserver.com/secret/foo -i '{{ (ds "v").value }}' 526 bar 527 ``` 528 529 To use dynamic secrets: 530 531 ```console 532 $ gomplate -d vault=vault:/// -i 'otp={{(ds "vault" "ssh/creds/test?ip=10.1.2.3&username=user").key}}' 533 otp=604a4bd5-7afd-30a2-d2d8-80c4aebc6183 534 ``` 535 536 With the AWS auth back-end: 537 538 ```console 539 $ export VAULT_AUTH_AWS_NONCE_FILE=/tmp/vault-aws-nonce 540 $ export VAULT_AUTH_AWS_NONCE_OUTPUT=$VAULT_AUTH_AWS_NONCE_FILE 541 $ gomplate -d vault=vault:///secret/foo -i '{{ (ds "vault").value }}' 542 ... 543 ``` 544 545 The file `/tmp/vault-aws-nonce` will be created if it didn't already exist, and further executions of `gomplate` can re-authenticate securely. 546 547 [`--datasource`/`-d`]: ../usage/#datasource-d 548 [`--context`/`-c`]: ../usage/#context-c 549 [context]: ../syntax/#the-context 550 [`--datasource-header`/`-H`]: ../usage/#datasource-header-h 551 [`defineDatasource`]: ../functions/data/#definedatasource 552 [`datasource`]: ../functions/data/#datasource 553 [`include`]: ../functions/data/#include 554 [`data.CSV`]: ../functions/data/#data-csv 555 [`data.JSON`]: ../functions/data/#data-json 556 [EJSON]: ../functions/data/#encrypted-json-support-ejson 557 [`data.JSONArray`]: ../functions/data/#data-jsonarray 558 [`data.TOML`]: ../functions/data/#data-toml 559 [`data.YAML`]: ../functions/data/#data-yaml 560 [`coll.Merge`]: ../functions/coll/#coll-merge 561 562 [AWS SMP]: https://aws.amazon.com/systems-manager/features#Parameter_Store 563 [AWS Secrets Manager]: https://aws.amazon.com/secrets-manager 564 [BoltDB]: https://github.com/boltdb/bolt 565 [HashiCorp Consul]: https://consul.io 566 [HashiCorp Vault]: https://vaultproject.io 567 [JSON]: https://json.org 568 [TOML]: https://github.com/toml-lang/toml 569 [YAML]: http://yaml.org 570 [HTTP Content-Type]: https://tools.ietf.org/html/rfc7231#section-3.1.1.1 571 [URL]: https://tools.ietf.org/html/rfc3986 572 [AWS SDK for Go]: https://docs.aws.amazon.com/sdk-for-go/api/