# Table of Contents - [gomplate - gomplate documentation](#gomplate-gomplate-documentation) - [Installing - gomplate documentation](#installing-gomplate-documentation) - [Usage - gomplate documentation](#usage-gomplate-documentation) - [Syntax - gomplate documentation](#syntax-gomplate-documentation) - [Configuration - gomplate documentation](#configuration-gomplate-documentation) - [Functions - gomplate documentation](#functions-gomplate-documentation) - [aws functions - gomplate documentation](#aws-functions-gomplate-documentation) - [collection functions - gomplate documentation](#collection-functions-gomplate-documentation) - [base64 functions - gomplate documentation](#base64-functions-gomplate-documentation) - [Datasources - gomplate documentation](#datasources-gomplate-documentation) - [conversion functions - gomplate documentation](#conversion-functions-gomplate-documentation) - [data functions - gomplate documentation](#data-functions-gomplate-documentation) - [crypto functions - gomplate documentation](#crypto-functions-gomplate-documentation) - [file functions - gomplate documentation](#file-functions-gomplate-documentation) - [env functions - gomplate documentation](#env-functions-gomplate-documentation) - [path functions - gomplate documentation](#path-functions-gomplate-documentation) - [filepath functions - gomplate documentation](#filepath-functions-gomplate-documentation) - [test functions - gomplate documentation](#test-functions-gomplate-documentation) - [math functions - gomplate documentation](#math-functions-gomplate-documentation) - [semver functions - gomplate documentation](#semver-functions-gomplate-documentation) - [template functions - gomplate documentation](#template-functions-gomplate-documentation) - [random functions - gomplate documentation](#random-functions-gomplate-documentation) - [regexp functions - gomplate documentation](#regexp-functions-gomplate-documentation) - [net functions - gomplate documentation](#net-functions-gomplate-documentation) - [strings functions - gomplate documentation](#strings-functions-gomplate-documentation) - [sockaddr functions - gomplate documentation](#sockaddr-functions-gomplate-documentation) - [uuid functions - gomplate documentation](#uuid-functions-gomplate-documentation) - [gcp functions - gomplate documentation](#gcp-functions-gomplate-documentation) - [time functions - gomplate documentation](#time-functions-gomplate-documentation) --- # gomplate - gomplate documentation gomplate ======== `gomplate` is a template renderer which supports a growing list of datasources, such as: JSON (_including EJSON - encrypted JSON_), YAML, AWS EC2 metadata, [Hashicorp Consul](https://www.consul.io/) and [Hashicorp Vault](https://www.vaultproject.io/) secrets. Come chat with developers and community in the [#gomplate channel](https://gophers.slack.com/messages/CGTR16RM2/) on [Gophers Slack](https://invite.slack.golangbridge.org) and on [GitHub Discussions](https://github.com/hairyhenderson/gomplate/discussions) ! _Please report any bugs found in the [issue tracker](https://github.com/hairyhenderson/gomplate/issues/) ._ Examples -------- Here are some hands-on examples of how `gomplate` works: $ # at its most basic, gomplate can be used with environment variables... $ echo 'Hello, {{ .Env.USER }}' | gomplate Hello, hairyhenderson $ # but that's kind of boring. gomplate has tons of functions to do useful stuff, too $ gomplate -i 'the answer is: {{ mul 6 7 }}' the answer is: 42 $ # and, since gomplate uses Go's templating syntax, you can do fun things like: $ gomplate -i '{{ range seq 5 1 }}{{ . }} {{ if eq . 1 }}{{ "blastoff" | toUpper }}{{ end }}{{ end }}' 5 4 3 2 1 BLASTOFF $ # the real fun comes when you use datasources! $ cat ./config.yaml foo: bar: baz: qux $ gomplate -d config=./config.yaml -i 'the value we want is: {{ (datasource "config").foo.bar.baz }}' the value we want is: qux $ # datasources are defined by URLs, and gomplate is not limited to just file-based datasources: $ gomplate -d ip=https://ipinfo.io -i 'country code: {{ (ds "ip").country }}' country code: CA $ # standard input can be used as a datasource too: $ echo '{"cities":["London", "Johannesburg", "Windhoek"]}' | gomplate -d city=stdin:///in.json -i '{{ range (ds "city").cities }}{{.}}, {{end}}' London, Johannesburg, Windhoek, $ # and here's something a little more complicated: $ export CITIES='city: [London, Johannesburg, Windhoek]' $ cat in.tmpl {{ range $i, $city := (ds "cities").city -}} {{ add 1 $i }}: {{ include "weather" (print $city "?0") }} {{ end }} $ gomplate -d 'cities=env:///CITIES?type=application/yaml' -d 'weather=https://wttr.in/?0' -H 'weather=User-Agent: curl' -f in.tmpl 1: Weather report: London \ / Partly cloudy _ /"".-. 4-7 °C \_( ). ↑ 20 km/h /(___(__) 10 km 0.0 mm 2: Weather report: Johannesburg \ / Partly cloudy _ /"".-. 15 °C \_( ). ↘ 0 km/h /(___(__) 10 km 2.2 mm 3: Weather report: Windhoek \ / Partly cloudy _ /"".-. 20 °C \_( ). ↑ 6 km/h /(___(__) 20 km 0.0 mm License ------- [The MIT License](http://opensource.org/licenses/MIT) Copyright (c) 2016-2025 Dave Henderson --- # Installing - gomplate documentation Installing ========== There are many installation methods available for gomplate, depending on your platform and use-case. macOS/Linux with homebrew ------------------------- The simplest method for macOS and Linux is to use [homebrew](https://brew.sh/) : $ brew install gomplate ... ==> Installing gomplate ==> Pouring gomplate-3.8.0.x86_64_linux.bottle.tar.gz 🍺 /home/linuxbrew/.linuxbrew/Cellar/gomplate/3.8.0: 6 files, 7.8MB macOS with MacPorts ------------------- On macOS, you can also install gomplate using [MacPorts](https://www.macports.org) : $ sudo port install gomplate Windows with Chocolatey ----------------------- The simplest method for installing gomplate on Windows is to use [`choco`](https://community.chocolatey.org/packages/gomplate) : choco install gomplate Alpine Linux ------------ `gomplate` is available in Alpine’s `community` repository. $ apk add --no-cache gomplate ... _Note: the Alpine version of gomplate may lag behind the latest release of gomplate._ use with Docker --------------- A simple way to get started is with one of the [hairyhenderson/gomplate](https://hub.docker.com/r/hairyhenderson/gomplate/tags/) Docker images. $ docker run hairyhenderson/gomplate:stable --version gomplate version 3.9.0 Of course, there are some drawbacks - any files to be used for \[datasources\]\[\] must be mounted and any environment variables to be used must be passed through: $ echo 'My voice is my {{.Env.THING}}. {{(datasource "vault").value}}' | docker run -i -e THING=passport -v /home/me/.vault-token:/root/.vault-token hairyhenderson/gomplate -d vault=vault:///secret/sneakers -f - My voice is my passport. Verify me. It can be awkward to always type `docker run hairyhenderson/gomplate:stable`, so this can be made simpler with a shell alias: $ alias gomplate='docker run hairyhenderson/gomplate:stable' $ gomplate --version gomplate version 3.9.0 ### use inside a container `gomplate` is often used inside Docker containers. When building images with Docker 17.05 or higher, you can use [multi-stage builds](https://docs.docker.com/develop/develop-images/multistage-build/) to easily include the `gomplate` binary in your container images. Use the `COPY` instruction’s `--from` flag to accomplish this: ... COPY --from=hairyhenderson/gomplate:stable /gomplate /bin/gomplate Now, `gomplate` will be available in the `/bin` directory inside the container image. Note that when using `gomplate` with HTTPS-based datasources, you will likely need to install the `ca-certificates` package for your base distribution. Here’s an example when using the [`alpine`](https://hub.docker.com/_/alpine) base image: FROM alpine COPY --from=hairyhenderson/gomplate:stable /gomplate /bin/gomplate RUN apk add --no-cache ca-certificates manual install -------------- 1. Get the latest `gomplate` for your platform from the [releases](https://github.com/hairyhenderson/gomplate/releases) page 2. Store the downloaded binary somewhere in your path as `gomplate` (or `gomplate.exe` on Windows) 3. Make sure it’s executable (on Linux/macOS) 4. Test it out with `gomplate --help`! In other words: $ curl -o /usr/local/bin/gomplate -sSL https://github.com/hairyhenderson/gomplate/releases/download//gomplate_- $ chmod 755 /usr/local/bin/gomplate $ gomplate --help ... install with `go install` ------------------------- If you’re a Go developer, sometimes it’s faster to just use `go install` to install `gomplate`: $ go install github.com/hairyhenderson/gomplate/v4/cmd/gomplate@latest $ gomplate --help ... (note that this method produces a binary that isn’t versioned and may not necessarily work correctly) install with `npm` ------------------ For some users, especially Node.js developers, using `npm` may be a natural fit. Even though `gomplate` is written in Go and not Node.js, it can still be installed with `npm`: $ npm install -g gomplate ... install with `tea.xyz` ---------------------- For some users (including for DEVOPS on [GitHub Actions](https://github.com/marketplace/actions/tea-setup) ), [`tea.xyz`](https://tea.xyz/) maybe be very comfortable, therefore, to install, just: $ sh <(curl https://tea.xyz) +gomplate.ca sh $ gomplate --version ... --- # Usage - gomplate documentation Usage ===== The simplest usage of `gomplate` is to just replace environment variables. All environment variables are available by referencing [`.Env`](/syntax/#env) (or [`getenv`](/functions/env/#envgetenv) ) in the template. The template is read from standard in, and written to standard out. Use it like this: $ echo "Hello, {{ .Env.USER }}" | gomplate Hello, hairyhenderson Commandline Arguments --------------------- ### `--config` Specify the path to a [gomplate config file](/config/) . The default is `.gomplate.yaml`. Can also be set with the `GOMPLATE_CONFIG` environment variable. Setting `--config` or `GOMPLATE_CONFIG` to an empty string (`--config=""` or `export GOMPLATE_CONFIG=""`) will disable the use of a config file, skipping the default `.gomplate.yaml` file. For example: $ cat myconfig.yaml in: hello {{ .data.thing }} datasources: data: url: https://example.com/data.json $ gomplate --config myconfig.yaml hello world ### `--file`/`-f`, `--in`/`-i`, and `--out`/`-o` By default, `gomplate` will read from `Stdin` and write to `Stdout`. This behaviour can be changed. * Use `--file`/`-f` to use a specific input template file. The special value `-` means `Stdin`. * Use `--out`/`-o` to save output to file. The special value `-` means `Stdout`. * Use `--in`/`-i` if you want to set the input template right on the commandline. This overrides `--file`. Because of shell command line lengths, it’s probably not a good idea to use a very long value with this argument. #### Multiple inputs You can specify multiple `--file` and `--out` arguments. The same number of each much be given. This allows `gomplate` to process multiple templates _slightly_ faster than invoking `gomplate` multiple times in a row. ### `--input-dir` and `--output-dir` For processing multiple templates in a directory you can use `--input-dir` and `--output-dir` together. In this case all files in input directory will be processed recursively as templates and the resulting files stored in `--output-dir`. The output directory will be created if it does not exist and the directory structure of the input directory will be preserved. You can use the [`--exclude`](#--exclude-and---include) argument and/or a [`.gomplateignore`](#gomplateignore-files) file to exclude some of the files in the input directory. Example: # Process all files in directory "templates" with the datasource given # and store the files with the same directory structure in "config" gomplate --input-dir=templates --output-dir=config --datasource config=config.yaml ### `--output-map` Sometimes a 1-to-1 mapping between input filenames and output filenames is not desirable. For these cases, you can supply a template string as the argument to `--output-map`. The template string is interpreted as a regular gomplate template, and all datasources and external nested templates are available to the output map template. A new [context](/syntax/#the-context) is provided, with the input filename is available at `.in`, and the original context is available at `.ctx`. For convenience, any context keys not conflicting with `in` or `ctx` are also copied. All whitespace on the left or right sides of the output is trimmed. For example, given an input directory `in/` containing files with the extension `.yaml.tmpl`, if we want to rename those to `.yaml`: $ gomplate --input-dir=in/ --output-map='out/{{ .in | strings.ReplaceAll ".yaml.tmpl" ".yaml" }}' #### Referencing complex output map template files It may be useful to store more complex output map templates in a file. This can be done with [external templates](/syntax/#external-templates) . Consider a template `out.t`: {{- /* .in may contain a directory name - we want to preserve that */ -}} {{ $f := filepath.Base .in -}} out/{{ .in | strings.ReplaceAll $f (index .filemap $f) }}.out And a datasource `filemap.json`: { "eins.txt": "uno", "deux.txt": "dos" } We can blend these two together: $ gomplate -t out=out.t -c filemap.json --input-dir=in --output-map='{{ template "out" . }}' ### `--chmod` By default, output files are created with the same file mode (permissions) as input files. If desired, the `--chmod` option can be used to override this behaviour, and set the output file mode explicitly. This can be useful for creating executable scripts or ensuring write permissions. The value must be an octal integer in the standard UNIX `chmod` format, i.e. `644` to indicate that owner gets read+write, group gets read-only, and others get read-only permissions. See the [`chmod(1)` man page](https://linux.die.net/man/1/chmod) for more details. **Note:** `--chmod` is supported on Windows, but only read/write (`666`) and read-only (`444`). If you pass a value like `755` on Windows, gomplate will reinterpret that as what you probably intended (read-write). ### `--exclude` and `--include` When using the [`--input-dir`](#--input-dir-and---output-dir) argument, it can be useful to filter which files are processed. You can use `--exclude` and `--include` to achieve this. The `--exclude` flag takes a [`.gitignore`](https://git-scm.com/docs/gitignore) \-style pattern, and any files matching the pattern will be excluded. The `--include` flag is effectively the opposite of `--exclude`. You can also repeat the arguments to provide a series of patterns to be excluded/included. Patterns provided with `--exclude`/`--include` are matched relative to the input directory. _Note:_ These patterns are _not_ treated as filesystem globs, and so a pattern like `/foo/bar.json` will match relative to the input directory, not the root of the filesystem as they may appear! Examples: $ gomplate --exclude example/** --exclude *.png --input-dir in/ --output-dir out/ This will stop all files in the `in/example` directory from being processed, as well as all `.png` files in the `in/` directory. $ gomplate --include *.tmpl --exclude foo*.tmpl --input-dir in/ --output-dir out/ This will cause only files ending in `.tmpl` to be processed, except for files with names beginning with `foo`: `template.tmpl` will be included, but `foo-template.tmpl` will not. ### `--exclude-processing` When using the [`--input-dir`](#--input-dir-and---output-dir) argument, it can be useful to skip some files from processing and copy them directly to the output directory. Like the `--exclude` flag, it takes a [`.gitignore`](https://git-scm.com/docs/gitignore) \-style pattern, and any files match the pattern will be copied. _Note:_ These patterns are _not_ treated as filesystem globs, and so a pattern like `/foo/bar.json` will match relative to the input directory, not the root of the filesystem as they may appear! Examples: $ gomplate --exclude-processing '*.png' --input-dir in/ --output-dir out/ This will skip all `*.png` files in the `in/` directory from being processed, and copy them to the `out/` directory. #### `.gomplateignore` files You can also use a file named `.gomplateignore` containing one exclude pattern on each line. This has the same syntax as a [`.gitignore`](https://git-scm.com/docs/gitignore) file. When processing sub-directories, `.gomplateignore` files in the parent directory are also considered. Patterns are matched relative to the location of the `.gomplateignore` file. ### `--datasource`/`-d` Add a data source in `name=URL` form. Specify multiple times to add multiple sources. The data can then be used by the [`datasource`](/functions/data/#datasource) and [`include`](/functions/data/#include) functions. Data sources referenced in this way are lazy-loaded: they will not be read until the template is parsed and a `datasource` or `include` function is encountered. See [Datasources](/datasources/) for full details. A few different forms are valid: * `mydata=file:///tmp/my/file.json` * Create a data source named `mydata` which is read from `/tmp/my/file.json`. This form is valid for any file in any path. * `mydata=file.json` * Create a data source named `mydata` which is read from `file.json` (in the current working directory). This form is only valid for files in the current directory. * `mydata.json` * This form infers the name from the file name (without extension). Only valid for files in the current directory. ### `--datasource-header`/`-H` Provides one (or more) HTTP headers to be sent along with the matching HTTP-based datasource. Value is in the form `alias="HeaderName: header-value"`. Note that the `alias` does not need to map to a datasource specified in a command-line flag, but can be used in dynamically-defined datasources (see [`defineDatasource`](/functions/data/#definedatasource) ). ### `--context`/`-c` Add a data source in `name=URL` form, and make it available in the [default context](/syntax/#the-context) as `.`. The special name `.` (period) can be used to override the entire default context. Data sources referenced with `--context` will be immediately loaded before gomplate processes the template. This is in contrast to the `--datasource` behaviour, which lazy-loads data while processing the template. All other rules for the [`--datasource`/`-d`](#--datasource-d) flag apply. Examples: $ gomplate --context post=https://jsonplaceholder.typicode.com/posts/2 -i 'post title is: {{ .post.title }}' post title is: qui est esse $ gomplate -c .=http://xkcd.com/info.0.json -i '{{ .title }}' Diploma Legal Notes ### `--missing-key` Control the behavior during execution if a map is indexed with a key that is not present in the map. Available values: * `error` (default): Execution stops immediately with an error. * `default` or `invalid`: Do nothing and continue execution. If printed, the result is the string `""`. * `zero`: The operation returns the zero value for the element (which may be `nil`, in which case the string `""` is printed). Examples: $ gomplate --missing-key error -i 'Hi {{ .name }}' Hi 14:06:57 ERR error="failed to render template : template: :1:6: executing \"\" at <.name>: map has no entry for key \"name\"" $ gomplate --missing-key default -i 'Hi {{ .name }}' Hi $ gomplate --missing-key zero -i 'Hi {{ .name | default "Alex" }}' Hi Alex $ gomplate --missing-key zero -i 'Hi {{ .name | required }}' Hi 14:12:04 ERR error="failed to render template : template: :1:11: executing \"\" at : error calling required: can not render template: a required value was not set" ### Overriding the template delimiters Sometimes it’s necessary to override the default template delimiters (`{{`/`}}`). Use `--left-delim`/`--right-delim` or set `$GOMPLATE_LEFT_DELIM`/`$GOMPLATE_RIGHT_DELIM`. ### `--template`/`-t` Add a nested template or directory of templates that can be referenced by the main input template(s) with the [`template`](https://pkg.go.dev/text/template/#hdr-Actions) built-in or the functions in the [`tmpl`](/functions/tmpl/) namespace. Specify multiple times to add multiple template references. Similar to data sources, the value is a `alias=url` pair, where `alias` is the template name and `url` is an optionally-relative URL to the template file or directory. Note that currently only `file:` URLs are supported. In addition to the `alias=url` form, in certain cases the alias may be omitted, in which case the `url` will be used as the `alias`. When referencing a directory, all files in the directory will be included, available to be referenced as `alias/`. Some examples: * `--template foo=file:///tmp/foo.tmpl` * References a file `/tmp/foo.tmpl` * It will be available as a template named `foo`: $ gomplate --template foo=file:///tmp/foo.tmpl -i 'here are the contents of the template: [ {{ template "foo" }} ]' here are the contents of the template: [ hello, world! ] * `--template mytemplate.t` * References a file `mytemplate.t` in the current working directory. * It will be available as a template named `mytemplate.t`: $ gomplate --template helloworld.tmpl -i 'here are the contents of the template: [ {{ template "helloworld.tmpl" }} ]' here are the contents of the template: [ hello, world! ] * `--template path/to/mytemplate.t` * References a file `mytemplate.t` in the path `path/to/`. * It will be available as a template named `path/to/mytemplate.t`: $ gomplate --template foo/bar/helloworld.tmpl -i 'here are the contents of the template: [ {{ template "foo/bar/helloworld.tmpl" }} ]' here are the contents of the template: [ hello, world! ] * `--template path/to/` * Makes available all files in the path `path/to/`. * Any files within this path can be referenced: $ gomplate --template foo/bar/ -i 'here are the contents of the template: [ {{ template "foo/bar/helloworld.tmpl" }} ]' here are the contents of the template: [ hello, world! ] * `--template alias=path/to/mytemplate.t` * References a file `mytemplate.t` in the path `path/to/` * It will be available as a template named `alias`: $ gomplate --template t=foo/bar/helloworld.tmpl -i 'here are the contents of the template: [ {{ template "t" }} ]' here are the contents of the template: [ hello, world! ] * `--template alias=path/to/` * Makes available all files in the path `path/to/`. * Any files within this path can be referenced, with the path replaced with `alias`: $ gomplate --template dir=foo/bar/ -i 'here are the contents of the template: [ {{ template "dir/helloworld.tmpl" }} ]' here are the contents of the template: [ hello, world! ] ### `--plugin` _See the [config file](/config/#plugins) for more plugin configuration options._ Some specialized use cases may need functionality that gomplate isn’t capable of on its own. If you have a command or script to perform this functionality, you can plug in your own custom functions with the `--plugin` flag: $ gomplate --plugin echo=/bin/echo -i 'Hello {{ echo "World" }}' Hello World All arguments provided to the function will be passed as positional arguments to the plugin, and the plugin’s standard output stream (`Stdout`) will be printed to the rendered output. To instead pipe the final argument of the function to the plugin’s standard input stream, use the [config file](/config/#plugins) and set the `pipe` field. If the plugin exits with a non-zero exit code, gomplate will also fail. All signals caught by gomplate will be propagated to the plugin. Any output on the standard error stream will be printed to gomplate’s standard error stream. Plugins can also be written as PowerShell or CMD scripts (`.ps1`, `.bat`, or `.cmd` extensions) on Windows. By default, plugins will time out after 5 seconds. To adjust this, set the `GOMPLATE_PLUGIN_TIMEOUT` environment variable to a valid [duration](/functions/time/#timeparseduration) such as `10s` or `3m`, or use the [`pluginTimeout`](/config/#plugintimeout) configuration option. ### `--exec-pipe` When using [post-template command execution](#post-template-command-execution) , it may be useful to pipe gomplate’s rendered output directly into the command’s standard input. To do this, simply use `--exec-pipe` instead of `--out` or any other output flag: $ gomplate -i 'hello world' --exec-pipe -- tr a-z A-Z HELLO WORLD Note that multiple inputs are not yet supported when using this option. ### `--experimental` Use this flag to enable experimental functionality. See the docs for the [`experimental`](/config/#experimental) configuration option for more information. ### `--verbose` When you specify `--verbose`, gomplate will log some extra information useful for debugging and troubleshooting. All log output is done on the _standard error_ stream, and so will never interrupt rendered output. For example, redirecting output to a file or another command will work as expected, without the log output interfering. Log formatting -------------- The `GOMPLATE_LOG_FORMAT` environment variable can be used to control the format of the log messages that gomplate may output, whether error messages or debug messages when the [`--verbose`](#--verbose) option is in use. The value can be set to `json` or `logfmt`. #### `json` format `json` is the default format when gomplate is used in a script or non-interactive terminal. $ GOMPLATE_LOG_FORMAT=json gomplate -i '{{' {"level":"error","error":"template: :1: unexpected unclosed action in command","time":"2021-01-24T20:49:02-05:00"} #### `console` format `console` is the default format used when gomplate is used in an interactive terminal. Messages are printed in colour when possible. $ GOMPLATE_LOG_FORMAT=console gomplate -i '{{' 20:49:28 ERR error="template: :1: unexpected unclosed action in command" #### `logfmt` format `logfmt` format is a simple structured `key=value` format. $ GOMPLATE_LOG_FORMAT=logfmt bin/gomplate -i '{{' time=2021-01-24T20:50:58-05:00 level=error error="template: :1: unexpected unclosed action in command" #### `simple` format `simple` omits the level and timestamp for a very simplistic output. $ GOMPLATE_LOG_FORMAT=simple bin/gomplate -i '{{' error="template: :1: unexpected unclosed action in command" Post-template command execution ------------------------------- Gomplate can launch other commands when template execution is successful. Simply add the command to the command-line after a `--` argument: $ gomplate -i 'hello world' -o out.txt -- cat out.txt hello world See also [`--exec-pipe`](#--exec-pipe) for piping output directly into the post-exec command. Empty output ------------ If the template renders to an empty file (i.e. output consisting of only whitespace), gomplate will not write the output. --- # Syntax - gomplate documentation Syntax ====== Gomplate uses the syntax understood by the Go language’s [`text/template`](https://pkg.go.dev/text/template/) package. This page documents some of that syntax, but see [the language docs](https://pkg.go.dev/text/template/) for full details. The basics ---------- Templates are just regular text, with special actions delimited by `{{` and `}}` markers. Consider the following template: Hello, {{ print "World" }}! If you render this template, it will produce the following output: Hello, World! This is obviously a contrived example, and you would likely never see this in _real life_, but this conveys the basics, which is that _actions_ are delimited by `{{` and `}}`, and are replaced with their output (if any) when the template is rendered. Multi-line templates -------------------- By default, every line containing an action will render a newline. For example, the action block below: {{ range coll.Slice "Foo" "bar" "baz" }} Hello, {{ . }}! {{ end }} will produce the output below: Hello, Foo! Hello, bar! Hello, baz! This might not be desirable. You can use [Golang template syntax](https://pkg.go.dev/text/template/#hdr-Text_and_spaces) to fix this. Leading newlines (i.e. newlines that come before the action) can be suppressed by placing a minus sign in front of the first set of delimiters (`{{`). Putting the minus sign behind the trailing set of delimiters (`}}`) will suppress the newline _after_ the action. You can do both to suppress newlines entirely on that line. Placing the minus sign within the context (i.e. inside of `{{.}}`) has no effect. Here are a few examples. ### Suppressing leading newlines {{- range coll.Slice "Foo" "bar" "baz" }} Hello, {{ . }}! {{- end }} will produce this: Hello, Foo! Hello, bar! Hello, baz! ### Suppressing trailing newlines This code: {{ range coll.Slice "Foo" "bar" "baz" -}} Hello, {{ . }}! {{ end -}} yields this: Hello, Foo! Hello, bar! Hello, baz! ### Suppressing newlines altogether This code: {{- range coll.Slice "Foo" "bar" "baz" -}} Hello, {{ . }}! {{- end -}} Produces: Hello, Foo!Hello, bar!Hello, baz! Variables --------- The result of an action can be assigned to a _variable_, which is denoted by a leading `$` character, followed by an alphanumeric string. For example: {{ $w := "world" }} Hello, {{ print $w }}! Goodbye, {{ print $w }}. this will render as: Hello, world! Goodbye, world. Variables are declared with `:=`, and can be redefined with `=`: {{ $w := "hello" }} {{ $w = "goodbye" }} ### Variable scope A variable’s scope extends to the `end` action of the control structure (`if`, `with`, or `range`) in which it is declared, or to the end of the template if there is no such control structure. In other words, if a variable is initialized inside an `if` or `else` block, it cannot be referenced outside that block. This template will error with `undefined variable "$w"` since `$w` is only declared within `if`/`else` blocks: {{ if 1 }} {{ $w := "world" }} {{ else }} {{ $w := "earth" }} {{ end }} Hello, {{ print $w }}! Goodbye, {{ print $w }}. One way to approach this is to declare the variable first to an empty value: {{ $w := "" }} {{ if 1 }} {{ $w = "world" }} {{ else }} {{ $w = "earth" }} {{ end -}} Hello, {{ print $w }}! Goodbye, {{ print $w }}. Indexing arrays and maps ------------------------ Occasionally, multi-dimensional data such as arrays (lists, slices) and maps (dictionaries) are used in templates, sometimes through the use of [data sources](/datasources/) . Accessing values within these data can be done in a few ways which bear clarifying. ### Arrays Arrays are always numerically-indexed, and individual values can be accessed with the `index` built-in function: {{ index $array 0 }} To visit each value, you can loop through an array with `range`: {{ range $array }} do something with {{ . }}... {{ end }} If you need to keep track of the index number, you can declare two variables, separated by a comma: {{ range $index, $element := $array }} do something with {{ $element }}, which is number {{ $index }} {{ end }} ### Maps For maps, accessing values can be done with the `.` operator. Given a map `$map` with a key `foo`, you could access it like: {{ $map.foo }} However, this kind of access is limited to keys which are strings and contain only characters in the set (`a`\-`z`,`A`\-`Z`,`_`,`1`\-`9`), and which do not begin with a number. If the key doesn’t conform to these rules, you can use the `index` built-in function instead: {{ index $map "foo-bar" }} `index` also supports nested keys and can be combined with other functions as such: {{ index $map "foo" (env.Getenv "BAR") "baz" ... }} **Note:** _while `index` can be used to access awkwardly-named values in maps, it behaves differently than the `.` operator. If the key doesn’t exist, `index` will simply not return a value, while `.` will error._ And, similar to arrays, you can loop through a map with the `range`: {{ range $map }} The value is {{ . }} {{ end }} Or if you need keys as well: {{ range $key, $value := $map }} {{ $key }}'s value is: {{ $value }} {{ end }} Functions --------- Almost all of gomplate’s utility is provided as _functions._ These are key words (like `print` in the previous examples) that perform some action. See the [functions documentation](/functions/) for more information. The Context ----------- Go templates are always executed with a _context_. You can reference the context with the `.` (period) character, and you can set the context in a block with the `with` action. Like so: $ gomplate -i '{{ with "foo" }}The context is {{ . }}{{ end }}' The context is foo Templates rendered by gomplate always have a _default_ context. You can populate the default context from data sources with the [`--context`/`c`](/usage/#--context-c) flag. The special context item [`.Env`](#env) is available for referencing the system’s environment variables. _Note:_ The initial context (`.`) is always available as the variable `$`, so the initial context is always available, even when shadowed with `range` or `with` blocks: $ echo '{"bar":"baz"}' | gomplate -c .=stdin:///in.json -i 'context is: {{ . }} {{ with "foo" }}now context is {{ . }} but the original context is still {{ $ }} {{ end }}' context is: map[bar:baz] now context is foo but the original context is still map[bar:baz] Nested templates ---------------- Gomplate supports nested templates, using Go’s `template` action. These can be defined in-line with the `define` action, or external data can be used with the [`--template`/`-t`](/usage/#--template-t) flag. Note that nested templates do _not_ have access to gomplate’s default [context](#the-context) (though it can be explicitly provided to the `template` action). ### In-line templates To define a nested template in-line, you can use the `define` action. {{ define "T1" -}} Hello {{ . }}! {{- end -}} {{ template "T1" "World" }} {{ template "T1" }} {{ template "T1" "everybody" }} This renders as: Hello World! Hello ! Hello everybody! ### External templates To define a nested template from an external source such as a file, use the [`--template`/`-t`](/usage/#--template-t) flag. _hello.t:_ Hello {{ . }}! $ gomplate -t hello=hello.t -i '{{ template "hello" "World" }} {{ template "hello" .Env.USER }}' Hello World! Hello hairyhenderson! `.Env` ------ You can easily access environment variables with `.Env`, but there’s a catch: if you try to reference an environment variable that doesn’t exist, parsing will fail and `gomplate` will exit with an error condition. For example: $ gomplate -i 'the user is {{ .Env.USER }}' the user is hairyhenderson $ gomplate -i 'this will fail: {{ .Env.BOGUS }}' this will fail: template: :1:23: executing "" at <.Env.BOGUS>: map has no entry for key "BOGUS" Sometimes, this behaviour is desired; if the output is unusable without certain strings, this is a sure way to know that variables are missing! If you want different behaviour, try [`getenv`](/functions/env/#envgetenv) . --- # Configuration - gomplate documentation Configuration ============= In addition to [command-line arguments](/usage/) , gomplate supports the use of configuration files to control its behaviour. Using a file for configuration can be useful especially when rendering templates that use multiple datasources, plugins, nested templates, etc… In situations where teams share templates, it can be helpful to commit config files into the team’s source control system. By default, gomplate will look for a file `.gomplate.yaml` in the current working directory, but this path can be altered with the [`--config`](/usage/#--config) command-line argument, or the `GOMPLATE_CONFIG` environment variable. ### Configuration precedence [Command-line arguments](/usage/) will always take precedence over settings in a config file. In the cases where configuration can be altered with an environment variable, the config file will take precedence over environment variables. So, if the `leftDelim` setting is configured in 3 ways: $ export GOMPLATE_LEFT_DELIM=:: $ echo "leftDelim: ((" > .gomplate.yaml $ gomplate --left-delim "<<" The delimiter will be `<<`. File format ----------- Currently, gomplate supports config files written in [YAML](http://yaml.org) syntax, though other structured formats may be supported in future (please [file an issue](https://github.com/hairyhenderson/gomplate/issues/new) if this is important to you!) Roughly all of the [command-line arguments](/usage/) are able to be set in a config file, with the exception of `--help`, `--verbose`, and `--version`. Some environment variable based settings not configurable on the command-line are also supported in config files. Most of the configuration names are similar, though instead of using `kebab-case`, multi-word names are rendered as `camelCase`. Here is an example of a simple config file: inputDir: in/ outputDir: out/ datasources: local: url: file:///tmp/data.json remote: url: https://example.com/api/v1/data header: Authorization: ["Basic aGF4MHI6c3dvcmRmaXNoCg=="] plugins: dostuff: /usr/local/bin/stuff.sh `chmod` ------- See [`--chmod`](/usage/#--chmod) . Sets the output file mode. `context` --------- See [`--context`](/usage/#--context-c) . Add data sources to the default context. This is a nested structure that includes the URL for the data source and the optional HTTP header to send. For example: context: data: url: https://example.com/api/v1/data header: Authorization: ["Basic aGF4MHI6c3dvcmRmaXNoCg=="] stuff: url: stuff.yaml This adds two datasources to the context: `data` and `stuff`, and when the `data` source is retrieved, an `Authorization` header will be sent with the given value. Note that the `.` name can also be used to set the entire context: context: .: url: data.toml `datasources` ------------- See [`--datasource`](/usage/#--datasource-d) . Define data sources. This is a nested structure that includes the URL for the data source and the optional HTTP header to send. For example: datasources: data: url: https://example.com/api/v1/data header: Authorization: ["Basic aGF4MHI6c3dvcmRmaXNoCg=="] stuff: url: stuff.yaml This defines two datasources: `data` and `stuff`, and when the `data` source is used, an `Authorization` header will be sent with the given value. `excludes` ---------- See [`--exclude` and `--include`](/usage/#--exclude-and---include) . This is an array of exclude patterns, used in conjunction with [`inputDir`](#inputdir) . Note that there is no `includes`, instead you can specify negative exclusions by prefixing the patterns with `!`. excludes: - '*.txt' - '!include-this.txt' This will skip all files with the extension `.txt`, except for files named `include-this.txt`, which will be processed. `excludeProcessing` ------------------- See [`--exclude-processing`](/usage/#--exclude-processing) . This is an array of exclude patterns, used in conjunction with [`inputDir`](#inputdir) . The matching files will be copied to the output directory without template rendering. excludeProcessing: - '*.jpg' This will copy all files with the extension `.jpg` to the output directory. `execPipe` ---------- See [`--exec-pipe`](/usage/#--exec-pipe) . Use the rendered output as the [`postExec`](#postexec) command’s standard input. Must be used in conjunction with [`postExec`](#postexec) , and will override any [`outputFiles`](#outputfiles) settings. `experimental` -------------- See [`--experimental`](/usage/#--experimental) . Can also be set with the `GOMPLATE_EXPERIMENTAL=true` environment variable. Some functions and features are provided for early feedback behind the `experimental` configuration option. These features may change before being permanently enabled, and [feedback](https://github.com/hairyhenderson/gomplate/issues/new) is requested from early adopters! Experimental functions are marked in the documentation with an _"(experimental)"_ annotation. experimental: true `in` ---- See [`--in`/`-i`](/usage/#--file-f---in-i-and---out-o) . Provide the input template inline. Note that unlike the `--in`/`-i` commandline argument, there are no shell-imposed length limits. A simple example: in: hello to {{ .Env.USER }} A multi-line example (see [https://yaml-multiline.info/](https://yaml-multiline.info/) for more about multi-line string syntax in YAML): in: | A longer multi-line document: {{- range .foo }} {{ .bar }} {{ end }} May not be used with `inputDir` or `inputFiles`. `inputDir` ---------- See [`--input-dir`](/usage/#--input-dir-and---output-dir) . The directory containing input template files. All files contained within will be processed recursively. Must be used with [`outputDir`](#outputdir) or [`outputMap`](#outputmap) . Can also be used with [`excludes`](#excludes) . inputDir: templates/ outputDir: out/ May not be used with `in` or `inputFiles`. `inputFiles` ------------ See [`--file`/`-f`](/usage/#--file-f---in-i-and---out-o) . An array of input template paths. The special value `-` means `Stdin`. Multiple values can be set, but there must be a corresponding number of `outputFiles` entries present. inputFiles: - first.tmpl - second.tmpl outputFiles: - first.out - second.out Flow style can be more compact: inputFiles: ['-'] outputFiles: ['-'] May not be used with `in` or `inputDir`. `leftDelim` ----------- See [`--left-delim`](/usage/#overriding-the-template-delimiters) . Overrides the left template delimiter. leftDelim: '%{' `missingKey` ------------ See [`--missing-key`](/usage/#--missing-key) . Control the behavior during execution if a map is indexed with a key that is not present in the map missingKey: error `outputDir` ----------- See [`--output-dir`](/usage/#--input-dir-and---output-dir) . The directory to write rendered output files. Must be used with [`inputDir`](#inputdir) . If the directory is missing, it will be created with the same permissions as the `inputDir`. inputDir: templates/ outputDir: out/ May not be used with `outputFiles`. `outputFiles` ------------- See [`--out`/`-o`](/usage/#--file-f---in-i-and---out-o) . An array of output file paths. The special value `-` means `Stdout`. Multiple values can be set, but there must be a corresponding number of `inputFiles` entries present. If any of the parent directories are missing, they will be created with the same permissions as the input directories. inputFiles: - first.tmpl - second.tmpl outputFiles: - first.out - second.out Can also be used with [`in`](#in) : in: >- hello, world! outputFiles: [ hello.txt ] May not be used with `inputDir`. `outputMap` ----------- See [`--output-map`](/usage/#--output-map) . Must be used with [`inputDir`](#inputdir) . inputDir: in/ outputMap: | out/{{ .in | strings.ReplaceAll ".yaml.tmpl" ".yaml" }} `plugins` --------- See [`--plugin`](/usage/#--plugin) . A map that configures custom functions for use in the templates. The key is the name of the function, and the value configures the plugin. The value is a map containing the command (`cmd`) and the options `pipe` (boolean) and `timeout` (duration). A list of optional arguments to always pass to the plugin can be set with `args` (array of strings). Alternatively, the value can be a string, which sets only `cmd`. in: '{{ "world" | figlet | lolcat }}' plugins: figlet: cmd: /usr/local/bin/figlet args: - oh - hello pipe: true timeout: 1s lolcat: /home/hairyhenderson/go/bin/lolcat ### `cmd` The path to the plugin executable (or script) to run. ### `args` An array of optional arguments to always pass to the plugin. These arguments will be passed _before_ any arguments provided in the template. For example: plugins: echo: cmd: /bin/echo args: - foo - bar With this template: {{ echo "baz" }} Will result the command being called like this: $ /bin/echo foo bar baz ### `pipe` Whether to pipe the final argument of the template function to the plugin’s Stdin, or provide as a separate argument. For example, given a `myfunc` plugin with a `cmd` of `/bin/myfunc`: With this template: {{ print "bar" | myfunc "foo" }} If `pipe` is `true`, the plugin executable will receive the input `"bar"` as its Stdin, like this shell command: $ echo -n "bar" | /bin/myfunc "foo" If `pipe` is `false` (the default), the plugin executable will receive the input `"bar"` as its last argument, like this shell command: $ /bin/myfunc "foo" "bar" _Note:_ in a chained pipeline (e.g. `{{ foo | bar }}`), the result of each command is passed as the final argument of the next, and so the template above could be written as `{{ myfunc "foo" "bar" }}`. ### `timeout` The plugin’s timeout. After this time, the command will be terminated and the template function will return an error. The value must be a valid [duration](/functions/time/#timeparseduration) such as `1s`, `1m`, `1h`, The default is `5s`. `pluginTimeout` --------------- See [`--plugin`](/usage/#--plugin) . Sets the timeout for all configured plugins. Overrides the default of `5s`. After this time, plugin commands will be killed. The value must be a valid [duration](/functions/time/#timeparseduration) such as `10s` or `3m`. plugins: figlet: /usr/local/bin/figlet pluginTimeout: 500ms `postExec` ---------- See [post-template command execution](/usage/#post-template-command-execution) . Configures a command to run after the template is rendered. See also [`execPipe`](#execpipe) for piping output directly into the `postExec` command. `rightDelim` ------------ See [`--right-delim`](/usage/#overriding-the-template-delimiters) . Overrides the right template delimiter. rightDelim: '))' `templates` ----------- See [`--template`/`-t`](/usage/#--template-t) . templates: t: url: file:///foo/bar/helloworld.tmpl remote: url: https://example.com/api/v1/someremotetemplate header: Authorization: ["Basic aGF4MHI6c3dvcmRmaXNoCg=="] --- # Functions - gomplate documentation Functions ========= Almost all of gomplate’s utility is provided as _functions._ These are key words that perform some action. For example, the [`base64.Encode`](/functions/base64/#base64encode) function will encode some input string as a base-64 string: The word is {{ base64.Encode "swordfish" }} renders as: The word is c3dvcmRmaXNo Built-ins --------- Go’s [`text/template`](https://golang.org/pkg/text/template/) language provides a number of built-in functions, operators, and actions that can be used in templates. ### Built-in functions Here is a list of the built-in functions, but see [the documentation](https://golang.org/pkg/text/template/#hdr-Functions) for full details: * `and`, `or`, `not`: Returns boolean AND/OR/NOT of the argument(s). * `call`: Returns the result of calling a function argument. * `html`, `js`, `urlquery`: Safely escapes input for inclusion in HTML, JavaScript, and URL query strings. * `index`: Returns the referenced element of an array/slice, string, or map. See also [Arrays](/syntax/#arrays) and [Maps](/syntax/#maps) . * `len`: Returns the length of the argument. * `print`, `printf`, `println`: Aliases for Go’s [`fmt.Print`](https://golang.org/pkg/fmt/#Print) , [`fmt.Printf`](https://golang.org/pkg/fmt/#Printf) , and [`fmt.Println`](https://golang.org/pkg/fmt/#Println) functions. See the [format documentation](https://golang.org/pkg/fmt/#hdr-Printing) for details on `printf`’s format syntax. ### Operators And the following comparison operators are also supported: * `eq`: Equal (`==`) * `ne`: Not-equal (`!=`) * `lt`: Less than (`<`) * `le`: Less than or equal to (`<=`) * `gt`: Greater than (`>`) * `ge`: Greater than or equal to (`>=`) ### Actions There are also a few _actions_, which are used for control flow and other purposes. See [the documentation](https://golang.org/pkg/text/template/#hdr-Actions) for details on these: * `if`/`else`/`else if`: Conditional control flow. * `with`/`else`: Conditional execution with assignment. * `range`: Looping control flow. See discussion in the [Arrays](/syntax/#arrays) and [Maps](/syntax/#maps) sections. * `break`: The innermost `range` loop is ended early, stopping the current iteration and bypassing all remaining iterations. * `continue`: The current iteration of the innermost `range` loop is stopped, and the loop starts the next iteration. * `template`: Include the output of a named template. See the [Nested templates](/syntax/#nested-templates) section for more details, and the [`tmpl`](/functions/tmpl/) namespace for more flexible versions of `template`. * `define`: Define a named nested template. See the [Nested templates](/syntax/#nested-templates) section for more details. * `block`: Shorthand for `define` followed immediately by `template`. gomplate functions ------------------ gomplate provides over 200 functions not found in the standard library. These are grouped into namespaces, and documented on the following pages: * [aws functions](/functions/aws/) * [base64 functions](/functions/base64/) * [collection functions](/functions/coll/) * [conversion functions](/functions/conv/) * [crypto functions](/functions/crypto/) * [data functions](/functions/data/) * [env functions](/functions/env/) * [file functions](/functions/file/) * [filepath functions](/functions/filepath/) * [gcp functions](/functions/gcp/) * [math functions](/functions/math/) * [net functions](/functions/net/) * [path functions](/functions/path/) * [random functions](/functions/random/) * [regexp functions](/functions/regexp/) * [semver functions](/functions/semver/) * [sockaddr functions](/functions/sockaddr/) * [strings functions](/functions/strings/) * [template functions](/functions/tmpl/) * [test functions](/functions/test/) * [time functions](/functions/time/) * [uuid functions](/functions/uuid/) --- # aws functions - gomplate documentation aws functions ============= The functions in the `aws` namespace interface with various Amazon Web Services APIs to make it possible for a template to render differently based on the AWS environment and metadata. ### Configuring AWS A number of environment variables can be used to control how gomplate communicates with AWS APIs. A few are documented here for convenience. See [the `aws-sdk-go` documentation](https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html) for details. | Environment Variable | Description | | --- | --- | | `AWS_ANON` | Set to `true` when accessing services that do not need authentication, such as with public S3 buckets. Not part of the AWS SDK. | | `AWS_TIMEOUT` | _(Default `500`)_ Adjusts timeout for API requests, in milliseconds. Not part of the AWS SDK. | | `AWS_PROFILE` | Profile name the SDK should use when loading shared config from the configuration files. If not provided `default` will be used as the profile name. | | `AWS_REGION` | Specifies where to send requests. See [this list](https://docs.aws.amazon.com/general/latest/gr/rande.html)
. Note that the region must be set for AWS functions to work correctly, either through this variable, through a configuration profile, or by running on an EC2 instance. | | `AWS_EC2_METADATA_SERVICE_ENDPOINT` | _(Default `http://169.254.169.254`)_ Sets the base address of the instance metadata service. | | `AWS_META_ENDPOINT` _(Deprecated)_ | _(Default `http://169.254.169.254`)_ Sets the base address of the instance metadata service. Use `AWS_EC2_METADATA_SERVICE_ENDPOINT` instead. | `aws.EC2Meta` ------------- **Alias:** `ec2meta` Queries AWS [EC2 Instance Metadata](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) for information. This only retrieves data in the `meta-data` path – for data in the `dynamic` path use `aws.EC2Dynamic`. For times when running outside EC2, or when the metadata API can’t be reached, a `default` value can be provided. _Added in gomplate [v1.8.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.8.0) _ ### Usage aws.EC2Meta key [default] ### Arguments | name | description | | --- | --- | | `key` | _(required)_ the metadata key to query | | `default` | _(optional)_ the default value | ### Examples $ echo '{{aws.EC2Meta "instance-id"}}' | gomplate i-12345678 `aws.EC2Dynamic` ---------------- **Alias:** `ec2dynamic` Queries AWS [EC2 Instance Dynamic Metadata](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) for information. This only retrieves data in the `dynamic` path – for data in the `meta-data` path use `aws.EC2Meta`. For times when running outside EC2, or when the metadata API can’t be reached, a `default` value can be provided. _Added in gomplate [v1.8.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.8.0) _ ### Usage aws.EC2Dynamic key [default] ### Arguments | name | description | | --- | --- | | `key` | _(required)_ the dynamic metadata key to query | | `default` | _(optional)_ the default value | ### Examples $ echo '{{ (aws.EC2Dynamic "instance-identity/document" | json).region }}' | gomplate us-east-1 `aws.EC2Region` --------------- **Alias:** `ec2region` Queries AWS to get the region. An optional default can be provided, or returns `unknown` if it can’t be determined for some reason. _Added in gomplate [v1.8.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.8.0) _ ### Usage aws.EC2Region [default] ### Arguments | name | description | | --- | --- | | `default` | _(optional)_ the default value | ### Examples _In EC2_ $ echo '{{ aws.EC2Region }}' | ./gomplate us-east-1 _Not in EC2_ $ echo '{{ aws.EC2Region }}' | ./gomplate unknown $ echo '{{ aws.EC2Region "foo" }}' | ./gomplate foo `aws.EC2Tag` ------------ **Alias:** `ec2tag` Queries the AWS EC2 API to find the value of the given [user-defined tag](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) . An optional default can be provided. _Added in gomplate [v3.8.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.8.0) _ ### Usage aws.EC2Tag tag [default] ### Arguments | name | description | | --- | --- | | `tag` | _(required)_ the tag to query | | `default` | _(optional)_ the default value | ### Examples $ echo 'This server is in the {{ aws.EC2Tag "Account" }} account.' | ./gomplate foo $ echo 'I am a {{ aws.EC2Tag "classification" "meat popsicle" }}.' | ./gomplate I am a meat popsicle. `aws.EC2Tags` ------------- **Alias:** `ec2tags` Queries the AWS EC2 API to find all the tags/values [user-defined tag](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) . _Added in gomplate [v3.8.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.8.0) _ ### Usage aws.EC2Tags ### Arguments | name | description | | --- | --- | ### Examples echo '{{ range $key, $value := aws.EC2Tags }}{{(printf "%s=%s\n" $key $value)}}{{ end }}' | ./gomplate Description=foo Name=bar svc:name=foobar `aws.KMSEncrypt` ---------------- Encrypt an input string with the AWS Key Management Service (KMS). At most 4kb (4096 bytes) of data may be encrypted. The resulting ciphertext will be base-64 encoded. The `keyID` parameter is used to reference the Customer Master Key to use, and can be: * the key’s ID (e.g. `1234abcd-12ab-34cd-56ef-1234567890ab`) * the key’s ARN (e.g. `arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab`) * the alias name (aliases must be prefixed with `alias/`, e.g. `alias/ExampleAlias`) * the alias ARN (e.g. `arn:aws:kms:us-east-2:111122223333:alias/ExampleAlias`) For information on creating keys, see [_Creating Keys_](https://docs.aws.amazon.com/kms/latest/developerguide/create-keys.html) See [the AWS documentation](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) for more details. See also [`aws.KMSDecrypt`](#awskmsdecrypt) . _Added in gomplate [v4.0.0](https://github.com/hairyhenderson/gomplate/releases/tag/v4.0.0) _ ### Usage aws.KMSEncrypt keyID input input | aws.KMSEncrypt keyID ### Arguments | name | description | | --- | --- | | `keyID` | _(required)_ the ID of the Customer Master Key (CMK) to use for encryption | | `input` | _(required)_ the string to encrypt | ### Examples $ export CIPHER=$(gomplate -i '{{ aws.KMSEncrypt "alias/gomplate" "hello world" }}') $ gomplate -i '{{ env.Getenv "CIPHER" | aws.KMSDecrypt }}' `aws.KMSDecrypt` ---------------- Decrypt ciphertext that was encrypted with the AWS Key Management Service (KMS). The ciphertext must be base-64 encoded. See [the AWS documentation](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) for more details. See also [`aws.KMSEncrypt`](#awskmsencrypt) . _Added in gomplate [v3.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.4.0) _ ### Usage aws.KMSDecrypt input input | aws.KMSDecrypt ### Arguments | name | description | | --- | --- | | `input` | _(required)_ the base-64 encoded ciphertext to decrypt | ### Examples $ export CIPHER=$(gomplate -i '{{ aws.KMSEncrypt "alias/gomplate" "hello world" }}') $ gomplate -i '{{ env.Getenv "CIPHER" | aws.KMSDecrypt }}' `aws.Account` ------------- Returns the currently-authenticated AWS account ID number. Wraps the [STS GetCallerIdentity API](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetCallerIdentity.html) See also [`aws.UserID`](#awsuserid) and [`aws.ARN`](#awsarn) . _Added in gomplate [v3.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.4.0) _ ### Usage aws.Account ### Examples $ gomplate -i 'My account is {{ aws.Account }}' My account is 123456789012 `aws.ARN` --------- Returns the AWS ARN (Amazon Resource Name) associated with the current authentication credentials. Wraps the [STS GetCallerIdentity API](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetCallerIdentity.html) See also [`aws.UserID`](#awsuserid) and [`aws.Account`](#awsaccount) . _Added in gomplate [v3.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.4.0) _ ### Usage aws.ARN ### Examples $ gomplate -i 'Calling from {{ aws.ARN }}' Calling from arn:aws:iam::123456789012:user/Alice `aws.UserID` ------------ Returns the unique identifier of the calling entity. The exact value depends on the type of entity making the call. The values returned are those listed in the `aws:userid` column in the [Principal table](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_variables.html#principaltable) found on the Policy Variables reference page in the IAM User Guide. Wraps the [STS GetCallerIdentity API](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetCallerIdentity.html) See also [`aws.ARN`](#awsarn) and [`aws.Account`](#awsaccount) . _Added in gomplate [v3.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.4.0) _ ### Usage aws.UserID ### Examples $ gomplate -i 'I am {{ aws.UserID }}' I am AIDACKCEVSQ6C2EXAMPLE --- # collection functions - gomplate documentation collection functions ==================== These functions help manipulate and query collections of data, like lists (slices, or arrays) and maps (dictionaries). #### Implementation Note For the functions that return an array, a Go `[]any` is returned, regardless of whether or not the input was a different type. `coll.Dict` ----------- **Alias:** `dict` Dict is a convenience function that creates a map with string keys. Provide arguments as key/value pairs. If an odd number of arguments is provided, the last is used as the key, and an empty string is set as the value. All keys are converted to strings. This function is equivalent to [Sprig’s `dict`](http://masterminds.github.io/sprig/dicts.html#dict) function, as used in [Helm templates](https://helm.sh/docs/chart_template_guide/functions_and_pipelines/) . For creating more complex maps, see [`data.JSON`](../data/#datajson) or [`data.YAML`](../data/#datayaml) . For creating arrays, see [`coll.Slice`](#collslice-_deprecated_) . _Added in gomplate [v3.2.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.2.0) _ ### Usage coll.Dict in... ### Arguments | name | description | | --- | --- | | `in...` | _(required)_ The key/value pairs | ### Examples $ gomplate -i '{{ coll.Dict "name" "Frank" "age" 42 | data.ToYAML }}' age: 42 name: Frank $ gomplate -i '{{ dict 1 2 3 | toJSON }}' {"1":2,"3":""} $ cat < 400 )].title` }}' -c books=https://openlibrary.org/subjects/fantasy.json [Alice's Adventures in Wonderland Gulliver's Travels] `coll.JQ` --------- **Alias:** `jq` Filters an input object or list using the [jq](https://stedolan.github.io/jq/) language, as implemented by [gojq](https://github.com/itchyny/gojq) . Any JSON datatype may be used as input (NOTE: strings are not JSON-parsed but passed in as is). If the expression results in multiple items (no matter if streamed or as an array) they are wrapped in an array. Otherwise a single item is returned (even if resulting in an array with a single contained element). JQ filter expressions can be tested at [https://jqplay.org/](https://jqplay.org/) See also: * [jq manual](https://stedolan.github.io/jq/manual/) * [gojq differences to jq](https://github.com/itchyny/gojq#difference-to-jq) _Added in gomplate [v4.0.0](https://github.com/hairyhenderson/gomplate/releases/tag/v4.0.0) _ ### Usage coll.JQ expression in in | coll.JQ expression ### Arguments | name | description | | --- | --- | | `expression` | _(required)_ The JQ expression | | `in` | _(required)_ The object or list to query | ### Examples $ gomplate \ -i '{{ .books | jq `[.works[]|{"title":.title,"authors":[.authors[].name],"published":.first_publish_year}][0]` }}' \ -c books=https://openlibrary.org/subjects/fantasy.json map[authors:[Lewis Carroll] published:1865 title:Alice's Adventures in Wonderland] `coll.Keys` ----------- **Alias:** `keys` Return a list of keys in one or more maps. The keys will be ordered first by map position (if multiple maps are given), then alphabetically. See also [`coll.Values`](#collvalues) . _Added in gomplate [v3.2.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.2.0) _ ### Usage coll.Keys in... in... | coll.Keys ### Arguments | name | description | | --- | --- | | `in...` | _(required)_ the maps | ### Examples $ gomplate -i '{{ coll.Keys (dict "foo" 1 "bar" 2) }}' [bar foo] $ gomplate -i '{{ $map1 := dict "foo" 1 "bar" 2 -}}{{ $map2 := dict "baz" 3 "qux" 4 -}}{{ coll.Keys $map1 $map2 }}' [bar foo baz qux] `coll.Values` ------------- **Alias:** `values` Return a list of values in one or more maps. The values will be ordered first by map position (if multiple maps are given), then alphabetically by key. See also [`coll.Keys`](#collkeys) . _Added in gomplate [v3.2.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.2.0) _ ### Usage coll.Values in... in... | coll.Values ### Arguments | name | description | | --- | --- | | `in...` | _(required)_ the maps | ### Examples $ gomplate -i '{{ coll.Values (dict "foo" 1 "bar" 2) }}' [2 1] $ gomplate -i '{{ $map1 := dict "foo" 1 "bar" 2 -}}{{ $map2 := dict "baz" 3 "qux" 4 -}}{{ coll.Values $map1 $map2 }}' [2 1 3 4] `coll.Append` ------------- **Alias:** `append` Append a value to the end of a list. _Note that this function does not change the given list; it always produces a new one._ See also [`coll.Prepend`](#collprepend) . _Added in gomplate [v3.2.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.2.0) _ ### Usage coll.Append value list... list... | coll.Append value ### Arguments | name | description | | --- | --- | | `value` | _(required)_ the value to add | | `list...` | _(required)_ the slice or array to append to | ### Examples $ gomplate -i '{{ coll.Slice 1 1 2 3 | append 5 }}' [1 1 2 3 5] `coll.Prepend` -------------- **Alias:** `prepend` Prepend a value to the beginning of a list. _Note that this function does not change the given list; it always produces a new one._ See also [`coll.Append`](#collappend) . _Added in gomplate [v3.2.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.2.0) _ ### Usage coll.Prepend value list... list... | coll.Prepend value ### Arguments | name | description | | --- | --- | | `value` | _(required)_ the value to add | | `list...` | _(required)_ the slice or array to prepend to | ### Examples $ gomplate -i '{{ coll.Slice 4 3 2 1 | prepend 5 }}' [5 4 3 2 1] `coll.Uniq` ----------- **Alias:** `uniq` Remove any duplicate values from the list, without changing order. _Note that this function does not change the given list; it always produces a new one._ _Added in gomplate [v3.2.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.2.0) _ ### Usage coll.Uniq list list | coll.Uniq ### Arguments | name | description | | --- | --- | | `list` | _(required)_ the input list | ### Examples $ gomplate -i '{{ coll.Slice 1 2 3 2 3 4 1 5 | uniq }}' [1 2 3 4 5] `coll.Flatten` -------------- **Alias:** `flatten` Flatten a nested list. Defaults to completely flattening all nested lists, but can be limited with `depth`. _Note that this function does not change the given list; it always produces a new one._ _Added in gomplate [v3.6.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.6.0) _ ### Usage coll.Flatten [depth] list list | coll.Flatten [depth] ### Arguments | name | description | | --- | --- | | `depth` | _(optional)_ maximum depth of nested lists to flatten. Omit or set to `-1` for infinite depth. | | `list` | _(required)_ the input list | ### Examples $ gomplate -i '{{ "[[1,2],[],[[3,4],[[[5],6],7]]]" | jsonArray | flatten }}' [1 2 3 4 5 6 7] $ gomplate -i '{{ coll.Flatten 2 ("[[1,2],[],[[3,4],[[[5],6],7]]]" | jsonArray) }}' [1 2 3 4 [[5] 6] 7] `coll.Reverse` -------------- **Alias:** `reverse` Reverse a list. _Note that this function does not change the given list; it always produces a new one._ _Added in gomplate [v3.2.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.2.0) _ ### Usage coll.Reverse list list | coll.Reverse ### Arguments | name | description | | --- | --- | | `list` | _(required)_ the list to reverse | ### Examples $ gomplate -i '{{ coll.Slice 4 3 2 1 | reverse }}' [1 2 3 4] `coll.Sort` ----------- **Alias:** `sort` Sort a given list. Uses the natural sort order if possible. For inputs that are not sortable (either because the elements are of different types, or of an un-sortable type), the input will simply be returned, unmodified. Maps and structs can be sorted by a named key. _Note that this function does not modify the input._ _Added in gomplate [v3.2.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.2.0) _ ### Usage coll.Sort [key] list list | coll.Sort [key] ### Arguments | name | description | | --- | --- | | `key` | _(optional)_ the key to sort by, for lists of maps or structs | | `list` | _(required)_ the slice or array to sort | ### Examples $ gomplate -i '{{ coll.Slice "foo" "bar" "baz" | coll.Sort }}' [bar baz foo] $ gomplate -i '{{ sort (coll.Slice 3 4 1 2 5) }}' [1 2 3 4 5] $ cat < in.json [{"a": "foo", "b": 1}, {"a": "bar", "b": 8}, {"a": "baz", "b": 3}] EOF $ gomplate -d in.json -i '{{ range (include "in" | jsonArray | coll.Sort "b") }}{{ print .a "\n" }}{{ end }}' foo baz bar `coll.Merge` ------------ **Alias:** `merge` Merge maps together by overriding src with dst. In other words, the src map can be configured the “default” map, whereas the dst map can be configured the “overrides”. Many source maps can be provided. Precedence is in left-to-right order. _Note that this function does not modify the input._ _Added in gomplate [v3.2.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.2.0) _ ### Usage coll.Merge dst srcs... srcs... | coll.Merge dst ### Arguments | name | description | | --- | --- | | `dst` | _(required)_ the map to merge _into_ | | `srcs...` | _(required)_ the map (or maps) to merge _from_ | ### Examples $ gomplate -i '{{ $default := dict "foo" 1 "bar" 2}} {{ $config := dict "foo" 8 }} {{ merge $config $default }}' map[bar:2 foo:8] $ gomplate -i '{{ $dst := dict "foo" 1 "bar" 2 }} {{ $src1 := dict "foo" 8 "baz" 4 }} {{ $src2 := dict "foo" 3 "bar" 5 }} {{ coll.Merge $dst $src1 $src2 }}' map[foo:1 bar:2 baz:4] `coll.Pick` ----------- Given a map, returns a new map with any entries that have the given keys. The keys can either be separate arguments, or a slice (since v4.0.0). This is the inverse of [`coll.Omit`](#collomit) . _Note that this function does not modify the input._ _Added in gomplate [v3.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.7.0) _ ### Usage coll.Pick keys... map map | coll.Pick keys... ### Arguments | name | description | | --- | --- | | `keys...` | _(required)_ the keys (strings) to match | | `map` | _(required)_ the map to pick from | ### Examples $ gomplate -i '{{ $data := dict "foo" 1 "bar" 2 "baz" 3 }} {{ coll.Pick "foo" "baz" $data }}' map[baz:3 foo:1] $ gomplate -i '{{ $data := dict "foo" 1 "bar" 2 "baz" 3 }} {{ $keys := coll.Slice "foo" "baz" }} {{ coll.Pick $keys $data }}' map[baz:3 foo:1] `coll.Omit` ----------- Given a map, returns a new map without any entries that have the given keys. The keys can either be separate arguments, or a slice (since v4.0.0). This is the inverse of [`coll.Pick`](#collpick) . _Note that this function does not modify the input._ _Added in gomplate [v3.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.7.0) _ ### Usage coll.Omit keys... map map | coll.Omit keys... ### Arguments | name | description | | --- | --- | | `keys...` | _(required)_ the keys (strings) to match | | `map` | _(required)_ the map to omit from | ### Examples $ gomplate -i '{{ $data := dict "foo" 1 "bar" 2 "baz" 3 }} {{ coll.Omit "foo" "baz" $data }}' map[bar:2] $ gomplate -i '{{ $data := dict "foo" 1 "bar" 2 "baz" 3 }} {{ $keys := coll.Slice "foo" "baz" }} {{ coll.Omit $keys $data }}' map[bar:2] `coll.Set` ---------- **Alias:** `set` Sets the given key to the given value in the given map. The map is modified in place, and the modified map is returned. _Added in gomplate [v4.0.0](https://github.com/hairyhenderson/gomplate/releases/tag/v4.0.0) _ ### Usage coll.Set key value map map | coll.Set key value ### Arguments | name | description | | --- | --- | | `key` | _(required)_ the key (string) to set | | `value` | _(required)_ the value to set | | `map` | _(required)_ the map to modify | ### Examples $ gomplate -i '{{ $data := dict "foo" 1 "bar" 2 }} {{ coll.Set "baz" 3 $data }}' map[bar:2 baz:3 foo:1] $ gomplate -i '{{ dict "foo" 1 | coll.Set "bar" 2 }}' map[bar:2 foo:1] `coll.Unset` ------------ **Alias:** `unset` Deletes the element with the specified key in the given map. If there is no such element, the map is returned unchanged. The map is modified in place, and the modified map is returned. _Added in gomplate [v4.0.0](https://github.com/hairyhenderson/gomplate/releases/tag/v4.0.0) _ ### Usage coll.Unset key map map | coll.Unset key ### Arguments | name | description | | --- | --- | | `key` | _(required)_ the key (string) to unset | | `map` | _(required)_ the map to modify | ### Examples $ gomplate -i '{{ $data := dict "foo" 1 "bar" 2 "baz" 3 }} {{ coll.Unset "bar" $data }}' map[baz:3 foo:1] $ gomplate -i '{{ dict "foo" 1 "bar" 2 | coll.Unset "bar" }}' map[foo:1] --- # base64 functions - gomplate documentation base64 functions ================ `base64.Encode` --------------- Encode data as a Base64 string. Specifically, this uses the standard Base64 encoding as defined in [RFC4648 §4](https://tools.ietf.org/html/rfc4648#section-4) (and _not_ the URL-safe encoding). _Added in gomplate [v1.8.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.8.0) _ ### Usage base64.Encode input input | base64.Encode ### Arguments | name | description | | --- | --- | | `input` | _(required)_ The data to encode. Can be a string, a byte array, or a buffer. Other types will be converted to strings first. | ### Examples $ gomplate -i '{{ base64.Encode "hello world" }}' aGVsbG8gd29ybGQ= $ gomplate -i '{{ "hello world" | base64.Encode }}' aGVsbG8gd29ybGQ= `base64.Decode` --------------- Decode a Base64 string. This supports both standard ([RFC4648 §4](https://tools.ietf.org/html/rfc4648#section-4) ) and URL-safe ([RFC4648 §5](https://tools.ietf.org/html/rfc4648#section-5) ) encodings. This function outputs the data as a string, so it may not be appropriate for decoding binary data. Use [`base64.DecodeBytes`](#base64decodebytes) for binary data. _Added in gomplate [v1.8.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.8.0) _ ### Usage base64.Decode input input | base64.Decode ### Arguments | name | description | | --- | --- | | `input` | _(required)_ The base64 string to decode | ### Examples $ gomplate -i '{{ base64.Decode "aGVsbG8gd29ybGQ=" }}' hello world $ gomplate -i '{{ "aGVsbG8gd29ybGQ=" | base64.Decode }}' hello world `base64.DecodeBytes` -------------------- Decode a Base64 string. This supports both standard ([RFC4648 §4](https://tools.ietf.org/html/rfc4648#section-4) ) and URL-safe ([RFC4648 §5](https://tools.ietf.org/html/rfc4648#section-5) ) encodings. This function outputs the data as a byte array, so it’s most useful for outputting binary data that will be processed further. Use [`base64.Decode`](#base64decode) to output a plain string. _Added in gomplate [v3.8.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.8.0) _ ### Usage base64.DecodeBytes input ### Arguments | name | description | | --- | --- | | `input` | _(required)_ The base64 string to decode | ### Examples $ gomplate -i '{{ base64.DecodeBytes "aGVsbG8gd29ybGQ=" }}' [104 101 108 108 111 32 119 111 114 108 100] $ gomplate -i '{{ "aGVsbG8gd29ybGQ=" | base64.DecodeBytes | conv.ToString }}' hello world --- # Datasources - gomplate documentation Datasources =========== 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. 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. Datasources can be defined with the [`--datasource`/`-d`](/usage/#--datasource-d) command-line flag or the [`defineDatasource`](/functions/data/#definedatasource) function, and referenced via an _alias_ inside the template, using a function such as [`datasource`](/functions/data/#datasource) or [`include`](/functions/data/#include) . Datasources can additionally be loaded into the [context](/syntax/#the-context) with the [`--context`/`-c`](/usage/#--context-c) command-line flag. 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. URL Format ---------- All datasources are defined with a [URL](https://tools.ietf.org/html/rfc3986) . As a refresher, a URL is made up of the following components: foo://userinfo@example.com:8042/over/there?name=ferret#nose \_/ \_______________________/\_________/ \_________/ \__/ | | | | | scheme authority path query fragment For our purposes, the _scheme_ and the _path_ components are especially important, though the other components are used by certain datasources for particular purposes. | component | purpose | | --- | --- | | _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` | | _authority_ | Used only by remote datasources, and can be omitted in some of those cases. Consists of _userinfo_ (`user:pass`), _host_, and _port_. | | _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. | | _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) | | _fragment_ | Used rarely for accessing a subset of the given path | ### Opaque URIs For some datasources, such as the [`merge`](#using-merge-datasources) , [`aws+sm`](#using-awssm-datasources) , and [`aws+smp`](#using-awssmp-datasources) schemes, opaque URIs can be used (rather than a hierarchical URL): scheme path query fragment | _____________________|__ _______|_ _| / \ / \ / \ / \ urn:example:animal:ferret:nose?name=ferret#nose The semantics of the different URI components are essentially the same as for hierarchical URLs (see above), but the _path_ component may not start with a `/` character. In gomplate’s usage, opaque URIs sometimes contain characters such as `|`, which require escaping with most shells. You may need to surround the datasource definition in quotes, or use the `\` escape character. Supported datasources --------------------- 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. | Type | URL Scheme(s) | Description | | --- | --- | --- | | [AWS Systems Manager Parameter Store](#using-awssmp-datasources) | `aws+smp` | [AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html)
is a hierarchically-organized key/value store which allows storage of text, lists, or encrypted secrets for retrieval by AWS resources | | [AWS Secrets Manager](#using-awssm-datasources) | `aws+sm` | [AWS Secrets Manager](https://aws.amazon.com/secrets-manager)
helps you protect secrets needed to access your applications, services, and IT resources. | | [Amazon S3](#using-s3-datasources) | `s3` | [Amazon S3](https://aws.amazon.com/s3/)
is a popular object storage service. | | [Consul](#using-consul-datasources) | `consul`, `consul+http`, `consul+https` | [HashiCorp Consul](https://consul.io)
provides (among many other features) a key/value store | | [Environment](#using-env-datasources) | `env` | Environment variables can be used as datasources - useful for testing | | [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. | | [Git](#using-git-datasources) | `git`, `git+file`, `git+http`, `git+https`, `git+ssh` | Files can be read from a local or remote git repository, at specific branches or tags. [Directory semantics](#directory-datasources)
are also supported. | | [Google Cloud Storage](#using-google-cloud-storage-gs-datasources) | `gs` | [Google Cloud Storage](https://cloud.google.com/storage/)
is the object storage service available on GCP, comparable to AWS S3. | | [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`](/usage/#--datasource-header-h)
flag | | [Merged Datasources](#using-merge-datasources) | `merge` | Merge two or more datasources together to produce the final value - useful for resolving defaults. Uses [`coll.Merge`](/functions/coll/#collmerge)
for merging. | | [Stdin](#using-stdin-datasources) | `stdin` | A special case of the `file` datasource; allows piping through standard input (`Stdin`) | | [Vault](#using-vault-datasources) | `vault`, `vault+http`, `vault+https` | [HashiCorp Vault](https://vaultproject.io)
is an industry-leading open-source secret management tool. [List support](#directory-datasources)
is also available. | Directory Datasources --------------------- 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. Currently the following datasources support directory semantics: * [File](#using-file-datasources) * [Vault](#using-vault-datasources) - translates to Vault’s `LIST` method * [Consul](#using-consul-datasources) When accessing a directory datasource, an array of key names is returned, and can be iterated through to access each individual value contained within. * [AWS S3](#using-s3-datasources) * [Google Cloud Storage](#using-google-cloud-storage-gs-datasources) * [Git](#using-git-datasources) * [AWS Systems Manager Parameter Store](#using-awssmp-datasources) 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: _template.tmpl:_ {{ range (datasource "config") -}} {{ . }} = {{ (datasource "config" .).value }} {{- end }} $ gomplate -d config=vault:///secret/configs/ -f template.tmpl one = v1 two = v2 three = v3 MIME Types ---------- 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`, `http`, `gs`, and `s3` datasources), or the [HTTP Content-Type](https://tools.ietf.org/html/rfc7231#section-3.1.1.1) header, if available. If an unsupported type is detected, gomplate will exit with an error. These are the supported types: | Format | MIME Type | Extension(s) | Notes | | --- | --- | --- | --- | | CSV | `text/csv` | `.csv` | Uses the [`data.CSV`](/functions/data/#datacsv)
function to present the file as a 2-dimensional row-first string array | | JSON | `application/json` | `.json` | [JSON](https://json.org)
_objects_ are assumed, but will support arrays as well. Other values are not parsed with this type. Uses the [`data.JSON`](/functions/data/#datajson)
function for parsing. [EJSON](/functions/data/#encrypted-json-support-ejson)
(encrypted JSON) is supported and will be decrypted. | | JSON Array | `application/array+json` | | A special type for parsing datasources containing just JSON arrays. Uses the [`data.JSONArray`](/functions/data/#datajsonarray)
function for parsing | | Plain Text | `text/plain` | | Unstructured, and as such only intended for use with the [`include`](/functions/data/#include)
function | | TOML | `application/toml` | `.toml` | Parses [TOML](https://github.com/toml-lang/toml)
with the [`data.TOML`](/functions/data/#datatoml)
function | | YAML | `application/yaml` | `.yml`, `.yaml` | Parses [YAML](http://yaml.org)
with the [`data.YAML`](/functions/data/#datayaml)
function | | [.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. | ### Overriding MIME Types 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](https://tools.ietf.org/html/rfc7231#section-3.1.1.1) header. For example, to force a file named `data.txt` to be parsed as a JSON document: $ echo '{"foo": "bar"}' > /tmp/data.txt $ gomplate -d data=file:///tmp/data.txt?type=application/json -i '{{ (ds "data").foo }}' bar If you need to provide a query parameter named `type` to the data source, set the `GOMPLATE_TYPE_PARAM` environment variable to another value: $ GOMPLATE_TYPE_PARAM=content-type gomplate -d data=https://example.com/mydata?content-type=application/json -i '{{ (ds "data").foo }}' bar ### The `.env` file format Many applications and frameworks support the use of a “.env” file for providing environment variables. It can also be considered a simple key/value file format, and as such can be used as a datasource in gomplate. To [override](#overriding-mime-types) , use the unregistered `application/x-env` MIME type. Here’s a sample explaining the syntax: FOO=a regular unquoted value export BAR=another value, exports are ignored # comments are totally ignored, as are blank lines FOO.BAR = "values can be double-quoted, and\tshell\nescapes are supported" BAZ="variable expansion: ${FOO}" QUX='single quotes ignore $variables and newlines' The [`github.com/joho/godotenv`](https://github.com/joho/godotenv) package is used for parsing - see the full details there. Using `aws+smp` datasources --------------------------- 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://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html) . 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. 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) . See details on how to configure gomplate’s AWS support in [_Configuring AWS_](/functions/aws/#configuring-aws) . ### URL Considerations The _scheme_ and _path_ URL components are used by this datasource. This may be an _opaque_ URI instead of an URL, when the key does not begin with a `/` character (e.g. `aws+smp:myparam`). * the _scheme_ must be `aws+smp` * the _path_ component is used to specify the path to the parameter (this may be a hierarchical path beginning with `/`, or an opaque path). [Directory](#directory-datasources) semantics are available when the path ends with a `/` character. ### Output The output will be a single `Parameter` object from the [AWS SDK for Go](https://docs.aws.amazon.com/sdk-for-go/api/service/ssm/#Parameter) : | name | description | | --- | --- | | `Name` | full Parameter name | | `Type` | `String`, `StringList` or `SecureString` | | `Value` | textual value, comma-separated single string if StringList | | `Version` | incrementing integer version | 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. ### Examples Given your AWS account’s Parameter Store has the following data: * `/foo/first/others` - `Bill,Ben` (a StringList) * `/foo/first/password` - `super-secret` (a SecureString) * `/foo/second/p1` - `aaa` * `myparameter` - `bar` $ echo '{{ ds "foo" }}' | gomplate -d foo=aws+smp:///foo/first/password map[Name:/foo/first/password Type:SecureString Value:super-secret Version:1] $ echo '{{ (ds "foo").Value }}' | gomplate -d foo=aws+smp:///foo/first/password super-secret $ echo '{{ (ds "foo" "/foo/first/others").Value }}' | gomplate -d foo=aws+smp: Bill,Ben $ echo '{{ (ds "foo" "/second/p1").Value }}' | gomplate -d foo=aws+smp:///foo/ aaa $ gomplate -d foo=aws+smp:///foo/first/ -i '{{ range (ds "foo") }} {{ . }}: {{ (ds "foo" .).Value }} {{- end }}' others: Bill,Ben password: super-secret $ gomplate -d foo=aws+smp:myparameter -i '{{ (ds "foo").Value }} bar Using `aws+sm` datasources -------------------------- ### URL Considerations For `aws+sm`, only the _scheme_ and _path_ components are necessary to be defined. This may be an _opaque_ URI instead of an URL, when the key does not begin with a `/` character (e.g. `aws+sm:myparam`). * the _scheme_ must be `aws+sm` * the _path_ component is used to specify the path to the secret (this may be a hierarchical path beginning with `/`, or an opaque path) ### Output The output will be the content of either the `SecretString` or `SecretBinary` field of the AWS SDK’s `GetSecretValueOutput` object from the [AWS SDK for Go](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/secretsmanager#GetSecretValueOutput) ### Examples Given your AWS account’s Secret Manager has the following data: * `/foo/bar/password` - `super-secret` * `mysecret` - `bar` $ echo '{{ (ds "foo") }}' | gomplate -d foo=aws+sm:///foo/bar/password super-secret $ echo '{{ (ds "foo" "/foo/bar/password") }}' | gomplate -d foo=aws+sm: super-secret $ echo '{{ (ds "foo" "/bar/password") }}' | gomplate -d foo=aws+sm:///foo/ super-secret $ echo '{{ (ds "foo") }}' | gomplate -d foo=aws+sm:mysecret bar Using `s3` datasources ---------------------- ### URL Considerations The _scheme_, _authority_, _path_, and _query_ URL components are used by this datasource. * the _scheme_ must be `s3` * the _authority_ component is used to specify the s3 bucket name * the _path_ component is used to specify the path to the object. [Directory](#directory-datasources) semantics are available when the path ends with a `/` character. * the _query_ component can be used to provide parameters to configure the connection: * `region`: The AWS region for requests. Defaults to the value from the `AWS_REGION` or `AWS_DEFAULT_REGION` environment variables, or the EC2 region if run in AWS EC2. * `endpoint`: The endpoint (`hostname`, `hostname:port`, or fully qualified URI). Useful for using a different S3-compatible object storage server. You can also set the `AWS_S3_ENDPOINT` environment variable. * `s3ForcePathStyle`: A value of `true` forces use of the deprecated “path-style” access. This is necessary for some S3-compatible object storage servers. * `disableSSL`: A value of `true` disables SSL when sending requests. Use only for test scenarios! * `type`: can be used to [override the MIME type](#overriding-mime-types) #### URL Examples Here are a few examples to help explain `s3` URLs: * `s3://mybucket/config/file.json` * the bucket region will be inferred, and the blob `config/file.json` in the `mybucket` bucket will be located in Amazon S3. * `s3://mybucket/` * The contents of the bucket `mybucket` will be listed into an array. Note that only the last portion of the path (the file name) will be listed. * `s3://mybucket/config/file?region=eu-west-1` * same as the first example, except the bucket’s region is overridden to `eu-west-1` * the lack of file extension means that file will be parsed according to the file’s `Content-Type` metadata * `s3://mybucket/config/file.json?endpoint=localhost:5432&disableSSL=true&s3ForcePathStyle=true` * this example is typical of a scenario where an S3-compatible server (such as [Minio](https://min.io) , [Zenko CloudServer](https://www.zenko.io/cloudserver/) , or testing-focused servers such as [gofakes3](https://github.com/johannesboyne/gofakes3) ) * the endpoint is overridden to be a server running on localhost * encryption is disabled since the endpoint is local * “path-style” access is used - this is typical for local servers, or scenarios where modifying DNS is impossible or impractical ### Output The output will be the object contents, parsed based on the discovered [MIME type](#mime-types) . ### Examples Given the S3 bucket named `my-bucket` has the following objects: * `foo/bar.json` - `{"hello": "world"}` * `foo/baz.txt` - `hello world` $ gomplate -c foo=s3://my-bucket/foo/bar.json -i 'Hello {{ .foo.hello }}' Hello world $ gomplate -c foo=s3://my-bucket/foo/ -i 'my-bucket/foo contains:{{ range .foo }}{{ print "\n" . }}{{ end }}' my-bucket/foo contains: bar.json baz.txt $ gomplate -c foo=s3://my-bucket/foo/bar.json?region=eu-west-1 -i 'Hello {{ .foo.hello }}' Hello world $ gomplate -c foo=s3://my-bucket/foo/bar.json?region=eu-west-1& endpoint=my-test-site& -i 'Hello {{ .foo.hello }}' Hello world $ gomplate -d bucket=s3://my-bucket/?region=eu-west-1&endpoint=my-test-site& -i 'Hello {{ (ds "bucket" "/foo/bar.json").hello }}' Hello world Using `consul` datasources -------------------------- Gomplate supports retrieving data from [HashiCorp Consul](https://consul.io) ’s [KV Store](https://developer.hashicorp.com/consul/api-docs/kv) . ### URL Considerations For `consul`, the _scheme_, _authority_, and _path_ components are used. * 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. * 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. * the _path_ can be provided to select a specific key, or a key prefix ### Consul Environment Variables The following optional environment variables are understood by the Consul datasource: | name | usage | | --- | --- | | `CONSUL_HTTP_ADDR` | Hostname and optional port for connecting to Consul. Defaults to `http://localhost:8500` | | `CONSUL_TIMEOUT` | Timeout (in seconds) when communicating to Consul. Defaults to 10 seconds. | | `CONSUL_HTTP_TOKEN` | The Consul token to use when connecting to the server. | | `CONSUL_HTTP_AUTH` | Should be specified as `:`. Used to authenticate to the server. | | `CONSUL_HTTP_SSL` | Force HTTPS if set to `true` value. Disables if set to `false`. Any value acceptable to [`strconv.ParseBool`](https://pkg.go.dev/strconv/#ParseBool)
can be provided. | | `CONSUL_TLS_SERVER_NAME` | The server name to use as the SNI host when connecting to Consul via TLS. | | `CONSUL_CACERT` | Path to CA file for verifying Consul server using TLS. | | `CONSUL_CAPATH` | Path to directory of CA files for verifying Consul server using TLS. | | `CONSUL_CLIENT_CERT` | Client certificate file for certificate authentication. If this is set, `$CONSUL_CLIENT_KEY` must also be set. | | `CONSUL_CLIENT_KEY` | Client key file for certificate authentication. If this is set, `$CONSUL_CLIENT_CERT` must also be set. | | `CONSUL_HTTP_SSL_VERIFY` | Set to `false` to disable Consul TLS certificate checking. Any value acceptable to [`strconv.ParseBool`](https://pkg.go.dev/strconv/#ParseBool)
can be provided. _Recommended only for testing and development scenarios!_ | | `CONSUL_VAULT_ROLE` | Set to the name of the role to use for authenticating to Consul with [Vault’s Consul secret backend](https://developer.hashicorp.com/vault/docs/secrets/consul)
. | | `CONSUL_VAULT_MOUNT` | Used to override the mount-point when using Vault’s Consul secret back-end for authentication. Defaults to `consul`. | ### Authentication Instead of using a non-authenticated Consul connection, you can authenticate with these methods: * provide an [ACL Token](https://developer.hashicorp.com/consul/docs/security/acl#tokens) in the `CONSUL_HTTP_TOKEN` environment variable * use HTTP Basic Auth by setting the `CONSUL_HTTP_AUTH` environment variable * dynamically generate an ACL token with Vault. This requires Vault to be configured to use the [Consul secret backend](https://developer.hashicorp.com/vault/docs/secrets/consul) and is enabled by passing the name of the role to use in the `CONSUL_VAULT_ROLE` environment variable. ### Examples $ gomplate -d consul=consul:// -i '{{(datasource "consul" "foo")}}' value for foo key $ gomplate -d consul=consul+https://my-consul-server.com:8533/foo -i '{{(datasource "consul" "bar")}}' value for foo/bar key $ gomplate -d consul=consul:///foo -i '{{(datasource "consul" "bar/baz")}}' value for foo/bar/baz key Using `env` datasources ----------------------- 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. No hierarchy or directory semantics are currently supported. **Note:** Variable names are _case-sensitive!_ ### URL Considerations 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) . * the _scheme_ must be `env` * 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_. ### Examples $ gomplate -d user=env:USER -i 'Hello {{ include "user" }}!' Hello hairyhenderson! $ gomplate -d homedir=env:///HOME -i '{{ file.IsDir (ds "homedir") }}' true $ export foo='{"one":1, "two":2}' $ gomplate -d foo=env:/foo?type=application/json -i '{{ (ds "foo").two }}' 2 Using `file` datasources ------------------------ The `file` datasource type provides access to files in any of the [supported formats](#mime-types) . [Directory datasource](#directory-datasources) semantics are supported. ### URL Considerations The _scheme_ and _path_ are used, and the _query_ component can be used to [override the MIME type](#overriding-mime-types) . * the _scheme_ must be `file` for absolute URLs, but may be omitted to allow setting relative paths * 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. ### Examples _`person.json`:_ { "name": "Dave" } _implicit alias:_ $ gomplate -d person.json -i 'Hello {{ (datasource "person").name }}' Hello Dave _explicit alias:_ $ gomplate -d person=./person.json -i 'Hello {{ (datasource "person").name }}' Hello Dave $ gomplate -d person=../path/to/person.json -i 'Hello {{ (datasource "person").name }}' Hello Dave $ gomplate -d person=file:///tmp/person.json -i 'Hello {{ (datasource "person").name }}' Hello Dave Using `git` datasources ----------------------- The `git` datasource type provides access to files in any of the [supported formats](#mime-types) hosted in local or remote git repositories. [Directory datasource](#directory-datasources) semantics are supported. Remote repositories can be accessed by SSH, HTTP(S), and Git protocols. Note that this datasource accesses the git state, and so for local filesystem repositories, any files not committed to a branch (i.e. “dirty” or modified files) will not be visible. ### URL Considerations The _scheme_, _authority_ (with _userinfo_), _path_, and _fragment_ are used, and the _query_ component can be used to [override the MIME type](#overriding-mime-types) . * the _scheme_ may be one of these values: * `git`: uses the [classic Git protocol](https://git-scm.com/book/en/v2/Git-on-the-Server-The-Protocols#_the_git_protocol) (as served by `git daemon`) * `git+file`: uses the local filesystem (repo can be bare or not) * `git+http`, `git+https`: uses the [Smart HTTP protocol](https://git-scm.com/book/en/v2/Git-on-the-Server-The-Protocols#_the_http_protocols) * `git+ssh`: uses the [SSH protocol](https://git-scm.com/book/en/v2/Git-on-the-Server-The-Protocols#_the_ssh_protocol) * the _authority_ component points to the remote git server hostname (and optional port, if applicable). The _userinfo_ subcomponent can be used for authenticated datasources like `git+https` and `git+ssh`. * the _path_ component is a composite of the path to the repository, and the path to the file or directory being referenced within. The `//` sequence (double forward-slash) is used to separate the repository from the path. If no `//` is present in the URL, the datasource will point to the root directory of the repository. * the _fragment_ component can be used to specify which branch or tag to reference. By default, the repository’s default branch will be chosen. * branches can be referenced by short name or by the long form. Valid fragments are `#main`, `#master`, `#develop`, `#refs/heads/mybranch`, etc… * tags must use the long form prefixed by `refs/tags/`, i.e. `#refs/tags/v1` for the `v1` tag ### Authentication The `git` and `git+file` schemes are always unauthenticated, `git+http`/`git+https` can _optionally_ be authenticated, and `git+ssh` _must_ be authenticated. Authenticating with both HTTP and SSH requires the user to be set (like `git+ssh://user@example.com`), but the credentials vary otherwise. #### HTTP(S) Authentication Note that because HTTP connections are unencypted, and HTTP authentication is performed with headers, it is strongly recommended to _only_ use HTTPS (`git+https`) connections when accessing authenticated repositories. ##### Basic Auth The most common form. The password can be specified as part of the URL, or provided through the `GIT_HTTP_PASSWORD` environment variable, or in a file referenced by the `GIT_HTTP_PASSWORD_FILE` environment variable. For authenticating with GitHub, Bitbucket, GitLab and other popular git hosts, use this method with a _personal access token_, and the user set to `git`. ##### Token Auth Some servers require the use of a bearer token. To use this method, a user is _not_ required, and the token must be set in the `GIT_HTTP_TOKEN` environment variable, or in a file referenced by the `GIT_HTTP_TOKEN_FILE` environment variable. #### SSH Authentication Only public key based authentication is supported for `git+ssh` connections. The key can be provided directly, or via the SSH Agent (or Pageant on Windows). To provide a key directly, set the `GIT_SSH_KEY` to the contents of the key, or point `GIT_SSH_KEY_FILE` to a file containing the key. Because the file may contain newline characters that may be difficult to provide in an environment variable, it can also be Base64-encoded. If neither `GIT_SSH_KEY` nor `GIT_SSH_KEY_FILE` are set, gomplate will attempt to use the SSH Agent. **Note:** password-protected SSH keys are currently not supported. If you have a password-protected key, use the SSH Agent. ### Examples Accessing a file in a publicly-readable GitHub repository: $ gomplate -c doc=git+https://github.com/hairyhenderson/gomplate//docs-src/content/functions/env.yml -i 'namespace is: {{ .doc.ns }}' namespace is: env Accessing a file from a local repo (using arguments): $ gomplate -d which=git+file:///repos/go-which/ -i 'GOPATH on Windows is {{ (datasource "which" ".//appveyor.yml").environment.GOPATH }}' GOPATH on Windows is c:\gopath Accessing a directory at a specific tag: $ gomplate -d 'cmd=git+https://github.com/hairyhenderson/go-which//cmd/which#refs/tags/v0.1.0' -i '{{ ds "cmd" }}' [main.go] Authenticating with the SSH Agent $ gomplate -d 'which=git+ssh://git@github.com/hairyhenderson/go-which/' -i '{{ len (ds "which") }}' 18 Using arguments to specify different repos $ gomplate -d 'hairyhenderson=git+https://github.com/hairyhenderson/' -i '{{ (ds "hairyhenderson" "gomplate//docs-src/content/functions/env.yml").ns }}' env Using Google Cloud Storage (`gs`) datasources --------------------------------------------- ### URL Considerations The _scheme_, _authority_, _path_, and _query_ URL components are used by this datasource. * the _scheme_ must be `gs` * the _authority_ component is used to specify the bucket name * the _path_ component is used to specify the path to the object. [Directory](#directory-datasources) semantics are available when the path ends with a `/` character. * the _query_ component can be used to provide parameters to configure the connection: * `access_id`: (optional) Usually unnecessary. Sets the GoogleAccessID (see [https://godoc.org/cloud.google.com/go/storage#SignedURLOptions](https://godoc.org/cloud.google.com/go/storage#SignedURLOptions) ) * `private_key_path`: (optional) Usually unnecessary. Sets the path to the Google service account private key (see [https://godoc.org/cloud.google.com/go/storage#SignedURLOptions](https://godoc.org/cloud.google.com/go/storage#SignedURLOptions) ) * `type`: can be used to [override the MIME type](#overriding-mime-types) ### Authentication All `gs` datasources need credentials, provided by the `GOOGLE_APPLICATION_CREDENTIALS` environment variable. This should point to an authentication configuration JSON file. See Google Cloud’s [Getting Started with Authentication](https://cloud.google.com/docs/authentication/getting-started) documentation for details. ### Output The output will be the object contents, parsed based on the discovered [MIME type](#mime-types) . ### Examples Given the bucket named `my-bucket` has the following objects: * `foo/bar.json` - `{"hello": "world"}` * `foo/baz.txt` - `hello world` $ gomplate -c foo=gs://my-bucket/foo/bar.json -i 'Hello {{ .foo.hello }}' Hello world $ gomplate -c foo=gs://my-bucket/foo/ -i 'my-bucket/foo contains:{{ range .foo }}{{ print "\n" . }}{{ end }}' my-bucket/foo contains: bar.json baz.txt Using `http` datasources ------------------------ To access datasources from HTTP sites or APIs, simply use a `http` or `https` URL: $ gomplate -d foo=https://httpbin.org/get -i 'Hello there, {{ (ds "foo").headers.Host }}...' Hello there, httpbin.org... $ 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...' Hello there, httpbin.org, you are looking very Go-http-client/1.1 today... ### Sending HTTP headers Additional headers can be provided with the `--datasource-header`/`-H` option: $ gomplate -d foo=https://httpbin.org/get -H 'foo=Foo: bar' -i '{{(datasource "foo").headers.Foo}}' bar This can be useful for providing API tokens to authenticated HTTP-based APIs. Using `merge` datasources ------------------------- The `merge` scheme can be used to merge two or more other datasources together. `merge:` uses an [_opaque_ URI](#opaque-uris) format, where the _path_ component is a list of datasource aliases or URLs, separated by the `|` character. The datasources are read and merged together from right to left (i.e. the left-most datasource values _override_ those to the right). Multiple different formats can be mixed, as long as they produce maps with string keys as their data type. The [`coll.Merge`](/functions/coll/#collmerge) function is used to perform the merge operation. ### Merging separately-defined datasources Consider this example: $ gomplate -d "foo=merge:foo|bar|baz" -d foo=... -d bar=... -d baz=... ... This will read the `foo`, `bar`, and `baz` datasources (which must be otherwise defined), and then overlay `bar`’s values on top of `baz`’s, then `foo`’s values on top of those. The disadvantage with this option is verbosity, but the advantage is that the individual datasources can still be referenced. ### Merging datasources defined in-line Here’s an example using URLs instead of aliases: $ gomplate -d "foo=merge:./config/main.yaml|http://example.com/defaults.json" ... This has the advantage of being slightly less verbose. Note that relative URLs in a subdirectory are supported in this context, as well as any other supported datasource URL. A caveat to defining datasources in-line is that the _query_ and _fragment_ components of the URI are interpreted as part of the `merge:` URI. To merge datasources with query strings or fragments, define separate sources first and use the aliases. Similarly, extra HTTP headers can only be defined for separately- defined datasources. Using `stdin` datasources ------------------------- Normally _Stdin_ is used as the input for the template, but it can also be used to stream a datasource. To do this, specify a URL with the `stdin:` scheme. 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`](/functions/data/#include) function), the scheme alone is enough. $ echo 'foo: bar' | gomplate -i '{{(ds "data").foo}}' -d data=stdin:///foo.yaml bar $ echo 'foo' | gomplate -i '{{ include "data" }}' -d data=stdin: foo $ echo '["one", "two"]' | gomplate -i '{{index (ds "data") 1 }}' -d data=stdin:?type=application/array%2Bjson two Using `vault` datasources ------------------------- Gomplate can retrieve secrets and other data from [HashiCorp Vault](https://vaultproject.io) . ### URL Considerations The _scheme_, _authority_, _path_, and _query_ URL components are used by this datasource. * 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://developer.hashicorp.com/vault/docs/concepts/dev-server) Vault servers, for test purposes. Otherwise, all connections to Vault are encrypted with TLS. * the _authority_ component can optionally be used to specify the Vault server’s hostname and port. This overrides the value of `$VAULT_ADDR`. * the _path_ component can optionally be used to specify a full or partial path to a secret. The second argument to the [`datasource`](/functions/data/#datasource) function is appended to provide the full secret path. [Directory](#directory-datasources) semantics are available when the path ends with a `/` character. * 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 `POST` request. The `version` parameter in particular can be used to specify the version of a secret when using the KV v2 secrets engine. These are all valid `vault` URLs: * `vault:`, `vault://`, `vault:///` - these all require the [`datasource`](/functions/data/#datasource) function to provide the secret path * `vault://vault.example.com:8200` - connect to `vault.example.com` over HTTPS at port `8200`. The path will be provided by [`datasource`](/functions/data/#datasource) * `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 * `vault:///secret/configs/` - returns a list of key names with the prefix of `secret/configs/` ### KV secrets engine - version 2 support Vault’s KV secrets engine version 2 is supported automatically. In order to access specific versions of secrets, you may provide the `version` query parameter. ### Vault Authentication This table describes the currently-supported authentication mechanisms and how to use them, in order of precedence: | auth back-end | configuration | | --- | --- | | [`approle`](https://developer.hashicorp.com/vault/docs/auth/approle) | Environment variables `$VAULT_ROLE_ID` and `$VAULT_SECRET_ID` must be set to the appropriate values. If the back-end is mounted to a different location, set `$VAULT_AUTH_APPROLE_MOUNT`. | | [`github`](https://developer.hashicorp.com/vault/docs/auth/github) | Environment variable `$VAULT_AUTH_GITHUB_TOKEN` must be set to an appropriate value. If the back-end is mounted to a different location, set `$VAULT_AUTH_GITHUB_MOUNT`. | | [`userpass`](https://developer.hashicorp.com/vault/docs/auth/userpass) | Environment variables `$VAULT_AUTH_USERNAME` and `$VAULT_AUTH_PASSWORD` must be set to the appropriate values. If the back-end is mounted to a different location, set `$VAULT_AUTH_USERPASS_MOUNT`. | | [`token`](https://developer.hashicorp.com/vault/docs/auth/token) | Determined from either the `$VAULT_TOKEN` environment variable, or read from the file `~/.vault-token` | | [`aws`](https://developer.hashicorp.com/vault/docs/auth/aws) | The env var `$VAULT_AUTH_AWS_ROLE` defines the [role](https://developer.hashicorp.com/vault/api-docs/auth/aws#role-4)
to log in with - defaults to the AMI ID of the EC2 instance. Usually a [Client Nonce](https://developer.hashicorp.com/vault/docs/auth/aws#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.If the back-end is mounted to a different location, set `$VAULT_AUTH_AWS_MOUNT`. | _**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. ### Vault Permissions The correct capabilities must be allowed for the [authenticated](#vault-authentication) credentials. See the [Vault documentation](https://developer.hashicorp.com/vault/docs/concepts/policies#capabilities) for full details. * regular secret read operations require the `read` capability * dynamic secret generation requires the `create` and `update` capabilities * list support requires the `list` capability ### Vault Environment variables 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://developer.hashicorp.com/vault/docs/commands#configure-environment-variables) . ### Examples $ gomplate -d vault=vault:///secret/sneakers -i 'My voice is my passport. {{(datasource "vault").value}}' My voice is my passport. Verify me. For KV v2 secrets engine, specifying a version: $ gomplate -d vault=vault:///kv2/sneakers?version=2 -i 'My voice is my passport. {{(datasource "vault").data.value}}' My voice is my passport. Verify me. You can also specify the secret path in the template by omitting the path portion of the URL: $ gomplate -d vault=vault:/// -i 'My voice is my passport. {{(datasource "vault" "secret/sneakers").value}}' My voice is my passport. Verify me. And the two can be mixed to scope secrets to a specific namespace: $ gomplate -d vault=vault:///secret/production -i 'db_password={{(datasource "vault" "db/pass").value}}' db_password=prodsecret If you are unable to set the `VAULT_ADDR` environment variable, or need to specify multiple Vault datasources connecting to different servers, you can set the address as part of the URL: $ gomplate -d v=vault://vaultserver.com/secret/foo -i '{{ (ds "v").value }}' bar To use dynamic secrets: $ gomplate -d vault=vault:/// -i 'otp={{(ds "vault" "ssh/creds/test?ip=10.1.2.3&username=user").key}}' otp=604a4bd5-7afd-30a2-d2d8-80c4aebc6183 With the AWS auth back-end: $ export VAULT_AUTH_AWS_NONCE_FILE=/tmp/vault-aws-nonce $ export VAULT_AUTH_AWS_NONCE_OUTPUT=$VAULT_AUTH_AWS_NONCE_FILE $ gomplate -d vault=vault:///secret/foo -i '{{ (ds "vault").value }}' ... The file `/tmp/vault-aws-nonce` will be created if it didn’t already exist, and further executions of `gomplate` can re-authenticate securely. --- # conversion functions - gomplate documentation conversion functions ==================== These are a collection of functions that mostly help converting from one type to another - generally from a `string` to something else, and vice-versa. `conv.Bool` ----------- **Alias:** `bool` **Note:** See also [`conv.ToBool`](#convtobool) for a more flexible variant. Converts a true-ish string to a boolean. Can be used to simplify conditional statements based on environment variables or other text input. _Added in gomplate [v0.2.0](https://github.com/hairyhenderson/gomplate/releases/tag/v0.2.0) _ ### Usage conv.Bool in in | conv.Bool ### Arguments | name | description | | --- | --- | | `in` | _(required)_ the input string | ### Examples _`input.tmpl`:_ {{if bool (getenv "FOO")}}foo{{else}}bar{{end}} $ gomplate < input.tmpl bar $ FOO=true gomplate < input.tmpl foo `conv.Default` -------------- **Alias:** `default` Provides a default value given an empty input. Empty inputs are `0` for numeric types, `""` for strings, `false` for booleans, empty arrays/maps, and `nil`. Note that this will not provide a default for the case where the input is undefined (i.e. referencing things like `.foo` where there is no `foo` field of `.`), but [`coll.Has`](../coll/#collhas) can be used for that. _Added in gomplate [v2.5.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.5.0) _ ### Usage conv.Default default in in | conv.Default default ### Arguments | name | description | | --- | --- | | `default` | _(required)_ the default value | | `in` | _(required)_ the input | ### Examples $ gomplate -i '{{ "" | default "foo" }} {{ "bar" | default "baz" }}' foo bar `conv.Dict` _(deprecated)_ -------------------------- **Deprecation Notice:** Renamed to [`coll.Dict`](../coll/#colldict) **Alias:** `dict` Dict is a convenience function that creates a map with string keys. Provide arguments as key/value pairs. If an odd number of arguments is provided, the last is used as the key, and an empty string is set as the value. All keys are converted to strings. This function is equivalent to [Sprig’s `dict`](http://masterminds.github.io/sprig/dicts.html#dict) function, as used in [Helm templates](https://helm.sh/docs/chart_template_guide/functions_and_pipelines/) . For creating more complex maps, see [`data.JSON`](../data/#datajson) or [`data.YAML`](../data/#datayaml) . For creating arrays, see [`coll.Slice`](../coll/#collslice-_deprecated_) . _Added in gomplate [v3.0.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.0.0) _ ### Usage conv.Dict in... ### Arguments | name | description | | --- | --- | | `in...` | _(required)_ The key/value pairs | ### Examples $ gomplate -i '{{ conv.Dict "name" "Frank" "age" 42 | data.ToYAML }}' age: 42 name: Frank $ gomplate -i '{{ dict 1 2 3 | toJSON }}' {"1":2,"3":""} $ cat <` command to convert from other formats to CUE. ### Usage data.ToCUE input input | data.ToCUE ### Arguments | name | description | | --- | --- | | `input` | _(required)_ the object to marshal as a CUE document | ### Examples $ gomplate -i '{{ `{"foo":"bar"}` | data.JSON | data.ToCUE }}' { foo: "bar" } $ gomplate -i '{{ toCUE "hello world" }}' "hello world" $ gomplate -i '{{ coll.Slice 1 "two" true | data.ToCUE }}' [1, "two", true] --- # crypto functions - gomplate documentation crypto functions ================ A set of crypto-related functions to be able to perform hashing and (simple!) encryption operations with `gomplate`. _Note: These functions are mostly wrappers of existing functions in the Go standard library. The authors of gomplate are not cryptographic experts, however, and so can not guarantee correctness of implementation. It is recommended to have your resident security experts inspect gomplate’s code before using gomplate for critical security infrastructure!_ `crypto.Bcrypt` --------------- Uses the [bcrypt](https://en.wikipedia.org/wiki/Bcrypt) password hashing algorithm to generate the hash of a given string. Wraps the [`golang.org/x/crypto/brypt`](https://godoc.org/golang.org/x/crypto/bcrypt) package. _Added in gomplate [v2.6.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.6.0) _ ### Usage crypto.Bcrypt [cost] input input | crypto.Bcrypt [cost] ### Arguments | name | description | | --- | --- | | `cost` | _(optional)_ the cost, as a number from `4` to `31` - defaults to `10` | | `input` | _(required)_ the input to hash, usually a password | ### Examples $ gomplate -i '{{ "foo" | crypto.Bcrypt }}' $2a$10$jO8nKZ1etGkKK7I3.vPti.fYDAiBqwazQZLUhaFoMN7MaLhTP0SLy $ gomplate -i '{{ crypto.Bcrypt 4 "foo" }} $2a$04$zjba3N38sjyYsw0Y7IRCme1H4gD0MJxH8Ixai0/sgsrf7s1MFUK1C `crypto.DecryptAES` _(experimental)_ ------------------------------------ **Experimental:** This function is [_experimental_](/config/#experimental) and may be enabled with the [`--experimental`](/config/#experimental) flag. Decrypts the given input using the given key. By default, uses AES-256-CBC, but supports 128- and 192-bit keys as well. This function prints the output as a string. Note that this may result in unreadable text if the decrypted payload is binary. See [`crypto.DecryptAESBytes`](#cryptodecryptaesbytes-_experimental_) for another method. This function is suitable for decrypting data that was encrypted by Helm’s `encryptAES` function, when the input is base64-decoded, and when using 256-bit keys. _Added in gomplate [v3.11.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.11.0) _ ### Usage crypto.DecryptAES key [keyBits] input input | crypto.DecryptAES key [keyBits] ### Arguments | name | description | | --- | --- | | `key` | _(required)_ the key to use for decryption | | `keyBits` | _(optional)_ the key length to use - defaults to `256` | | `input` | _(required)_ the input to decrypt | ### Examples $ gomplate -i '{{ base64.Decode "Gp2WG/fKOUsVlhcpr3oqgR+fRUNBcO1eZJ9CW+gDI18=" | crypto.DecryptAES "swordfish" 128 }}' hello world `crypto.DecryptAESBytes` _(experimental)_ ----------------------------------------- **Experimental:** This function is [_experimental_](/config/#experimental) and may be enabled with the [`--experimental`](/config/#experimental) flag. Decrypts the given input using the given key. By default, uses AES-256-CBC, but supports 128- and 192-bit keys as well. This function outputs the raw byte array, which may be sent as input to other functions. This function is suitable for decrypting data that was encrypted by Helm’s `encryptAES` function, when the input is base64-decoded, and when using 256-bit keys. _Added in gomplate [v3.11.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.11.0) _ ### Usage crypto.DecryptAESBytes key [keyBits] input input | crypto.DecryptAESBytes key [keyBits] ### Arguments | name | description | | --- | --- | | `key` | _(required)_ the key to use for decryption | | `keyBits` | _(optional)_ the key length to use - defaults to `256` | | `input` | _(required)_ the input to decrypt | ### Examples $ gomplate -i '{{ base64.Decode "Gp2WG/fKOUsVlhcpr3oqgR+fRUNBcO1eZJ9CW+gDI18=" | crypto.DecryptAES "swordfish" 128 }}' hello world `crypto.EncryptAES` _(experimental)_ ------------------------------------ **Experimental:** This function is [_experimental_](/config/#experimental) and may be enabled with the [`--experimental`](/config/#experimental) flag. Encrypts the given input using the given key. By default, uses AES-256-CBC, but supports 128- and 192-bit keys as well. This function is suitable for encrypting data that will be decrypted by Helm’s `decryptAES` function, when the output is base64-encoded, and when using 256-bit keys. _Added in gomplate [v3.11.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.11.0) _ ### Usage crypto.EncryptAES key [keyBits] input input | crypto.EncryptAES key [keyBits] ### Arguments | name | description | | --- | --- | | `key` | _(required)_ the key to use for encryption | | `keyBits` | _(optional)_ the key length to use - defaults to `256` | | `input` | _(required)_ the input to encrypt | ### Examples $ gomplate -i '{{ "hello world" | crypto.EncryptAES "swordfish" 128 | base64.Encode }}' MnRutHovsh/9JN3YrJtBVjZtI6xXZh33bCQS2iZ4SDI= `crypto.ECDSAGenerateKey` _(experimental)_ ------------------------------------------ **Experimental:** This function is [_experimental_](/config/#experimental) and may be enabled with the [`--experimental`](/config/#experimental) flag. Generate a new Elliptic Curve Private Key and output in PEM-encoded PKCS#1 ASN.1 DER form. Go’s standard NIST P-224, P-256, P-384, and P-521 elliptic curves are all supported. Default curve is P-256 and can be overridden with the optional `curve` parameter. _Added in gomplate [v3.11.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.11.0) _ ### Usage crypto.ECDSAGenerateKey [curve] curve | crypto.ECDSAGenerateKey ### Arguments | name | description | | --- | --- | | `curve` | _(optional)_ One of Go’s standard NIST curves, P-224, P-256, P-384, or P-521 - | | defaults to P-256. | | | | | ### Examples $ gomplate -i '{{ crypto.ECDSAGenerateKey }}' -----BEGIN EC PRIVATE KEY----- ... `crypto.ECDSADerivePublicKey` _(experimental)_ ---------------------------------------------- **Experimental:** This function is [_experimental_](/config/#experimental) and may be enabled with the [`--experimental`](/config/#experimental) flag. Derive a public key from an elliptic curve private key and output in PKIX ASN.1 DER form. _Added in gomplate [v3.11.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.11.0) _ ### Usage crypto.ECDSADerivePublicKey key key | crypto.ECDSADerivePublicKey ### Arguments | name | description | | --- | --- | | `key` | _(required)_ the private key to derive a public key from | ### Examples $ gomplate -i '{{ crypto.ECDSAGenerateKey | crypto.ECDSADerivePublicKey }}' -----BEGIN PUBLIC KEY----- ... $ gomplate -d key=priv.pem -i '{{ crypto.ECDSADerivePublicKey (include "key") }}' -----BEGIN PUBLIC KEY----- MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBZvTS1wcCJSsGYQUVoSVctynkuhke kikB38iNwx/80jzdm+Z8OmRGlwH6OE9NX1MyxjvYMimhcj6zkaOKh1/HhMABrfuY +hIz6+EUt/Db51awO7iCuRly5L4TZ+CnMAsIbtUOqsqwSQDtv0AclAuogmCst75o aztsmrD79OXXnhUlURI= -----END PUBLIC KEY----- `crypto.Ed25519GenerateKey` _(experimental)_ -------------------------------------------- **Experimental:** This function is [_experimental_](/config/#experimental) and may be enabled with the [`--experimental`](/config/#experimental) flag. Generate a new Ed25519 Private Key and output in PEM-encoded PKCS#8 ASN.1 DER form. _Added in gomplate [v4.0.0](https://github.com/hairyhenderson/gomplate/releases/tag/v4.0.0) _ ### Usage crypto.Ed25519GenerateKey ### Examples $ gomplate -i '{{ crypto.Ed25519GenerateKey }}' -----BEGIN PRIVATE KEY----- ... `crypto.Ed25519GenerateKeyFromSeed` _(experimental)_ ---------------------------------------------------- **Experimental:** This function is [_experimental_](/config/#experimental) and may be enabled with the [`--experimental`](/config/#experimental) flag. Generate a new Ed25519 Private Key from a random seed and output in PEM-encoded PKCS#8 ASN.1 DER form. _Added in gomplate [v4.0.0](https://github.com/hairyhenderson/gomplate/releases/tag/v4.0.0) _ ### Usage crypto.Ed25519GenerateKeyFromSeed encoding seed seed | crypto.Ed25519GenerateKeyFromSeed encoding ### Arguments | name | description | | --- | --- | | `encoding` | _(required)_ the encoding that the seed is in (`hex` or `base64`) | | `seed` | _(required)_ the random seed encoded in either base64 or hex | ### Examples $ gomplate -i '{{ crypto.Ed25519GenerateKeyFromSeed "base64" "MDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDA=" }}' -----BEGIN PRIVATE KEY----- ... `crypto.Ed25519DerivePublicKey` _(experimental)_ ------------------------------------------------ **Experimental:** This function is [_experimental_](/config/#experimental) and may be enabled with the [`--experimental`](/config/#experimental) flag. Derive a public key from an Ed25519 private key and output in PKIX ASN.1 DER form. _Added in gomplate [v4.0.0](https://github.com/hairyhenderson/gomplate/releases/tag/v4.0.0) _ ### Usage crypto.Ed25519DerivePublicKey key key | crypto.Ed25519DerivePublicKey ### Arguments | name | description | | --- | --- | | `key` | _(required)_ the private key to derive a public key from | ### Examples $ gomplate -i '{{ crypto.Ed25519GenerateKey | crypto.Ed25519DerivePublicKey }}' -----BEGIN PUBLIC KEY----- ... $ gomplate -d key=priv.pem -i '{{ crypto.Ed25519DerivePublicKey (include "key") }}' -----BEGIN PUBLIC KEY----- ...PK `crypto.PBKDF2` --------------- Run the Password-Based Key Derivation Function #2 as defined in [RFC 8018 (PKCS #5 v2.1)](https://tools.ietf.org/html/rfc8018#section-5.2) . This function outputs the binary result as a hexadecimal string. _Added in gomplate [v2.3.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.3.0) _ ### Usage crypto.PBKDF2 password salt iter keylen [hashfunc] ### Arguments | name | description | | --- | --- | | `password` | _(required)_ the password to use to derive the key | | `salt` | _(required)_ the salt | | `iter` | _(required)_ iteration count | | `keylen` | _(required)_ desired length of derived key | | `hashfunc` | _(optional)_ the hash function to use - must be one of the allowed functions (either in the SHA-1 or SHA-2 sets). Defaults to `SHA-1` | ### Examples $ gomplate -i '{{ crypto.PBKDF2 "foo" "bar" 1024 8 }}' 32c4907c3c80792b `crypto.RSADecrypt` _(experimental)_ ------------------------------------ **Experimental:** This function is [_experimental_](/config/#experimental) and may be enabled with the [`--experimental`](/config/#experimental) flag. Decrypt an RSA-encrypted input and print the output as a string. Note that this may result in unreadable text if the decrypted payload is binary. See [`crypto.RSADecryptBytes`](#cryptorsadecryptbytes-_experimental_) for a safer method. The private key must be a PEM-encoded RSA private key in PKCS#1, ASN.1 DER form, which typically begins with `-----BEGIN RSA PRIVATE KEY-----`. The input text must be plain ciphertext, as a byte array, or safely convertible to a byte array. To decrypt base64-encoded input, you must first decode with the [`base64.DecodeBytes`](../base64/#base64decodebytes) function. _Added in gomplate [v3.8.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.8.0) _ ### Usage crypto.RSADecrypt key input input | crypto.RSADecrypt key ### Arguments | name | description | | --- | --- | | `key` | _(required)_ the private key to decrypt the input with | | `input` | _(required)_ the encrypted input | ### Examples $ gomplate -c pubKey=./testPubKey -c privKey=./testPrivKey \ -i '{{ $enc := "hello" | crypto.RSAEncrypt .pubKey -}} {{ crypto.RSADecrypt .privKey $enc }}' hello $ export ENCRYPTED="ScTcX1NZ6p/EeDIf6R7FKLcDFjvP98YgiBhyhPE4jtehajIyTKP1GL8C72qbAWrgdQ6A2cSVjoyo3viqf/PZxpcBDUUMDJuemTaJqUUjMWaDuPG37mQbmRtcvFTuUhw1qSbKyHorDOgTX5d4DvWV4otycGtBT6dXhnmmb5V72J/w3z68vtTJ21m9wREFD7LrYVHdFFtRZiIyMBAF0ngQ+hcujrxilnmgzPkEAg6E7Ccctn28Ie2c4CojrwRbNNxXNlIWCCkC/8Vq8qlDfZ70a+BsTmJDuScE6BZbTyteo9uGYrLn+bTIHNDj90AeLCKUTyWLUJ5Edi9LhlKVBoJUNQ==" $ gomplate -c ciphertext=env:///ENCRYPTED -c privKey=./testPrivKey \ -i '{{ base64.DecodeBytes .ciphertext | crypto.RSADecrypt .privKey }}' hello `crypto.RSADecryptBytes` _(experimental)_ ----------------------------------------- **Experimental:** This function is [_experimental_](/config/#experimental) and may be enabled with the [`--experimental`](/config/#experimental) flag. Decrypt an RSA-encrypted input and output the decrypted byte array. The private key must be a PEM-encoded RSA private key in PKCS#1, ASN.1 DER form, which typically begins with `-----BEGIN RSA PRIVATE KEY-----`. The input text must be plain ciphertext, as a byte array, or safely convertible to a byte array. To decrypt base64-encoded input, you must first decode with the [`base64.DecodeBytes`](../base64/#base64decodebytes) function. See [`crypto.RSADecrypt`](#cryptorsadecrypt-_experimental_) for a function that outputs a string. _Added in gomplate [v3.8.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.8.0) _ ### Usage crypto.RSADecryptBytes key input input | crypto.RSADecryptBytes key ### Arguments | name | description | | --- | --- | | `key` | _(required)_ the private key to decrypt the input with | | `input` | _(required)_ the encrypted input | ### Examples $ gomplate -c pubKey=./testPubKey -c privKey=./testPrivKey \ -i '{{ $enc := "hello" | crypto.RSAEncrypt .pubKey -}} {{ crypto.RSADecryptBytes .privKey $enc }}' [104 101 108 108 111] $ gomplate -c pubKey=./testPubKey -c privKey=./testPrivKey \ -i '{{ $enc := "hello" | crypto.RSAEncrypt .pubKey -}} {{ crypto.RSADecryptBytes .privKey $enc | conv.ToString }}' hello `crypto.RSAEncrypt` _(experimental)_ ------------------------------------ **Experimental:** This function is [_experimental_](/config/#experimental) and may be enabled with the [`--experimental`](/config/#experimental) flag. Encrypt the input with RSA and the padding scheme from PKCS#1 v1.5. This function is suitable for encrypting data that will be decrypted by [Terraform’s `rsadecrypt` function](https://www.terraform.io/docs/configuration/functions/rsadecrypt.html) . The key should be a PEM-encoded RSA public key in PKIX ASN.1 DER form, which typically begins with `BEGIN PUBLIC KEY`. RSA public keys in PKCS#1 ASN.1 DER form are also supported (beginning with `RSA PUBLIC KEY`). The output will not be encoded, so consider [base64-encoding](../base64/#base64encode) it for display. _Note:_ Output encrypted with this function will _not_ be deterministic, so encrypting the same input twice will not result in the same ciphertext. _Warning:_ Using this function may not be safe. See the warning on Go’s [`rsa.EncryptPKCS1v15`](https://pkg.go.dev/crypto/rsa/#EncryptPKCS1v15) documentation. _Added in gomplate [v3.8.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.8.0) _ ### Usage crypto.RSAEncrypt key input input | crypto.RSAEncrypt key ### Arguments | name | description | | --- | --- | | `key` | _(required)_ the public key to encrypt the input with | | `input` | _(required)_ the encrypted input | ### Examples $ gomplate -c pubKey=./testPubKey \ -i '{{ "hello" | crypto.RSAEncrypt .pubKey | base64.Encode }}' ScTcX1NZ6p/EeDIf6R7FKLcDFjvP98YgiBhyhPE4jtehajIyTKP1GL8C72qbAWrgdQ6A2cSVjoyo3viqf/PZxpcBDUUMDJuemTaJqUUjMWaDuPG37mQbmRtcvFTuUhw1qSbKyHorDOgTX5d4DvWV4otycGtBT6dXhnmmb5V72J/w3z68vtTJ21m9wREFD7LrYVHdFFtRZiIyMBAF0ngQ+hcujrxilnmgzPkEAg6E7Ccctn28Ie2c4CojrwRbNNxXNlIWCCkC/8Vq8qlDfZ70a+BsTmJDuScE6BZbTyteo9uGYrLn+bTIHNDj90AeLCKUTyWLUJ5Edi9LhlKVBoJUNQ== $ gomplate -c pubKey=./testPubKey \ -i '{{ $enc := "hello" | crypto.RSAEncrypt .pubKey -}} Ciphertext in hex: {{ printf "%x" $enc }}' 71729b87cccabb248b9e0e5173f0b12c01d9d2a0565bad18aef9d332ce984bde06acb8bb69334a01446f7f6430077f269e6fbf2ccacd972fe5856dd4719252ebddf599948d937d96ea41540dad291b868f6c0cf647dffdb5acb22cd33557f9a1ddd0ee6c1ad2bbafc910ba8f817b66ea0569afc06e5c7858fd9dc2638861fe7c97391b2f190e4c682b4aa2c9b0050081efe18b10aa8c2b2b5f5b68a42dcc06c9da35b37fca9b1509fddc940eb99f516a2e0195405bcb3993f0fa31bc038d53d2e7231dff08cc39448105ed2d0ac52d375cb543ca8a399f807cc5d007e2c44c69876d189667eee66361a393c4916826af77479382838cd4e004b8baa05636805a `crypto.RSAGenerateKey` _(experimental)_ ---------------------------------------- **Experimental:** This function is [_experimental_](/config/#experimental) and may be enabled with the [`--experimental`](/config/#experimental) flag. Generate a new RSA Private Key and output in PEM-encoded PKCS#1 ASN.1 DER form. Default key length is 4096 bits, which should be safe enough for most uses, but can be overridden with the optional `bits` parameter. In order to protect against [CWE-326](https://cwe.mitre.org/data/definitions/326.html) , keys shorter than `2048` bits may not be generated. The output is a string, suitable for use with the other `crypto.RSA*` functions. _Added in gomplate [v3.8.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.8.0) _ ### Usage crypto.RSAGenerateKey [bits] bits | crypto.RSAGenerateKey ### Arguments | name | description | | --- | --- | | `bits` | _(optional)_ Length in bits of the generated key. Must be at least `2048`. Defaults to `4096` | ### Examples $ gomplate -i '{{ crypto.RSAGenerateKey }}' -----BEGIN RSA PRIVATE KEY----- ... $ gomplate -i '{{ $key := crypto.RSAGenerateKey 2048 -}} {{ $pub := crypto.RSADerivePublicKey $key -}} {{ $enc := "hello" | crypto.RSAEncrypt $pub -}} {{ crypto.RSADecrypt $key $enc }}' hello `crypto.RSADerivePublicKey` _(experimental)_ -------------------------------------------- **Experimental:** This function is [_experimental_](/config/#experimental) and may be enabled with the [`--experimental`](/config/#experimental) flag. Derive a public key from an RSA private key and output in PKIX ASN.1 DER form. The output is a string, suitable for use with other `crypto.RSA*` functions. _Added in gomplate [v3.8.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.8.0) _ ### Usage crypto.RSADerivePublicKey key key | crypto.RSADerivePublicKey ### Arguments | name | description | | --- | --- | | `key` | _(required)_ the private key to derive a public key from | ### Examples $ gomplate -i '{{ crypto.RSAGenerateKey | crypto.RSADerivePublicKey }}' -----BEGIN PUBLIC KEY----- ... $ gomplate -c privKey=./privKey.pem \ -i '{{ $pub := crypto.RSADerivePublicKey .privKey -}} {{ $enc := "hello" | crypto.RSAEncrypt $pub -}} {{ crypto.RSADecrypt .privKey $enc }}' hello `crypto.SHA1`, `crypto.SHA224`, `crypto.SHA256`, `crypto.SHA384`, `crypto.SHA512`, `crypto.SHA512_224`, `crypto.SHA512_256` --------------------------------------------------------------------------------------------------------------------------- Compute a checksum with a SHA-1 or SHA-2 algorithm as defined in [RFC 3174](https://tools.ietf.org/html/rfc3174) (SHA-1) and [FIPS 180-4](http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf) (SHA-2). These functions output the binary result as a hexadecimal string. _Warning: SHA-1 is cryptographically broken and should not be used for secure applications._ _Added in gomplate [v2.3.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.3.0) _ ### Usage crypto.SHA1 input crypto.SHA224 input crypto.SHA256 input crypto.SHA384 input crypto.SHA512 input crypto.SHA512_224 input crypto.SHA512_256 input ### Arguments | name | description | | --- | --- | | `input` | _(required)_ the data to hash - can be binary data or text | ### Examples $ gomplate -i '{{ crypto.SHA1 "foo" }}' f1d2d2f924e986ac86fdf7b36c94bcdf32beec15 $ gomplate -i '{{ crypto.SHA512 "bar" }}' cc06808cbbee0510331aa97974132e8dc296aeb795be229d064bae784b0a87a5cf4281d82e8c99271b75db2148f08a026c1a60ed9cabdb8cac6d24242dac4063 `crypto.SHA1Bytes`, `crypto.SHA224Bytes`, `crypto.SHA256Bytes`, `crypto.SHA384Bytes`, `crypto.SHA512Bytes`, `crypto.SHA512_224Bytes`, `crypto.SHA512_256Bytes` -------------------------------------------------------------------------------------------------------------------------------------------------------------- Compute a checksum with a SHA-1 or SHA-2 algorithm as defined in [RFC 3174](https://tools.ietf.org/html/rfc3174) (SHA-1) and [FIPS 180-4](http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf) (SHA-2). These functions output the raw binary result, suitable for piping to other functions. _Warning: SHA-1 is cryptographically broken and should not be used for secure applications._ _Added in gomplate [v3.11.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.11.0) _ ### Usage crypto.SHA1Bytes input crypto.SHA224Bytes input crypto.SHA256Bytes input crypto.SHA384Bytes input crypto.SHA512Bytes input crypto.SHA512_224Bytes input crypto.SHA512_256Bytes input ### Arguments | name | description | | --- | --- | | `input` | _(required)_ the data to hash - can be binary data or text | ### Examples $ gomplate -i '{{ crypto.SHA256Bytes "foo" | base64.Encode }}' LCa0a2j/xo/5m0U8HTBBNBNCLXBkg7+g+YpeiGJm564= `crypto.WPAPSK` --------------- This is really an alias to [`crypto.PBKDF2`](#cryptopbkdf2) with the values necessary to convert ASCII passphrases to the WPA pre-shared keys for use with WiFi networks. This can be used, for example, to help generate a configuration for [wpa\_supplicant](http://w1.fi/wpa_supplicant/) . _Added in gomplate [v2.3.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.3.0) _ ### Usage crypto.WPAPSK ssid password ### Arguments | name | description | | --- | --- | | `ssid` | _(required)_ the WiFi SSID (network name) - must be less than 32 characters | | `password` | _(required)_ the password - must be between 8 and 63 characters | ### Examples $ PW=abcd1234 gomplate -i '{{ crypto.WPAPSK "mynet" (getenv "PW") }}' 2c201d66f01237d17d4a7788051191f31706844ac3ffe7547a66c902f2900d34 --- # file functions - gomplate documentation file functions ============== Functions for working with files. `file.Exists` ------------- Reports whether a file or directory exists at the given path. _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage file.Exists path path | file.Exists ### Arguments | name | description | | --- | --- | | `path` | _(required)_ The path | ### Examples _`input.tmpl`:_ {{ if (file.Exists "/tmp/foo") }}yes{{else}}no{{end}} $ gomplate -f input.tmpl no $ touch /tmp/foo $ gomplate -f input.tmpl yes `file.IsDir` ------------ Reports whether a given path is a directory. _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage file.IsDir path path | file.IsDir ### Arguments | name | description | | --- | --- | | `path` | _(required)_ The path | ### Examples _`input.tmpl`:_ {{ if (file.IsDir "/tmp/foo") }}yes{{else}}no{{end}} $ gomplate -f input.tmpl no $ touch /tmp/foo $ gomplate -f input.tmpl no $ rm /tmp/foo && mkdir /tmp/foo $ gomplate -f input.tmpl yes `file.Read` ----------- Reads a given file _as text_. Note that this will succeed if the given file is binary, but the output may be gibberish. _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage file.Read path path | file.Read ### Arguments | name | description | | --- | --- | | `path` | _(required)_ The path | ### Examples $ echo "hello world" > /tmp/hi $ gomplate -i '{{file.Read "/tmp/hi"}}' hello world `file.ReadDir` -------------- Reads a directory and lists the files and directories contained within. _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage file.ReadDir path path | file.ReadDir ### Arguments | name | description | | --- | --- | | `path` | _(required)_ The path | ### Examples $ mkdir /tmp/foo $ touch /tmp/foo/a; touch /tmp/foo/b; touch /tmp/foo/c $ mkdir /tmp/foo/d $ gomplate -i '{{ range (file.ReadDir "/tmp/foo") }}{{.}}{{"\n"}}{{end}}' a b c d `file.Stat` ----------- Returns a [`os.FileInfo`](https://pkg.go.dev/os/#FileInfo) describing the named path. Essentially a wrapper for Go’s [`os.Stat`](https://pkg.go.dev/os/#Stat) function. _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage file.Stat path path | file.Stat ### Arguments | name | description | | --- | --- | | `path` | _(required)_ The path | ### Examples $ echo "hello world" > /tmp/foo $ gomplate -i '{{ $s := file.Stat "/tmp/foo" }}{{ $s.Mode }} {{ $s.Size }} {{ $s.Name }}' -rw-r--r-- 12 foo `file.Walk` ----------- Like a recursive [`file.ReadDir`](#filereaddir) , recursively walks the file tree rooted at `path`, and returns an array of all files and directories contained within. The files are walked in lexical order, which makes the output deterministic but means that for very large directories can be inefficient. Walk does not follow symbolic links. Similar to Go’s [`filepath.Walk`](https://pkg.go.dev/path/filepath/#Walk) function. _Added in gomplate [v2.6.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.6.0) _ ### Usage file.Walk path path | file.Walk ### Arguments | name | description | | --- | --- | | `path` | _(required)_ The path | ### Examples $ tree /tmp/foo /tmp/foo ├── one ├── sub │   ├── one │   └── two ├── three └── two 1 directory, 5 files $ gomplate -i '{{ range file.Walk "/tmp/foo" }}{{ if not (file.IsDir .) }}{{.}} is a file{{"\n"}}{{end}}{{end}}' /tmp/foo/one is a file /tmp/foo/sub/one is a file /tmp/foo/sub/two is a file /tmp/foo/three is a file /tmp/foo/two is a file `file.Write` ------------ Write the given data to the given file. If the file exists, it will be overwritten. For increased security, `file.Write` will only write to files which are contained within the current working directory. Attempts to write elsewhere will fail with an error. Non-existing directories in the output path will be created. If the data is a byte array (`[]byte`), it will be written as-is. Otherwise, it will be converted to a string before being written. _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage file.Write filename data data | file.Write filename ### Arguments | name | description | | --- | --- | | `filename` | _(required)_ The name of the file to write to | | `data` | _(required)_ The data to write | ### Examples $ gomplate -i '{{ file.Write "/tmp/foo" "hello world" }}' $ cat /tmp/foo hello world --- # env functions - gomplate documentation env functions ============= `env.Getenv` ------------ **Alias:** `getenv` Exposes the [os.Getenv](https://pkg.go.dev/os/#Getenv) function. Retrieves the value of the environment variable named by the key. If the variable is unset, but the same variable ending in `_FILE` is set, the contents of the file will be returned. Otherwise the provided default (or an empty string) is returned. This is a more forgiving alternative to using `.Env`, since missing keys will return an empty string, instead of panicking. The `_FILE` fallback is especially useful for use with [12-factor](https://12factor.net) \-style applications configurable only by environment variables, and especially in conjunction with features like [Docker Secrets](https://docs.docker.com/engine/swarm/secrets/#build-support-for-docker-secrets-into-your-images) . _Added in gomplate [v0.2.0](https://github.com/hairyhenderson/gomplate/releases/tag/v0.2.0) _ ### Usage env.Getenv var [default] ### Arguments | name | description | | --- | --- | | `var` | _(required)_ the environment variable name | | `default` | _(optional)_ the default | ### Examples $ gomplate -i 'Hello, {{env.Getenv "USER"}}' Hello, hairyhenderson $ gomplate -i 'Hey, {{getenv "FIRSTNAME" "you"}}!' Hey, you! $ echo "safe" > /tmp/mysecret $ export SECRET_FILE=/tmp/mysecret $ gomplate -i 'Your secret is {{getenv "SECRET"}}' Your secret is safe `env.ExpandEnv` --------------- Exposes the [os.ExpandEnv](https://pkg.go.dev/os/#ExpandEnv) function. Replaces `${var}` or `$var` in the input string according to the values of the current environment variables. References to undefined variables are replaced by the empty string. Like [`env.Getenv`](#envgetenv) , the `_FILE` variant of a variable is used. _Added in gomplate [v2.5.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.5.0) _ ### Usage env.ExpandEnv input ### Arguments | name | description | | --- | --- | | `input` | _(required)_ the input | ### Examples $ gomplate -i '{{env.ExpandEnv "Hello $USER"}}' Hello, hairyhenderson $ gomplate -i 'Hey, {{env.ExpandEnv "Hey, ${FIRSTNAME}!"}}' Hey, you! $ echo "safe" > /tmp/mysecret $ export SECRET_FILE=/tmp/mysecret $ gomplate -i '{{env.ExpandEnv "Your secret is $SECRET"}}' Your secret is safe $ gomplate -i '{{env.ExpandEnv (file.Read "foo")}} contents of file "foo"... --- # path functions - gomplate documentation path functions ============== gomplate’s path functions are split into 2 namespaces: * `path`, which is useful for manipulating slash-based (`/`) paths, such as in URLs * `filepath`, which should be used for local filesystem paths, especially when Windows paths may be involved. This page documents the `path` namespace - see also the [`filepath`](../filepath) documentation. These functions are wrappers for Go’s [`path`](https://pkg.go.dev/path/) and [`path/filepath`](https://pkg.go.dev/path/filepath/) packages. `path.Base` ----------- Returns the last element of path. Trailing slashes are removed before extracting the last element. If the path is empty, Base returns `.`. If the path consists entirely of slashes, Base returns `/`. A wrapper for Go’s [`path.Base`](https://pkg.go.dev/path/#Base) function. _Added in gomplate [v2.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.7.0) _ ### Usage path.Base path path | path.Base ### Arguments | name | description | | --- | --- | | `path` | _(required)_ The input path | ### Examples $ gomplate -i '{{ path.Base "/tmp/foo" }}' foo `path.Clean` ------------ Clean returns the shortest path name equivalent to path by purely lexical processing. A wrapper for Go’s [`path.Clean`](https://pkg.go.dev/path/#Clean) function. _Added in gomplate [v2.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.7.0) _ ### Usage path.Clean path path | path.Clean ### Arguments | name | description | | --- | --- | | `path` | _(required)_ The input path | ### Examples $ gomplate -i '{{ path.Clean "/tmp//foo/../" }}' /tmp `path.Dir` ---------- Returns all but the last element of path, typically the path’s directory. A wrapper for Go’s [`path.Dir`](https://pkg.go.dev/path/#Dir) function. _Added in gomplate [v2.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.7.0) _ ### Usage path.Dir path path | path.Dir ### Arguments | name | description | | --- | --- | | `path` | _(required)_ The input path | ### Examples $ gomplate -i '{{ path.Dir "/tmp/foo" }}' /tmp `path.Ext` ---------- Returns the file name extension used by path. A wrapper for Go’s [`path.Ext`](https://pkg.go.dev/path/#Ext) function. _Added in gomplate [v2.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.7.0) _ ### Usage path.Ext path path | path.Ext ### Arguments | name | description | | --- | --- | | `path` | _(required)_ The input path | ### Examples $ gomplate -i '{{ path.Ext "/tmp/foo.csv" }}' .csv `path.IsAbs` ------------ Reports whether the path is absolute. A wrapper for Go’s [`path.IsAbs`](https://pkg.go.dev/path/#IsAbs) function. _Added in gomplate [v2.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.7.0) _ ### Usage path.IsAbs path path | path.IsAbs ### Arguments | name | description | | --- | --- | | `path` | _(required)_ The input path | ### Examples $ gomplate -i 'the path is {{ if (path.IsAbs "/tmp/foo.csv") }}absolute{{else}}relative{{end}}' the path is absolute $ gomplate -i 'the path is {{ if (path.IsAbs "../foo.csv") }}absolute{{else}}relative{{end}}' the path is relative `path.Join` ----------- Joins any number of path elements into a single path, adding a separating slash if necessary. A wrapper for Go’s [`path.Join`](https://pkg.go.dev/path/#Join) function. _Added in gomplate [v2.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.7.0) _ ### Usage path.Join elem... ### Arguments | name | description | | --- | --- | | `elem...` | _(required)_ The path elements to join (0 or more) | ### Examples $ gomplate -i '{{ path.Join "/tmp" "foo" "bar" }}' /tmp/foo/bar `path.Match` ------------ Reports whether name matches the shell file name pattern. A wrapper for Go’s [`path.Match`](https://pkg.go.dev/path/#Match) function. _Added in gomplate [v2.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.7.0) _ ### Usage path.Match pattern path ### Arguments | name | description | | --- | --- | | `pattern` | _(required)_ The pattern to match on | | `path` | _(required)_ The path to match | ### Examples $ gomplate -i '{{ path.Match "*.csv" "foo.csv" }}' true `path.Split` ------------ Splits path immediately following the final slash, separating it into a directory and file name component. The function returns an array with two values, the first being the directory, and the second the file. A wrapper for Go’s [`path.Split`](https://pkg.go.dev/path/#Split) function. _Added in gomplate [v2.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.7.0) _ ### Usage path.Split path path | path.Split ### Arguments | name | description | | --- | --- | | `path` | _(required)_ The input path | ### Examples $ gomplate -i '{{ $p := path.Split "/tmp/foo" }}{{ $dir := index $p 0 }}{{ $file := index $p 1 }}dir is {{$dir}}, file is {{$file}}' dir is /tmp/, file is foo --- # filepath functions - gomplate documentation filepath functions ================== gomplate’s path functions are split into 2 namespaces: * `path`, which is useful for manipulating slash-based (`/`) paths, such as in URLs * `filepath`, which should be used for local filesystem paths, especially when Windows paths may be involved. This page documents the `filepath` namespace - see also the [`path`](../path) documentation. These functions are wrappers for Go’s [`path/filepath`](https://pkg.go.dev/path/filepath/) package. `filepath.Base` --------------- Returns the last element of path. Trailing path separators are removed before extracting the last element. If the path is empty, Base returns `.`. If the path consists entirely of separators, Base returns a single separator. A wrapper for Go’s [`filepath.Base`](https://pkg.go.dev/path/filepath/#Base) function. _Added in gomplate [v2.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.7.0) _ ### Usage filepath.Base path path | filepath.Base ### Arguments | name | description | | --- | --- | | `path` | _(required)_ The input path | ### Examples $ gomplate -i '{{ filepath.Base "/tmp/foo" }}' foo `filepath.Clean` ---------------- Clean returns the shortest path name equivalent to path by purely lexical processing. A wrapper for Go’s [`filepath.Clean`](https://pkg.go.dev/path/filepath/#Clean) function. _Added in gomplate [v2.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.7.0) _ ### Usage filepath.Clean path path | filepath.Clean ### Arguments | name | description | | --- | --- | | `path` | _(required)_ The input path | ### Examples $ gomplate -i '{{ filepath.Clean "/tmp//foo/../" }}' /tmp `filepath.Dir` -------------- Returns all but the last element of path, typically the path’s directory. A wrapper for Go’s [`filepath.Dir`](https://pkg.go.dev/path/filepath/#Dir) function. _Added in gomplate [v2.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.7.0) _ ### Usage filepath.Dir path path | filepath.Dir ### Arguments | name | description | | --- | --- | | `path` | _(required)_ The input path | ### Examples $ gomplate -i '{{ filepath.Dir "/tmp/foo" }}' /tmp `filepath.Ext` -------------- Returns the file name extension used by path. A wrapper for Go’s [`filepath.Ext`](https://pkg.go.dev/path/filepath/#Ext) function. _Added in gomplate [v2.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.7.0) _ ### Usage filepath.Ext path path | filepath.Ext ### Arguments | name | description | | --- | --- | | `path` | _(required)_ The input path | ### Examples $ gomplate -i '{{ filepath.Ext "/tmp/foo.csv" }}' .csv `filepath.FromSlash` -------------------- Returns the result of replacing each slash (`/`) character in the path with the platform’s separator character. A wrapper for Go’s [`filepath.FromSlash`](https://pkg.go.dev/path/filepath/#FromSlash) function. _Added in gomplate [v2.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.7.0) _ ### Usage filepath.FromSlash path path | filepath.FromSlash ### Arguments | name | description | | --- | --- | | `path` | _(required)_ The input path | ### Examples $ gomplate -i '{{ filepath.FromSlash "/foo/bar" }}' /foo/bar C:\> gomplate.exe -i '{{ filepath.FromSlash "/foo/bar" }}' C:\foo\bar `filepath.IsAbs` ---------------- Reports whether the path is absolute. A wrapper for Go’s [`filepath.IsAbs`](https://pkg.go.dev/path/filepath/#IsAbs) function. _Added in gomplate [v2.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.7.0) _ ### Usage filepath.IsAbs path path | filepath.IsAbs ### Arguments | name | description | | --- | --- | | `path` | _(required)_ The input path | ### Examples $ gomplate -i 'the path is {{ if (filepath.IsAbs "/tmp/foo.csv") }}absolute{{else}}relative{{end}}' the path is absolute $ gomplate -i 'the path is {{ if (filepath.IsAbs "../foo.csv") }}absolute{{else}}relative{{end}}' the path is relative `filepath.Join` --------------- Joins any number of path elements into a single path, adding a separator if necessary. A wrapper for Go’s [`filepath.Join`](https://pkg.go.dev/path/filepath/#Join) function. _Added in gomplate [v2.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.7.0) _ ### Usage filepath.Join elem... ### Arguments | name | description | | --- | --- | | `elem...` | _(required)_ The path elements to join (0 or more) | ### Examples $ gomplate -i '{{ filepath.Join "/tmp" "foo" "bar" }}' /tmp/foo/bar C:\> gomplate.exe -i '{{ filepath.Join "C:\tmp" "foo" "bar" }}' C:\tmp\foo\bar `filepath.Match` ---------------- Reports whether name matches the shell file name pattern. A wrapper for Go’s [`filepath.Match`](https://pkg.go.dev/path/filepath/#Match) function. _Added in gomplate [v2.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.7.0) _ ### Usage filepath.Match pattern path ### Arguments | name | description | | --- | --- | | `pattern` | _(required)_ The pattern to match on | | `path` | _(required)_ The path to match | ### Examples $ gomplate -i '{{ filepath.Match "*.csv" "foo.csv" }}' true `filepath.Rel` -------------- Returns a relative path that is lexically equivalent to targetpath when joined to basepath with an intervening separator. A wrapper for Go’s [`filepath.Rel`](https://pkg.go.dev/path/filepath/#Rel) function. _Added in gomplate [v2.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.7.0) _ ### Usage filepath.Rel basepath targetpath ### Arguments | name | description | | --- | --- | | `basepath` | _(required)_ The base path | | `targetpath` | _(required)_ The target path | ### Examples $ gomplate -i '{{ filepath.Rel "/a" "/a/b/c" }}' b/c `filepath.Split` ---------------- Splits path immediately following the final path separator, separating it into a directory and file name component. The function returns an array with two values, the first being the directory, and the second the file. A wrapper for Go’s [`filepath.Split`](https://pkg.go.dev/path/filepath/#Split) function. _Added in gomplate [v2.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.7.0) _ ### Usage filepath.Split path path | filepath.Split ### Arguments | name | description | | --- | --- | | `path` | _(required)_ The input path | ### Examples $ gomplate -i '{{ $p := filepath.Split "/tmp/foo" }}{{ $dir := index $p 0 }}{{ $file := index $p 1 }}dir is {{$dir}}, file is {{$file}}' dir is /tmp/, file is foo C:\> gomplate.exe -i '{{ $p := filepath.Split `C:\tmp\foo` }}{{ $dir := index $p 0 }}{{ $file := index $p 1 }}dir is {{$dir}}, file is {{$file}}' dir is C:\tmp\, file is foo `filepath.ToSlash` ------------------ Returns the result of replacing each separator character in path with a slash (`/`) character. A wrapper for Go’s [`filepath.ToSlash`](https://pkg.go.dev/path/filepath/#ToSlash) function. _Added in gomplate [v2.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.7.0) _ ### Usage filepath.ToSlash path path | filepath.ToSlash ### Arguments | name | description | | --- | --- | | `path` | _(required)_ The input path | ### Examples $ gomplate -i '{{ filepath.ToSlash "/foo/bar" }}' /foo/bar C:\> gomplate.exe -i '{{ filepath.ToSlash `foo\bar\baz` }}' foo/bar/baz `filepath.VolumeName` --------------------- Returns the leading volume name. Given `C:\foo\bar` it returns `C:` on Windows. Given a UNC like `\\host\share\foo` it returns `\\host\share`. On other platforms it returns an empty string. A wrapper for Go’s [`filepath.VolumeName`](https://pkg.go.dev/path/filepath/#VolumeName) function. _Added in gomplate [v2.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.7.0) _ ### Usage filepath.VolumeName path path | filepath.VolumeName ### Arguments | name | description | | --- | --- | | `path` | _(required)_ The input path | ### Examples C:\> gomplate.exe -i 'volume is {{ filepath.VolumeName "C:/foo/bar" }}' volume is C: $ gomplate -i 'volume is {{ filepath.VolumeName "/foo/bar" }}' volume is --- # test functions - gomplate documentation test functions ============== The `test` namespace contains some simple functions to help validate assumptions and can cause template generation to fail in specific cases. `test.Assert` ------------- **Alias:** `assert` Asserts that the given expression or value is `true`. If it is not, causes template generation to fail immediately with an optional message. _Added in gomplate [v2.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.7.0) _ ### Usage test.Assert [message] value value | test.Assert [message] ### Arguments | name | description | | --- | --- | | `message` | _(optional)_ The optional message to provide in the case of failure | | `value` | _(required)_ The value to test | ### Examples $ gomplate -i '{{ assert (eq "foo" "bar") }}' template: :1:3: executing "" at : error calling assert: assertion failed $ gomplate -i '{{ assert "something horrible happened" false }}' template: :1:3: executing "" at : error calling assert: assertion failed: something horrible happened `test.Fail` ----------- **Alias:** `fail` Cause template generation to fail immediately, with an optional message. _Added in gomplate [v2.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.7.0) _ ### Usage test.Fail [message] message | test.Fail ### Arguments | name | description | | --- | --- | | `message` | _(optional)_ The optional message to provide | ### Examples $ gomplate -i '{{ fail }}' template: :1:3: executing "" at : error calling fail: template generation failed $ gomplate -i '{{ test.Fail "something is wrong!" }}' template: :1:7: executing "" at : error calling Fail: template generation failed: something is wrong! `test.IsKind` ------------- **Alias:** `isKind` Report whether the argument is of the given Kind. Can be used to render different templates depending on the kind of data. See [the Go `reflect` source code](https://github.com/golang/go/blob/36fcde1676a0d3863cb5f295eed6938cd782fcbb/src/reflect/type.go#L595..L622) for the complete list, but these are some common values: * `string` * `bool` * `int`, `int64`, `uint64` * `float64` * `slice` * `map` * `invalid` (a catch-all, usually just `nil` values) In addition, the special kind `number` is accepted by this function, to represent _any_ numeric kind (whether `float32`, `uint8`, or whatever). This is useful when the specific numeric type is unknown. See also [`test.Kind`](#testkind) . _Added in gomplate [v3.8.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.8.0) _ ### Usage test.IsKind kind value value | test.IsKind kind ### Arguments | name | description | | --- | --- | | `kind` | _(required)_ the kind to compare with (see description for possible values) | | `value` | _(required)_ the value to check | ### Examples $ gomplate -i '{{ $data := "hello world" }} {{- if isKind "string" $data }}{{ $data }} is a string{{ end }}' hello world is a string $ gomplate -i '{{ $object := dict "key1" true "key2" "foobar" }} {{- if test.IsKind "map" $object }} Got a map: {{ range $key, $value := $object -}} - "{{ $key }}": {{ $value }} {{ end }} {{ else if test.IsKind "number" $object }} Got a number: {{ $object }} {{ end }}' Got a map: - "key1": true - "key2": foobar `test.Kind` ----------- **Alias:** `kind` Report the _kind_ of the given argument. This differs from the _type_ of the argument in specificity; for example, while a slice of strings may have a type of `[]string`, the _kind_ of that slice will simply be `slice`. If you need to know the precise type of a value, use `printf "%T" $value`. See also [`test.IsKind`](#testiskind) . _Added in gomplate [v3.8.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.8.0) _ ### Usage test.Kind value value | test.Kind ### Arguments | name | description | | --- | --- | | `value` | _(required)_ the value to check | ### Examples $ gomplate -i '{{ kind "hello world" }}' string $ gomplate -i '{{ dict "key1" true "key2" "foobar" | test.Kind }}' map `test.Required` --------------- **Alias:** `required` Passes through the given value, if it’s non-empty, and non-`nil`. Otherwise, exits and prints a given error message so the user can adjust as necessary. This is particularly useful for cases where templates require user-provided data (such as datasources or environment variables), and rendering can not continue correctly. This was inspired by [Helm’s `required` function](https://github.com/kubernetes/helm/blob/master/docs/charts_tips_and_tricks.md#know-your-template-functions) , but has slightly different behaviour. Notably, gomplate will always fail in cases where a referenced _key_ is missing, and this function will have no effect. _Added in gomplate [v3.0.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.0.0) _ ### Usage test.Required [message] value value | test.Required [message] ### Arguments | name | description | | --- | --- | | `message` | _(optional)_ The optional message to provide when the required value is not provided | | `value` | _(required)_ The required value | ### Examples $ FOO=foobar gomplate -i '{{ getenv "FOO" | required "Missing FOO environment variable!" }}' foobar $ FOO= gomplate -i '{{ getenv "FOO" | required "Missing FOO environment variable!" }}' error: Missing FOO environment variable! $ cat < config.yaml defined: a value empty: "" EOF $ gomplate -d config=config.yaml -i '{{ (ds "config").defined | required "The `config` datasource must have a value defined for `defined`" }}' a value $ gomplate -d config=config.yaml -i '{{ (ds "config").empty | required "The `config` datasource must have a value defined for `empty`" }}' template: :1:25: executing "" at : error calling required: The `config` datasource must have a value defined for `empty` $ gomplate -d config=config.yaml -i '{{ (ds "config").bogus | required "The `config` datasource must have a value defined for `bogus`" }}' template: :1:7: executing "" at <"config">: map has no entry for key "bogus" `test.Ternary` -------------- **Alias:** `ternary` Returns one of two values depending on whether the third is true. Note that the third value does not have to be a boolean - it is converted first by the [`conv.ToBool`](../conv/#convtobool) function (values like `true`, `1`, `"true"`, `"Yes"`, etc… are considered true). This is effectively a short-form of the following template: {{ if conv.ToBool $condition }}{{ $truevalue }}{{ else }}{{ $falsevalue }}{{ end }} Keep in mind that using an explicit `if`/`else` block is often easier to understand than ternary expressions! _Added in gomplate [v3.1.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.1.0) _ ### Usage test.Ternary truevalue falsevalue condition condition | test.Ternary truevalue falsevalue ### Arguments | name | description | | --- | --- | | `truevalue` | _(required)_ the value to return if `condition` is true | | `falsevalue` | _(required)_ the value to return if `condition` is false | | `condition` | _(required)_ the value to evaluate for truthiness | ### Examples $ gomplate -i '{{ ternary "FOO" "BAR" false }}' BAR $ gomplate -i '{{ ternary "FOO" "BAR" "yes" }}' FOO --- # math functions - gomplate documentation math functions ============== A set of basic math functions to be able to perform simple arithmetic operations with `gomplate`. ### Supported input In general, any input will be converted to the correct input type by the various functions in this package, and an appropriately-typed value will be returned type. Special cases are documented. In addition to regular base-10 numbers, integers can be [specified](https://golang.org/ref/spec#Integer_literals) as octal (prefix with `0`) or hexadecimal (prefix with `0x`). Decimal/floating-point numbers can be [specified](https://golang.org/ref/spec#Floating-point_literals) with optional exponents. Some examples demonstrating this: $ NUM=50 gomplate -i '{{ div (getenv "NUM") 10 }}' 5 $ gomplate -i '{{ add "0x2" "02" "2.0" "2e0" }}' 8 $ gomplate -i '{{ add 2.5 2.5 }}' 5.0 `math.Abs` ---------- Returns the absolute value of a given number. When the input is an integer, the result will be an `int64`, otherwise it will be a `float64`. _Added in gomplate [v2.6.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.6.0) _ ### Usage math.Abs num ### Arguments | name | description | | --- | --- | | `num` | _(required)_ The input number | ### Examples $ gomplate -i '{{ math.Abs -3.5 }} {{ math.Abs 3.5 }} {{ math.Abs -42 }}' 3.5 3.5 42 `math.Add` ---------- **Alias:** `add` Adds all given operators. When one of the inputs is a floating-point number, the result will be a `float64`, otherwise it will be an `int64`. _Added in gomplate [v2.2.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.2.0) _ ### Usage math.Add n... ### Arguments | name | description | | --- | --- | | `n...` | _(required)_ The numbers to add together | ### Examples $ gomplate -i '{{ math.Add 1 2 3 4 }} {{ math.Add 1.5 2 3 }}' 10 6.5 `math.Ceil` ----------- Returns the least integer value greater than or equal to a given floating-point number. This wraps Go’s [`math.Ceil`](https://pkg.go.dev/math/#Ceil) . **Note:** the return value of this function is a `float64` so that the special-cases `NaN` and `Inf` can be returned appropriately. _Added in gomplate [v2.6.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.6.0) _ ### Usage math.Ceil num ### Arguments | name | description | | --- | --- | | `num` | _(required)_ The input number. Will be converted to a `float64`, or `0` if not convertible | ### Examples $ gomplate -i '{{ range (coll.Slice 5.1 42 "3.14" "0xFF" "NaN" "Inf" "-0") }}ceil {{ printf "%#v" . }} = {{ math.Ceil . }}{{"\n"}}{{ end }}' ceil 5.1 = 6 ceil 42 = 42 ceil "3.14" = 4 ceil "0xFF" = 255 ceil "NaN" = NaN ceil "Inf" = +Inf ceil "-0" = 0 `math.Div` ---------- **Alias:** `div` Divide the first number by the second. Division by zero is disallowed. The result will be a `float64`. _Added in gomplate [v2.2.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.2.0) _ ### Usage math.Div a b b | math.Div a ### Arguments | name | description | | --- | --- | | `a` | _(required)_ The divisor | | `b` | _(required)_ The dividend | ### Examples $ gomplate -i '{{ math.Div 8 2 }} {{ math.Div 3 2 }}' 4 1.5 `math.Floor` ------------ Returns the greatest integer value less than or equal to a given floating-point number. This wraps Go’s [`math.Floor`](https://pkg.go.dev/math/#Floor) . **Note:** the return value of this function is a `float64` so that the special-cases `NaN` and `Inf` can be returned appropriately. _Added in gomplate [v2.6.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.6.0) _ ### Usage math.Floor num ### Arguments | name | description | | --- | --- | | `num` | _(required)_ The input number. Will be converted to a `float64`, or `0` if not convertible | ### Examples $ gomplate -i '{{ range (coll.Slice 5.1 42 "3.14" "0xFF" "NaN" "Inf" "-0") }}floor {{ printf "%#v" . }} = {{ math.Floor . }}{{"\n"}}{{ end }}' floor 5.1 = 4 floor 42 = 42 floor "3.14" = 3 floor "0xFF" = 255 floor "NaN" = NaN floor "Inf" = +Inf floor "-0" = 0 `math.IsFloat` -------------- Returns whether or not the given number can be interpreted as a floating-point literal, as defined by the [Go language reference](https://golang.org/ref/spec#Floating-point_literals) . **Note:** If a decimal point is part of the input number, it will be considered a floating-point number, even if the decimal is `0`. _Added in gomplate [v2.6.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.6.0) _ ### Usage math.IsFloat num ### Arguments | name | description | | --- | --- | | `num` | _(required)_ The value to test | ### Examples $ gomplate -i '{{ range (coll.Slice 1.0 "-1.0" 5.1 42 "3.14" "foo" "0xFF" "NaN" "Inf" "-0") }}{{ if (math.IsFloat .) }}{{.}} is a float{{"\n"}}{{ end }}{{end}}' 1 is a float -1.0 is a float 5.1 is a float 3.14 is a float NaN is a float Inf is a float `math.IsInt` ------------ Returns whether or not the given number is an integer. _Added in gomplate [v2.6.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.6.0) _ ### Usage math.IsInt num ### Arguments | name | description | | --- | --- | | `num` | _(required)_ The value to test | ### Examples $ gomplate -i '{{ range (coll.Slice 1.0 "-1.0" 5.1 42 "3.14" "foo" "0xFF" "NaN" "Inf" "-0") }}{{ if (math.IsInt .) }}{{.}} is an integer{{"\n"}}{{ end }}{{end}}' 42 is an integer 0xFF is an integer -0 is an integer `math.IsNum` ------------ Returns whether the given input is a number. Useful for `if` conditions. _Added in gomplate [v2.6.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.6.0) _ ### Usage math.IsNum in ### Arguments | name | description | | --- | --- | | `in` | _(required)_ The value to test | ### Examples $ gomplate -i '{{ math.IsNum "foo" }} {{ math.IsNum 0xDeadBeef }}' false true `math.Max` ---------- Returns the largest number provided. If any values are floating-point numbers, a `float64` is returned, otherwise an `int64` is returned. The same special-cases as Go’s [`math.Max`](https://pkg.go.dev/math/#Max) are followed. _Added in gomplate [v2.6.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.6.0) _ ### Usage math.Max nums... ### Arguments | name | description | | --- | --- | | `nums...` | _(required)_ One or more numbers to compare | ### Examples $ gomplate -i '{{ math.Max 0 8.0 4.5 "-1.5e-11" }}' 8 `math.Min` ---------- Returns the smallest number provided. If any values are floating-point numbers, a `float64` is returned, otherwise an `int64` is returned. The same special-cases as Go’s [`math.Min`](https://pkg.go.dev/math/#Min) are followed. _Added in gomplate [v2.6.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.6.0) _ ### Usage math.Min nums... ### Arguments | name | description | | --- | --- | | `nums...` | _(required)_ One or more numbers to compare | ### Examples $ gomplate -i '{{ math.Min 0 8 4.5 "-1.5e-11" }}' -1.5e-11 `math.Mul` ---------- **Alias:** `mul` Multiply all given operators together. _Added in gomplate [v2.2.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.2.0) _ ### Usage math.Mul n... ### Arguments | name | description | | --- | --- | | `n...` | _(required)_ The numbers to multiply | ### Examples $ gomplate -i '{{ math.Mul 8 8 2 }}' 128 `math.Pow` ---------- **Alias:** `pow` Calculate an exponent - _bn_. This wraps Go’s [`math.Pow`](https://pkg.go.dev/math/#Pow) . If any values are floating-point numbers, a `float64` is returned, otherwise an `int64` is returned. _Added in gomplate [v2.2.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.2.0) _ ### Usage math.Pow b n ### Arguments | name | description | | --- | --- | | `b` | _(required)_ The base | | `n` | _(required)_ The exponent | ### Examples $ gomplate -i '{{ math.Pow 10 2 }}' 100 $ gomplate -i '{{ math.Pow 2 32 }}' 4294967296 $ gomplate -i '{{ math.Pow 1.5 2 }}' 2.2 `math.Rem` ---------- **Alias:** `rem` Return the remainder from an integer division operation. _Added in gomplate [v2.2.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.2.0) _ ### Usage math.Rem a b b | math.Rem a ### Arguments | name | description | | --- | --- | | `a` | _(required)_ The divisor | | `b` | _(required)_ The dividend | ### Examples $ gomplate -i '{{ math.Rem 5 3 }}' 2 $ gomplate -i '{{ math.Rem -5 3 }}' -2 `math.Round` ------------ Returns the nearest integer, rounding half away from zero. **Note:** the return value of this function is a `float64` so that the special-cases `NaN` and `Inf` can be returned appropriately. _Added in gomplate [v2.6.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.6.0) _ ### Usage math.Round num ### Arguments | name | description | | --- | --- | | `num` | _(required)_ The input number. Will be converted to a `float64`, or `0` if not convertible | ### Examples $ gomplate -i '{{ range (coll.Slice -6.5 5.1 42.9 "3.5" 6.5) }}round {{ printf "%#v" . }} = {{ math.Round . }}{{"\n"}}{{ end }}' round -6.5 = -7 round 5.1 = 5 round 42.9 = 43 round "3.5" = 4 round 6.5 = 7 `math.Seq` ---------- **Alias:** `seq` Return a sequence from `start` to `end`, in steps of `step`. Can handle counting down as well as up, including with negative numbers. Note that the sequence _may_ not end at `end`, if `end` is not divisible by `step`. _Added in gomplate [v2.2.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.2.0) _ ### Usage math.Seq [start] end [step] ### Arguments | name | description | | --- | --- | | `start` | _(optional)_ The first number in the sequence (defaults to `1`) | | `end` | _(required)_ The last number in the sequence | | `step` | _(optional)_ The amount to increment between each number (defaults to `1`) | ### Examples $ gomplate -i '{{ range (math.Seq 5) }}{{.}} {{end}}' 1 2 3 4 5 $ gomplate -i '{{ conv.Join (math.Seq 10 -3 2) ", " }}' 10, 8, 6, 4, 2, 0, -2 `math.Sub` ---------- **Alias:** `sub` Subtract the second from the first of the given operators. When one of the inputs is a floating-point number, the result will be a `float64`, otherwise it will be an `int64`. _Added in gomplate [v2.2.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.2.0) _ ### Usage math.Sub a b b | math.Sub a ### Arguments | name | description | | --- | --- | | `a` | _(required)_ The minuend (the number to subtract from) | | `b` | _(required)_ The subtrahend (the number being subtracted) | ### Examples $ gomplate -i '{{ math.Sub 3 1 }}' 2 --- # semver functions - gomplate documentation semver functions ================ These functions allow user you to parse a [semantic version](http://semver.org/) string or test it with constraint. It’s implemented with the [https://github.com/Masterminds/semver](https://github.com/Masterminds/semver) library. `semver.Semver`_(unreleased)_ ----------------------------- **Unreleased:** _This function is in development, and not yet available in released builds of gomplate._ Returns a semantic version struct holding the `input` version string. The returned struct are defined at: [`semver.Version`](https://pkg.go.dev/github.com/Masterminds/semver/v3#Version) . ### Usage semver.Semver input input | semver.Semver ### Arguments | name | description | | --- | --- | | `input` | _(required)_ The input to parse | ### Examples $ gomplate -i '{{ semver.Semver "v1.1.1"}}' 1.1.1 $ gomplate -i '{{ (semver.Semver "v1.1.1").Major }}' 1 $ gomplate -i 'the pre release version is {{ ("v1.1.1" | semver.Semver).SetPrerelease "beta.1" }}' the pre release version is 1.1.1-beta.1 `semver.CheckConstraint`_(unreleased)_ -------------------------------------- **Unreleased:** _This function is in development, and not yet available in released builds of gomplate._ Test whether the input version matches the constraint. Ref: [https://github.com/Masterminds/semver#checking-version-constraints](https://github.com/Masterminds/semver#checking-version-constraints) ### Usage semver.CheckConstraint constraint input input | semver.CheckConstraint constraint ### Arguments | name | description | | --- | --- | | `constraint` | _(required)_ The constraints expression to test. | | `input` | _(required)_ The input semantic version string to test. | ### Examples $ gomplate -i '{{ semver.CheckConstraint "> 1.0" "v1.1.1" }}' true $ gomplate -i '{{ semver.CheckConstraint "> 1.0, <1.1" "v1.1.1" }}' false $ gomplate -i '{{ "v1.1.1" | semver.CheckConstraint "> 1.0" }}' true --- # template functions - gomplate documentation template functions ================== Functions for defining or executing templates. `tmpl.Exec` ----------- Execute (render) the named template. This is equivalent to using the [`template`](https://pkg.go.dev/text/template/#hdr-Actions) action, except the result is returned as a string. This allows for post-processing of templates. _Added in gomplate [v3.3.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.3.0) _ ### Usage tmpl.Exec name [context] context | tmpl.Exec name ### Arguments | name | description | | --- | --- | | `name` | _(required)_ The template’s name. | | `context` | _(optional)_ The context to use. | ### Examples $ gomplate -i '{{define "T1"}}hello, world!{{end}}{{ tmpl.Exec "T1" | strings.ToUpper }}' HELLO, WORLD! $ gomplate -i '{{define "T1"}}hello, {{.}}{{end}}{{ tmpl.Exec "T1" "world!" | strings.Title }}' Hello, World! `tmpl.Inline` ------------- **Alias:** `tpl` Render the given string as a template, just like a nested template. If the template is given a name (see `name` argument below), it can be re-used later with the `template` keyword. A context can be provided, otherwise the default gomplate context will be used. _Added in gomplate [v3.3.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.3.0) _ ### Usage tmpl.Inline [name] in [context] ### Arguments | name | description | | --- | --- | | `name` | _(optional)_ The template’s name. | | `in` | _(required)_ The template to render, as a string | | `context` | _(optional)_ The context to use when rendering - this becomes `.` inside the template. | ### Examples $ gomplate -i '{{ tmpl.Inline "{{print `hello world`}}" }}' hello world $ gomplate -i ' {{ $tstring := "{{ print .value ` world` }}" }} {{ $context := dict "value" "hello" }} {{ tpl "T1" $tstring $context }} {{ template "T1" (dict "value" "goodbye") }} ' hello world goodbye world `tmpl.Path` ----------- Output the path of the current template, if it came from a file. For inline templates, this will be an empty string. Note that if this function is called from a nested template, the path of the main template will be returned instead. _Added in gomplate [v3.11.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.11.0) _ ### Usage tmpl.Path ### Examples _`subdir/input.tpl`:_ this template is in {{ tmpl.Path }} $ gomplate -f subdir/input.tpl this template is in subdir/input.tpl `tmpl.PathDir` -------------- Output the current template’s directory. For inline templates, this will be an empty string. Note that if this function is called from a nested template, the path of the main template will be used instead. _Added in gomplate [v3.11.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.11.0) _ ### Usage tmpl.PathDir ### Examples _`subdir/input.tpl`:_ this template is in {{ tmpl.Dir }} $ gomplate -f subdir/input.tpl this template is in subdir --- # random functions - gomplate documentation random functions ================ Functions for generating random values. ### About randomness `gomplate` uses Go’s [`math/rand`](https://pkg.go.dev/math/rand/) package to generate pseudo-random numbers. Note that these functions are not suitable for use in security-sensitive applications, such as cryptography. However, these functions will not deplete system entropy. `random.ASCII` -------------- Generates a random string of a desired length, containing the set of printable characters from the 7-bit [ASCII](https://en.wikipedia.org/wiki/ASCII) set. This includes _space_ (’ ‘), but no other whitespace characters. _Added in gomplate [v3.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.4.0) _ ### Usage random.ASCII count ### Arguments | name | description | | --- | --- | | `count` | _(required)_ the length of the string to produce (number of characters) | ### Examples $ gomplate -i '{{ random.ASCII 8 }}' _woJ%D&K `random.Alpha` -------------- Generates a random alphabetical (`A-Z`, `a-z`) string of a desired length. _Added in gomplate [v3.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.4.0) _ ### Usage random.Alpha count ### Arguments | name | description | | --- | --- | | `count` | _(required)_ the length of the string to produce (number of characters) | ### Examples $ gomplate -i '{{ random.Alpha 42 }}' oAqHKxHiytYicMxTMGHnUnAfltPVZDhFkVkgDvatJK `random.AlphaNum` ----------------- Generates a random alphanumeric (`0-9`, `A-Z`, `a-z`) string of a desired length. _Added in gomplate [v3.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.4.0) _ ### Usage random.AlphaNum count ### Arguments | name | description | | --- | --- | | `count` | _(required)_ the length of the string to produce (number of characters) | ### Examples $ gomplate -i '{{ random.AlphaNum 16 }}' 4olRl9mRmVp1nqSm `random.String` --------------- Generates a random string of a desired length. By default, the possible characters are those represented by the regular expression `[a-zA-Z0-9_.-]` (alphanumeric, plus `_`, `.`, and `-`). A different set of characters can be specified with a regular expression, or by giving a range of possible characters by specifying the lower and upper bounds. Lower/upper bounds can be specified as characters (e.g. `"q"`, or escape sequences such as `"\U0001f0AF"`), or numeric Unicode code-points (e.g. `48` or `0x30` for the character `0`). When given a range of Unicode code-points, `random.String` will discard non-printable characters from the selection. This may result in a much smaller set of possible characters than intended, so check the [Unicode character code charts](http://www.unicode.org/charts/) to verify the correct code-points. _Added in gomplate [v3.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.4.0) _ ### Usage random.String count [regex] [lower] [upper] ### Arguments | name | description | | --- | --- | | `count` | _(required)_ the length of the string to produce (number of characters) | | `regex` | _(optional)_ the regular expression that each character must match (defaults to `[a-zA-Z0-9_.-]`) | | `lower` | _(optional)_ lower bound for a range of characters (number or single character) | | `upper` | _(optional)_ upper bound for a range of characters (number or single character) | ### Examples $ gomplate -i '{{ random.String 8 }}' FODZ01u_ $ gomplate -i '{{ random.String 16 `[[:xdigit:]]` }}' B9e0527C3e45E1f3 $ gomplate -i '{{ random.String 20 `[\p{Canadian_Aboriginal}]` }}' ᗄᖖᣡᕔᕫᗝᖴᒙᗌᘔᓰᖫᗵᐕᗵᙔᗠᓅᕎᔹ $ gomplate -i '{{ random.String 8 "c" "m" }}' ffmidgjc $ gomplate -i 'You rolled... {{ random.String 3 "⚀" "⚅" }}' You rolled... ⚅⚂⚁ $ gomplate -i 'Poker time! {{ random.String 5 "\U0001f0a1" "\U0001f0de" }}' Poker time! 🂼🂺🂳🃅🂪 `random.Item` ------------- Pick an element at a random from a given slice or array. _Added in gomplate [v3.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.4.0) _ ### Usage random.Item items items | random.Item ### Arguments | name | description | | --- | --- | | `items` | _(required)_ the input array | ### Examples $ gomplate -i '{{ random.Item (seq 0 5) }}' 4 $ export SLICE='["red", "green", "blue"]' $ gomplate -i '{{ getenv "SLICE" | jsonArray | random.Item }}' blue `random.Number` --------------- Pick a random integer. By default, a number between `0` and `100` (inclusive) is chosen, but this range can be overridden. Note that the difference between `min` and `max` can not be larger than a 63-bit integer (i.e. the unsigned portion of a 64-bit signed integer). The result is given as an `int64`. _Added in gomplate [v3.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.4.0) _ ### Usage random.Number [min] [max] ### Arguments | name | description | | --- | --- | | `min` | _(optional)_ The minimum value, defaults to `0`. Must be less than `max`. | | `max` | _(optional)_ The maximum value, defaults to `100` (if no args provided) | ### Examples $ gomplate -i '{{ random.Number }}' 55 $ gomplate -i '{{ random.Number -10 10 }}' -3 $ gomplate -i '{{ random.Number 5 }}' 2 `random.Float` -------------- Pick a random decimal floating-point number. By default, a number between `0.0` and `1.0` (_exclusive_, i.e. `[0.0,1.0)`) is chosen, but this range can be overridden.\ \ The result is given as a `float64`.\ \ _Added in gomplate [v3.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.4.0)\ _\ \ ### Usage\ \ random.Float [min] [max]\ \ ### Arguments\ \ | name | description |\ | --- | --- |\ | `min` | _(optional)_ The minimum value, defaults to `0.0`. Must be less than `max`. |\ | `max` | _(optional)_ The maximum value, defaults to `1.0` (if no args provided). |\ \ ### Examples\ \ $ gomplate -i '{{ random.Float }}'\ 0.2029946480303966\ \ \ $ gomplate -i '{{ random.Float 100 }}' \ 71.28595374161743\ \ \ $ gomplate -i '{{ random.Float -100 200 }}'\ 105.59119437834909 --- # regexp functions - gomplate documentation regexp functions ================ These functions allow user you to search and modify text with regular expressions. The syntax of the regular expressions accepted is [Go’s `regexp` syntax](https://pkg.go.dev/regexp/syntax/#hdr-Syntax) , and is the same general syntax used by Perl, Python, and other languages. `regexp.Find` ------------- Returns a string holding the text of the leftmost match in `input` of the regular expression `expression`. This function provides the same behaviour as Go’s [`regexp.FindString`](https://pkg.go.dev/regexp/#Regexp.FindString) function. _Added in gomplate [v3.1.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.1.0) _ ### Usage regexp.Find expression input input | regexp.Find expression ### Arguments | name | description | | --- | --- | | `expression` | _(required)_ The regular expression | | `input` | _(required)_ The input to search | ### Examples $ gomplate -i '{{ regexp.Find "[a-z]{3}" "foobar"}}' foo $ gomplate -i 'no {{ "will not match" | regexp.Find "[0-9]" }}numbers' no numbers `regexp.FindAll` ---------------- Returns a list of all successive matches of the regular expression. This can be called with 2 or 3 arguments. When called with 2 arguments, the `n` argument (number of matches) will be set to `-1`, causing all matches to be returned. This function provides the same behaviour as Go’s [`regexp.FindAllString`](https://pkg.go.dev/regexp#Regexp.FindAllString) function. _Added in gomplate [v3.1.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.1.0) _ ### Usage regexp.FindAll expression [n] input input | regexp.FindAll expression [n] ### Arguments | name | description | | --- | --- | | `expression` | _(required)_ The regular expression | | `n` | _(optional)_ The number of matches to return | | `input` | _(required)_ The input to search | ### Examples $ gomplate -i '{{ regexp.FindAll "[a-z]{3}" "foobar" | toJSON}}' ["foo", "bar"] $ gomplate -i '{{ "foo bar baz qux" | regexp.FindAll "[a-z]{3}" 3 | toJSON}}' ["foo", "bar", "baz"] `regexp.Match` -------------- Returns `true` if a given regular expression matches a given input. This returns a boolean which can be used in an `if` condition, for example. _Added in gomplate [v1.9.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.9.0) _ ### Usage regexp.Match expression input input | regexp.Match expression ### Arguments | name | description | | --- | --- | | `expression` | _(required)_ The regular expression | | `input` | _(required)_ The input to test | ### Examples $ gomplate -i '{{ if (.Env.USER | regexp.Match `^h`) }}username ({{.Env.USER}}) starts with h!{{end}}' username (hairyhenderson) starts with h! `regexp.QuoteMeta` ------------------ Escapes all regular expression metacharacters in the input. The returned string is a regular expression matching the literal text. This function provides the same behaviour as Go’s [`regexp.QuoteMeta`](https://pkg.go.dev/regexp#QuoteMeta) function. _Added in gomplate [v3.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.7.0) _ ### Usage regexp.QuoteMeta input input | regexp.QuoteMeta ### Arguments | name | description | | --- | --- | | `input` | _(required)_ The input to escape | ### Examples $ gomplate -i '{{ `{hello}` | regexp.QuoteMeta }}' \{hello\} `regexp.Replace` ---------------- Replaces matches of a regular expression with the replacement string. The replacement is substituted after expanding variables beginning with `$`. This function provides the same behaviour as Go’s [`regexp.ReplaceAllString`](https://pkg.go.dev/regexp/#Regexp.ReplaceAllString) function. _Added in gomplate [v1.9.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.9.0) _ ### Usage regexp.Replace expression replacement input input | regexp.Replace expression replacement ### Arguments | name | description | | --- | --- | | `expression` | _(required)_ The regular expression string | | `replacement` | _(required)_ The replacement string | | `input` | _(required)_ The input string to operate on | ### Examples $ gomplate -i '{{ regexp.Replace "(foo)bar" "$1" "foobar"}}' foo $ gomplate -i '{{ regexp.Replace "(?P[a-zA-Z]+) (?P[a-zA-Z]+)" "${last}, ${first}" "Alan Turing"}}' Turing, Alan `regexp.ReplaceLiteral` ----------------------- Replaces matches of a regular expression with the replacement string. The replacement is substituted directly, without expanding variables beginning with `$`. This function provides the same behaviour as Go’s [`regexp.ReplaceAllLiteralString`](https://pkg.go.dev/regexp/#Regexp.ReplaceAllLiteralString) function. _Added in gomplate [v3.1.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.1.0) _ ### Usage regexp.ReplaceLiteral expression replacement input input | regexp.ReplaceLiteral expression replacement ### Arguments | name | description | | --- | --- | | `expression` | _(required)_ The regular expression string | | `replacement` | _(required)_ The replacement string | | `input` | _(required)_ The input string to operate on | ### Examples $ gomplate -i '{{ regexp.ReplaceLiteral "(foo)bar" "$1" "foobar"}}' $1 $ gomplate -i '{{ `foo.bar,baz` | regexp.ReplaceLiteral `\W` `$` }}' foo$bar$baz `regexp.Split` -------------- Splits `input` into sub-strings, separated by the expression. This can be called with 2 or 3 arguments. When called with 2 arguments, the `n` argument (number of matches) will be set to `-1`, causing all sub-strings to be returned. This is equivalent to [`strings.SplitN`](../strings/#stringssplitn) , except that regular expressions are supported. This function provides the same behaviour as Go’s [`regexp.Split`](https://pkg.go.dev/regexp/#Regexp.Split) function. _Added in gomplate [v3.1.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.1.0) _ ### Usage regexp.Split expression [n] input input | regexp.Split expression [n] ### Arguments | name | description | | --- | --- | | `expression` | _(required)_ The regular expression | | `n` | _(optional)_ The number of matches to return | | `input` | _(required)_ The input to search | ### Examples $ gomplate -i '{{ regexp.Split `[\s,.]` "foo bar,baz.qux" | toJSON}}' ["foo","bar","baz","qux"] $ gomplate -i '{{ "foo bar.baz,qux" | regexp.Split `[\s,.]` 3 | toJSON}}' ["foo","bar","baz"] --- # net functions - gomplate documentation net functions ============= The `net` namespace contains functions that can help deal with network-related lookups and calculations. Some of these functions return specifically-typed values that contain additional methods useful for formatting or further calculations. `net.LookupIP` -------------- Resolve an IPv4 address for a given host name. When multiple IP addresses are resolved, the first one is returned. _Added in gomplate [v1.9.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.9.0) _ ### Usage net.LookupIP name name | net.LookupIP ### Arguments | name | description | | --- | --- | | `name` | _(required)_ The hostname to look up. This can be a simple hostname, or a fully-qualified domain name. | ### Examples $ gomplate -i '{{ net.LookupIP "example.com" }}' 93.184.216.34 `net.LookupIPs` --------------- Resolve all IPv4 addresses for a given host name. Returns an array of strings. _Added in gomplate [v1.9.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.9.0) _ ### Usage net.LookupIPs name name | net.LookupIPs ### Arguments | name | description | | --- | --- | | `name` | _(required)_ The hostname to look up. This can be a simple hostname, or a fully-qualified domain name. | ### Examples $ gomplate -i '{{ join (net.LookupIPs "twitter.com") "," }}' 104.244.42.65,104.244.42.193 `net.LookupCNAME` ----------------- Resolve the canonical name for a given host name. This does a DNS lookup for the `CNAME` record type. If no `CNAME` is present, a canonical form of the given name is returned – e.g. `net.LookupCNAME "localhost"` will return `"localhost."`. _Added in gomplate [v1.9.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.9.0) _ ### Usage net.LookupCNAME name name | net.LookupCNAME ### Arguments | name | description | | --- | --- | | `name` | _(required)_ The hostname to look up. This can be a simple hostname, or a fully-qualified domain name. | ### Examples $ gomplate -i '{{ net.LookupCNAME "www.amazon.com" }}' d3ag4hukkh62yn.cloudfront.net. `net.LookupSRV` --------------- Resolve a DNS [`SRV` service record](https://en.wikipedia.org/wiki/SRV_record) . This implementation supports the canonical [RFC2782](https://tools.ietf.org/html/rfc2782) form (i.e. `_Service._Proto.Name`), but other forms are also supported, such as those served by [Consul’s DNS interface](https://developer.hashicorp.com/consul/docs/services/discovery/dns-dynamic-lookups#standard-lookup) . When multiple records are returned, this function returns the first. A [`net.SRV`](https://pkg.go.dev/net/#SRV) data structure is returned. The following properties are available: * `Target` - _(string)_ the hostname where the service can be reached * `Port` - _(uint16)_ the service’s port * `Priority`, `Weight` - see [RFC2782](https://tools.ietf.org/html/rfc2782) for details _Added in gomplate [v1.9.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.9.0) _ ### Usage net.LookupSRV name name | net.LookupSRV ### Arguments | name | description | | --- | --- | | `name` | _(required)_ The service name to look up | ### Examples $ gomplate -i '{{ net.LookupSRV "_sip._udp.sip.voice.google.com" | toJSONPretty " " }}' { "Port": 5060, "Priority": 10, "Target": "sip-anycast-1.voice.google.com.", "Weight": 1 } `net.LookupSRVs` ---------------- Resolve a DNS [`SRV` service record](https://en.wikipedia.org/wiki/SRV_record) . This implementation supports the canonical [RFC2782](https://tools.ietf.org/html/rfc2782) form (i.e. `_Service._Proto.Name`), but other forms are also supported, such as those served by [Consul’s DNS interface](https://developer.hashicorp.com/consul/docs/services/discovery/dns-dynamic-lookups#standard-lookup) . This function returns all available SRV records. An array of [`net.SRV`](https://pkg.go.dev/net/#SRV) data structures is returned. For each element, the following properties are available: * `Target` - _(string)_ the hostname where the service can be reached * `Port` - _(uint16)_ the service’s port * `Priority`, `Weight` - see [RFC2782](https://tools.ietf.org/html/rfc2782) for details _Added in gomplate [v1.9.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.9.0) _ ### Usage net.LookupSRVs name name | net.LookupSRVs ### Arguments | name | description | | --- | --- | | `name` | _(required)_ The hostname to look up. This can be a simple hostname, or a fully-qualified domain name. | ### Examples _input.tmpl:_ {{ range (net.LookupSRVs "_sip._udp.sip.voice.google.com") -}} priority={{.Priority}}/port={{.Port}} {{- end }} $ gomplate -f input.tmpl priority=10/port=5060 priority=20/port=5060 `net.LookupTXT` --------------- Resolve a DNS [`TXT` record](https://en.wikipedia.org/wiki/SRV_record) . This function returns all available TXT records as an array of strings. _Added in gomplate [v1.9.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.9.0) _ ### Usage net.LookupTXT name name | net.LookupTXT ### Arguments | name | description | | --- | --- | | `name` | _(required)_ The host name to look up | ### Examples $ gomplate -i '{{net.LookupTXT "example.com" | data.ToJSONPretty " " }}' [\ "v=spf1 -all"\ ] `net.ParseAddr` --------------- Parse the given string as an IP address (a [`netip.Addr`](https://pkg.go.dev/net/netip#Addr) ). Any of `netip.Addr`’s methods may be called on the resulting value. See [the docs](https://pkg.go.dev/net/netip#Addr) for details. _Added in gomplate [v4.0.0](https://github.com/hairyhenderson/gomplate/releases/tag/v4.0.0) _ ### Usage net.ParseAddr addr addr | net.ParseAddr ### Arguments | name | description | | --- | --- | | `addr` | _(required)_ The IP string to parse. It must be either an IPv4 or IPv6 address. | ### Examples $ gomplate -i '{{ (net.ParseAddr "192.168.0.1").IsPrivate }}' true $ gomplate -i '{{ $ip := net.ParseAddr (net.LookupIP "example.com") -}} {{ $ip.Prefix 12 }}' 93.176.0.0/12 `net.ParseIP` _(deprecated)_ ---------------------------- **Deprecation Notice:** Use [`net.ParseAddr`](#netparseaddr) instead. Parse the given string as an IP address (a `netaddr.IP` from the [`inet.af/netaddr`](https://pkg.go.dev/inet.af/netaddr) package). Any of `netaddr.IP`’s methods may be called on the resulting value. See [the docs](https://pkg.go.dev/inet.af/netaddr) for details. _Added in gomplate [v3.10.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.10.0) _ ### Usage net.ParseIP ip ip | net.ParseIP ### Arguments | name | description | | --- | --- | | `ip` | _(required)_ The IP string to parse. It must be either an IPv4 or IPv6 address. | ### Examples $ gomplate -i '{{ (net.ParseIP "192.168.0.1").IsPrivate }}' true $ gomplate -i '{{ $ip := net.ParseIP (net.LookupIP "example.com") -}} {{ $ip.Prefix 12 }}' 93.176.0.0/12 `net.ParsePrefix` ----------------- Parse the given string as an IP address prefix (CIDR) representing an IP network (a [`netip.Prefix`](https://pkg.go.dev/net/netip#Prefix) ). The string can be in the form `"192.168.1.0/24"` or `"2001::db8::/32"`, the CIDR notations defined in [RFC 4632](http://tools.ietf.org/html/rfc4632) and [RFC 4291](http://tools.ietf.org/html/rfc4291) . Any of `netip.Prefix`’s methods may be called on the resulting value. See [the docs](https://pkg.go.dev/net/netip#Prefix) for details. _Added in gomplate [v4.0.0](https://github.com/hairyhenderson/gomplate/releases/tag/v4.0.0) _ ### Usage net.ParsePrefix prefix prefix | net.ParsePrefix ### Arguments | name | description | | --- | --- | | `prefix` | _(required)_ The IP address prefix to parse. It must represent either an IPv4 or IPv6 prefix, containing a `/`. | ### Examples $ gomplate -i '{{ (net.ParsePrefix "192.168.0.0/24").Range }}' 192.168.0.0-192.168.0.255 $ gomplate -i '{{ $ip := net.ParseAddr (net.LookupIP "example.com") -}} {{ $net := net.ParsePrefix "93.184.0.0/16" -}} {{ $net.Contains $ip }}' true `net.ParseIPPrefix` _(deprecated)_ ---------------------------------- **Deprecation Notice:** Use [`net.ParsePrefix`](#netparseprefix) instead. Parse the given string as an IP address prefix (CIDR) representing an IP network (a `netaddr.IPPrefix` from the [`inet.af/netaddr`](https://pkg.go.dev/inet.af/netaddr) package). The string can be in the form `"192.168.1.0/24"` or `"2001::db8::/32"`, the CIDR notations defined in [RFC 4632](http://tools.ietf.org/html/rfc4632) and [RFC 4291](http://tools.ietf.org/html/rfc4291) . Any of `netaddr.IPPrefix`’s methods may be called on the resulting value. See [the docs](https://pkg.go.dev/inet.af/netaddr) for details. _Added in gomplate [v3.10.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.10.0) _ ### Usage net.ParseIPPrefix ipprefix ipprefix | net.ParseIPPrefix ### Arguments | name | description | | --- | --- | | `ipprefix` | _(required)_ The IP address prefix to parse. It must represent either an IPv4 or IPv6 prefix, containing a `/`. | ### Examples $ gomplate -i '{{ (net.ParseIPPrefix "192.168.0.0/24").Range }}' 192.168.0.0-192.168.0.255 $ gomplate -i '{{ $ip := net.ParseIP (net.LookupIP "example.com") -}} {{ $net := net.ParseIPPrefix "93.184.0.0/16" -}} {{ $net.Contains $ip }}' true $ gomplate -i '{{ $net := net.ParseIPPrefix "93.184.0.0/12" -}} {{ $net.Range }}' 93.176.0.0-93.191.255.255 `net.ParseRange` _(experimental)_ --------------------------------- **Experimental:** This function is [_experimental_](/config/#experimental) and may be enabled with the [`--experimental`](/config/#experimental) flag. Parse the given string as an inclusive range of IP addresses from the same address family (a [`netipx.IPRange`](https://pkg.go.dev/go4.org/netipx#IPRange) from the [`go4.org/netipx`](https://pkg.go.dev/go4.org/netipx) module). The string must contain a hyphen (`-`). Any of `netipx.IPRange`’s methods may be called on the resulting value. See [the docs](https://pkg.go.dev/go4.org/netipx#IPRange) for details. Note that this function is experimental for now, because it uses a [third-party module](https://pkg.go.dev/go4.org/netipx) which may be brought into the standard library in the future, which may require breaking changes to this function. _Added in gomplate [v4.0.0](https://github.com/hairyhenderson/gomplate/releases/tag/v4.0.0) _ ### Usage net.ParseRange iprange iprange | net.ParseRange ### Arguments | name | description | | --- | --- | | `iprange` | _(required)_ The IP address range to parse. It must represent either an IPv4 or IPv6 range, containing a `-`. | ### Examples $ gomplate -i '{{ (net.ParseRange "192.168.0.0-192.168.0.255").To }}' 192.168.0.255 $ gomplate -i '{{ $range := net.ParseRange "1.2.3.0-1.2.3.233" -}} {{ $range.Prefixes }}' [1.2.3.0/25 1.2.3.128/26 1.2.3.192/27 1.2.3.224/29 1.2.3.232/31] `net.ParseIPRange` _(deprecated)_ --------------------------------- **Deprecation Notice:** Use [`net.ParseRange`](#netparserange-_experimental_) instead. Parse the given string as an inclusive range of IP addresses from the same address family (a `netaddr.IPRange` from the [`inet.af/netaddr`](https://pkg.go.dev/inet.af/netaddr) package). The string must contain a hyphen (`-`). Any of `netaddr.IPRange`’s methods may be called on the resulting value. See [the docs](https://pkg.go.dev/inet.af/netaddr) for details. _Added in gomplate [v3.10.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.10.0) _ ### Usage net.ParseIPRange iprange iprange | net.ParseIPRange ### Arguments | name | description | | --- | --- | | `iprange` | _(required)_ The IP address range to parse. It must represent either an IPv4 or IPv6 range, containing a `-`. | ### Examples $ gomplate -i '{{ (net.ParseIPRange "192.168.0.0-192.168.0.255").To }}' 192.168.0.255 $ gomplate -i '{{ $range := net.ParseIPRange "1.2.3.0-1.2.3.233" -}} {{ $range.Prefixes }}' [1.2.3.0/25 1.2.3.128/26 1.2.3.192/27] `net.CIDRHost` _(experimental)_ ------------------------------- **Experimental:** This function is [_experimental_](/config/#experimental) and may be enabled with the [`--experimental`](/config/#experimental) flag. Calculates a full host IP address for a given host number within a given IP network address prefix. The IP network can be in the form `"192.168.1.0/24"` or `"2001::db8::/32"`, the CIDR notations defined in [RFC 4632](http://tools.ietf.org/html/rfc4632) and [RFC 4291](http://tools.ietf.org/html/rfc4291) . Any of `netip.Addr`’s methods may be called on the resulting value. See [the docs](https://pkg.go.dev/net/netip#Addr) for details. _Added in gomplate [v3.11.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.11.0) _ ### Usage net.CIDRHost hostnum prefix prefix | net.CIDRHost hostnum ### Arguments | name | description | | --- | --- | | `hostnum` | _(required)_ Is a whole number that can be represented as a binary integer with no more than the number of digits remaining in the address after the given prefix. | | `prefix` | _(required)_ Must be given in CIDR notation. It must represent either an IPv4 or IPv6 prefix, containing a `/`. String or [`net.IPNet`](https://pkg.go.dev/net#IPNet)
object returned from `net.ParseIPPrefix` can by used. | ### Examples $ gomplate -i '{{ "10.12.127.0/20" | net.CIDRHost 268 }}' 10.12.113.12 `net.CIDRNetmask` _(experimental)_ ---------------------------------- **Experimental:** This function is [_experimental_](/config/#experimental) and may be enabled with the [`--experimental`](/config/#experimental) flag. The result is a subnet address formatted in the conventional dotted-decimal IPv4 address syntax or hexadecimal IPv6 address syntax, as expected by some software. Any of `netip.Addr`’s methods may be called on the resulting value. See [the docs](https://pkg.go.dev/net/netip#Addr) for details. _Added in gomplate [v3.11.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.11.0) _ ### Usage net.CIDRNetmask prefix prefix | net.CIDRNetmask ### Arguments | name | description | | --- | --- | | `prefix` | _(required)_ Must be given in CIDR notation. It must represent either an IPv4 or IPv6 prefix, containing a `/`. String or [`net.IPNet`](https://pkg.go.dev/net#IPNet)
object returned from `net.ParseIPPrefix` can by used. | ### Examples $ gomplate -i '{{ net.CIDRNetmask "10.12.127.0/20" }}' 255.255.240.0 $ gomplate -i '{{ net.CIDRNetmask "fd00:fd12:3456:7890:00a2::/72" }}' ffff:ffff:ffff:ffff:ff00:: `net.CIDRSubnets` _(experimental)_ ---------------------------------- **Experimental:** This function is [_experimental_](/config/#experimental) and may be enabled with the [`--experimental`](/config/#experimental) flag. Calculates a subnet address within given IP network address prefix. Any of `netip.Prefix`’s methods may be called on the resulting values. See [the docs](https://pkg.go.dev/net/netip#Prefix) for details. _Added in gomplate [v3.11.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.11.0) _ ### Usage net.CIDRSubnets newbits prefix prefix | net.CIDRSubnets newbits ### Arguments | name | description | | --- | --- | | `newbits` | _(required)_ Is the number of additional bits with which to extend the prefix. For example, if given a prefix ending in `/16` and a `newbits` value of `4`, the resulting subnet address will have length `/20`. | | `prefix` | _(required)_ Must be given in CIDR notation. It must represent either an IPv4 or IPv6 prefix, containing a `/`. String or [`net.IPNet`](https://pkg.go.dev/net#IPNet)
object returned from `net.ParseIPPrefix` can by used. | ### Examples $ gomplate -i '{{ index ("10.0.0.0/16" | net.CIDRSubnets 2) 1 }}' 10.0.64.0/18 $ gomplate -i '{{ net.CIDRSubnets 2 "10.0.0.0/16" -}}' [10.0.0.0/18 10.0.64.0/18 10.0.128.0/18 10.0.192.0/18] `net.CIDRSubnetSizes` _(experimental)_ -------------------------------------- **Experimental:** This function is [_experimental_](/config/#experimental) and may be enabled with the [`--experimental`](/config/#experimental) flag. Calculates a sequence of consecutive IP address ranges within a particular CIDR prefix. Any of `netip.Prefix`’s methods may be called on the resulting values. See [the docs](https://pkg.go.dev/net/netip#Prefix) for details. _Added in gomplate [v3.11.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.11.0) _ ### Usage net.CIDRSubnetSizes newbits... prefix prefix | net.CIDRSubnetSizes newbits... ### Arguments | name | description | | --- | --- | | `newbits...` | _(required)_ Numbers of additional network prefix bits for returned address range. | | `prefix` | _(required)_ Must be given in CIDR notation. It must represent either an IPv4 or IPv6 prefix, containing a `/`. String or [`net.IPNet`](https://pkg.go.dev/net#IPNet)
object returned from `net.ParseIPPrefix` can by used. | ### Examples $ gomplate -i '{{ net.CIDRSubnetSizes 4 4 8 4 "10.1.0.0/16" -}}' [10.1.0.0/20 10.1.16.0/20 10.1.32.0/24 10.1.48.0/20] --- # strings functions - gomplate documentation strings functions ================= `strings.Abbrev` ---------------- Abbreviates a string using `...` (ellipses). Takes an optional offset from the beginning of the string, and a maximum final width (including added ellipses). _Also see [`strings.Trunc`](#stringstrunc) ._ _Added in gomplate [v2.6.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.6.0) _ ### Usage strings.Abbrev [offset] width input input | strings.Abbrev [offset] width ### Arguments | name | description | | --- | --- | | `offset` | _(optional)_ offset from the start of the string. Must be `4` or greater for ellipses to be added. Defaults to `0` | | `width` | _(required)_ the desired maximum final width of the string, including ellipses | | `input` | _(required)_ the input string to abbreviate | ### Examples $ gomplate -i '{{ "foobarbazquxquux" | strings.Abbrev 9 }}' foobar... $ gomplate -i '{{ "foobarbazquxquux" | strings.Abbrev 6 9 }}' ...baz... `strings.Contains` ------------------ Reports whether a substring is contained within a string. _Added in gomplate [v1.9.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.9.0) _ ### Usage strings.Contains substr input input | strings.Contains substr ### Arguments | name | description | | --- | --- | | `substr` | _(required)_ the substring to search for | | `input` | _(required)_ the input to search | ### Examples _`input.tmpl`:_ {{ if (.Env.FOO | strings.Contains "f") }}yes{{else}}no{{end}} $ FOO=foo gomplate < input.tmpl yes $ FOO=bar gomplate < input.tmpl no `strings.HasPrefix` ------------------- Tests whether a string begins with a certain prefix. _Added in gomplate [v1.9.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.9.0) _ ### Usage strings.HasPrefix prefix input input | strings.HasPrefix prefix ### Arguments | name | description | | --- | --- | | `prefix` | _(required)_ the prefix to search for | | `input` | _(required)_ the input to search | ### Examples $ URL=http://example.com gomplate -i '{{if .Env.URL | strings.HasPrefix "https"}}foo{{else}}bar{{end}}' bar $ URL=https://example.com gomplate -i '{{if .Env.URL | strings.HasPrefix "https"}}foo{{else}}bar{{end}}' foo `strings.HasSuffix` ------------------- Tests whether a string ends with a certain suffix. _Added in gomplate [v1.9.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.9.0) _ ### Usage strings.HasSuffix suffix input input | strings.HasSuffix suffix ### Arguments | name | description | | --- | --- | | `suffix` | _(required)_ the suffix to search for | | `input` | _(required)_ the input to search | ### Examples _`input.tmpl`:_ {{.Env.URL}}{{if not (.Env.URL | strings.HasSuffix ":80")}}:80{{end}} $ URL=http://example.com gomplate < input.tmpl http://example.com:80 `strings.Indent` ---------------- **Alias:** `indent` Indents a string. If the input string has multiple lines, each line will be indented. As of v4.0.0, this function will error if the `width` or `indent` arguments are invalid. _Added in gomplate [v1.9.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.9.0) _ ### Usage strings.Indent [width] [indent] input input | strings.Indent [width] [indent] ### Arguments | name | description | | --- | --- | | `width` | _(optional)_ Number of times to repeat the `indent` string. Must be greater than 0. Default: `1` | | `indent` | _(optional)_ The string to indent with. Must not contain a newline character ("\\n"). Default: `" "` | | `input` | _(required)_ The string to indent | ### Examples This function can be especially useful when adding YAML snippets into other YAML documents, where indentation is important: _`input.tmpl`:_ foo: {{ `{"bar": {"baz": 2}}` | json | toYAML | strings.Indent " " }} {{- `{"qux": true}` | json | toYAML | strings.Indent 2 }} quux: {{ `{"quuz": 42}` | json | toYAML | strings.Indent 2 " " -}} $ gomplate -f input.tmpl foo: bar: baz: 2 qux: true quux: quuz: 42 `strings.Sort` _(deprecated)_ ----------------------------- **Deprecation Notice:** Use [`coll.Sort`](../coll/#collsort) instead Returns an alphanumerically-sorted copy of a given string list. _Added in gomplate [v2.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.7.0) _ ### Usage strings.Sort list list | strings.Sort ### Arguments | name | description | | --- | --- | | `list` | _(required)_ The list to sort | ### Examples $ gomplate -i '{{ (coll.Slice "foo" "bar" "baz") | strings.Sort }}' [bar baz foo] `strings.SkipLines` ------------------- Skips the given number of lines (each ending in a `\n`), returning the remainder. If `skip` is greater than the number of lines in `in`, an empty string is returned. _Added in gomplate [v4.0.0](https://github.com/hairyhenderson/gomplate/releases/tag/v4.0.0) _ ### Usage strings.SkipLines skip in in | strings.SkipLines skip ### Arguments | name | description | | --- | --- | | `skip` | _(required)_ the number of lines to skip - must be a positive number | | `in` | _(required)_ the input string | ### Examples $ gomplate -i '{{ "foo\nbar\nbaz" | strings.SkipLines 2 }}' baz $ gomplate -i '{{ strings.SkipLines 1 "foo\nbar\nbaz" }}' bar baz `strings.Split` --------------- _Not to be confused with [`split`](#split-_deprecated_) , which is deprecated._ Slices `input` into the substrings separated by `separator`, returning a slice of the substrings between those separators. If `input` does not contain `separator` and `separator` is not empty, returns a single-element slice whose only element is `input`. If `separator` is empty, it will split after each UTF-8 sequence. If both inputs are empty (i.e. `strings.Split "" ""`), it will return an empty slice. This is equivalent to [`strings.SplitN`](#stringssplitn) with a `count` of `-1`. Note that the delimiter is not included in the resulting elements. _Added in gomplate [v1.9.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.9.0) _ ### Usage strings.Split separator input input | strings.Split separator ### Arguments | name | description | | --- | --- | | `separator` | _(required)_ the delimiter to split on, can be multiple characters | | `input` | _(required)_ the input string | ### Examples $ gomplate -i '{{range ("Bart,Lisa,Maggie" | strings.Split ",") }}Hello, {{.}} {{end}}' Hello, Bart Hello, Lisa Hello, Maggie $ gomplate -i '{{range strings.Split "," "One,Two,Three" }}{{.}}{{"\n"}}{{end}}' One Two Three `strings.SplitN` ---------------- _Not to be confused with [`splitN`](#splitn-_deprecated_) , which is deprecated._ Slices `input` into the substrings separated by `separator`, returning a slice of the substrings between those separators. If `input` does not contain `separator` and `separator` is not empty, returns a single-element slice whose only element is `input`. The `count` determines the number of substrings to return: * `count > 0`: at most `count` substrings; the last substring will be the unsplit remainder. * `count == 0`: the result is nil (zero substrings) * `count < 0`: all substrings See [`strings.Split`](#stringssplit) for more details. _Added in gomplate [v1.9.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.9.0) _ ### Usage strings.SplitN separator count input input | strings.SplitN separator count ### Arguments | name | description | | --- | --- | | `separator` | _(required)_ the delimiter to split on, can be multiple characters | | `count` | _(required)_ the maximum number of substrings to return | | `input` | _(required)_ the input string | ### Examples $ gomplate -i '{{ range ("foo:bar:baz" | strings.SplitN ":" 2) }}{{.}} {{end}}' foo bar:baz `strings.Quote` --------------- **Alias:** `quote` Surrounds an input string with double-quote characters (`"`). If the input is not a string, converts first. `"` characters in the input are first escaped with a `\` character. This is a convenience function which is equivalent to: {{ print "%q" "input string" }} _Added in gomplate [v3.1.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.1.0) _ ### Usage strings.Quote in in | strings.Quote ### Arguments | name | description | | --- | --- | | `in` | _(required)_ The input to quote | ### Examples $ gomplate -i '{{ "in" | quote }}' "in" $ gomplate -i '{{ strings.Quote 500 }}' "500" `strings.Repeat` ---------------- Returns a new string consisting of `count` copies of the input string. It errors if `count` is negative or if the length of `input` multiplied by `count` overflows. This wraps Go’s [`strings.Repeat`](https://pkg.go.dev/strings/#Repeat) . _Added in gomplate [v2.6.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.6.0) _ ### Usage strings.Repeat count input input | strings.Repeat count ### Arguments | name | description | | --- | --- | | `count` | _(required)_ the number of times to repeat the input | | `input` | _(required)_ the input to repeat | ### Examples $ gomplate -i '{{ "hello " | strings.Repeat 5 }}' hello hello hello hello hello `strings.ReplaceAll` -------------------- **Alias:** `replaceAll` Replaces all occurrences of a given string with another. _Added in gomplate [v1.9.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.9.0) _ ### Usage strings.ReplaceAll old new input input | strings.ReplaceAll old new ### Arguments | name | description | | --- | --- | | `old` | _(required)_ the text to replace | | `new` | _(required)_ the new text to replace with | | `input` | _(required)_ the input to modify | ### Examples $ gomplate -i '{{ strings.ReplaceAll "." "-" "172.21.1.42" }}' 172-21-1-42 $ gomplate -i '{{ "172.21.1.42" | strings.ReplaceAll "." "-" }}' 172-21-1-42 `strings.Slug` -------------- Creates a a “slug” from a given string - supports Unicode correctly. This wraps the [github.com/gosimple/slug](https://github.com/gosimple/slug) package. See [the github.com/gosimple/slug docs](https://godoc.org/github.com/gosimple/slug) for more information. _Added in gomplate [v2.6.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.6.0) _ ### Usage strings.Slug input input | strings.Slug ### Arguments | name | description | | --- | --- | | `input` | _(required)_ the input to “slugify” | ### Examples $ gomplate -i '{{ "Hello, world!" | strings.Slug }}' hello-world $ echo 'Rock & Roll @ Cafe Wha?' | gomplate -d in=stdin: -i '{{ strings.Slug (include "in") }}' rock-and-roll-at-cafe-wha `strings.ShellQuote` -------------------- **Alias:** `shellQuote` Given a string, emits a version of that string that will evaluate to its literal data when expanded by any POSIX-compliant shell. Given an array or slice, emit a single string which will evaluate to a series of shell words, one per item in that array or slice. _Added in gomplate [v3.6.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.6.0) _ ### Usage strings.ShellQuote in in | strings.ShellQuote ### Arguments | name | description | | --- | --- | | `in` | _(required)_ The input to quote | ### Examples $ gomplate -i "{{ coll.Slice \"one word\" \"foo='bar baz'\" | shellQuote }}" 'one word' 'foo='"'"'bar baz'"'"'' $ gomplate -i "{{ strings.ShellQuote \"it's a banana\" }}" 'it'"'"'s a banana' `strings.Squote` ---------------- **Alias:** `squote` Surrounds an input string with a single-quote (apostrophe) character (`'`). If the input is not a string, converts first. `'` characters in the input are first escaped in the YAML-style (by repetition: `''`). _Added in gomplate [v3.1.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.1.0) _ ### Usage strings.Squote in in | strings.Squote ### Arguments | name | description | | --- | --- | | `in` | _(required)_ The input to quote | ### Examples $ gomplate -i '{{ "in" | squote }}' 'in' $ gomplate -i "{{ strings.Squote \"it's a banana\" }}" 'it''s a banana' `strings.Title` --------------- **Alias:** `title` Convert to title-case. _Added in gomplate [v1.9.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.9.0) _ ### Usage strings.Title input input | strings.Title ### Arguments | name | description | | --- | --- | | `input` | _(required)_ the input | ### Examples $ gomplate -i '{{strings.Title "hello, world!"}}' Hello, World! `strings.ToLower` ----------------- **Alias:** `toLower` Convert to lower-case. _Added in gomplate [v1.9.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.9.0) _ ### Usage strings.ToLower input input | strings.ToLower ### Arguments | name | description | | --- | --- | | `input` | _(required)_ the input | ### Examples $ echo '{{strings.ToLower "HELLO, WORLD!"}}' | gomplate hello, world! `strings.ToUpper` ----------------- **Alias:** `toUpper` Convert to upper-case. _Added in gomplate [v1.9.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.9.0) _ ### Usage strings.ToUpper input input | strings.ToUpper ### Arguments | name | description | | --- | --- | | `input` | _(required)_ the input | ### Examples $ gomplate -i '{{strings.ToUpper "hello, world!"}}' HELLO, WORLD! `strings.Trim` -------------- Trims a string by removing the given characters from the beginning and end of the string. _Added in gomplate [v1.9.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.9.0) _ ### Usage strings.Trim cutset input input | strings.Trim cutset ### Arguments | name | description | | --- | --- | | `cutset` | _(required)_ the set of characters to cut | | `input` | _(required)_ the input | ### Examples $ gomplate -i '{{ "_-foo-_" | strings.Trim "_-" }}' foo `strings.TrimLeft` ------------------ Trims a string by removing the given characters from the beginning of the string. This wraps Go’s [`strings.TrimLeft`](https://pkg.go.dev/strings#TrimLeft) . _Added in gomplate [v4.1.0](https://github.com/hairyhenderson/gomplate/releases/tag/v4.1.0) _ ### Usage strings.TrimLeft cutset input input | strings.TrimLeft cutset ### Arguments | name | description | | --- | --- | | `cutset` | _(required)_ the set of characters to cut | | `input` | _(required)_ the input | ### Examples $ gomplate -i '{{ " - hello, world!" | strings.TrimLeft " " }}' - hello, world! `strings.TrimPrefix` -------------------- Returns a string without the provided leading prefix string, if the prefix is present. This wraps Go’s [`strings.TrimPrefix`](https://pkg.go.dev/strings/#TrimPrefix) . _Added in gomplate [v2.5.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.5.0) _ ### Usage strings.TrimPrefix prefix input input | strings.TrimPrefix prefix ### Arguments | name | description | | --- | --- | | `prefix` | _(required)_ the prefix to trim | | `input` | _(required)_ the input | ### Examples $ gomplate -i '{{ "hello, world" | strings.TrimPrefix "hello, " }}' world `strings.TrimRight` ------------------- Trims a string by removing the given characters from the end of the string. This wraps Go’s [`strings.TrimRight`](https://pkg.go.dev/strings#TrimRight) . _Added in gomplate [v4.1.0](https://github.com/hairyhenderson/gomplate/releases/tag/v4.1.0) _ ### Usage strings.TrimRight cutset input input | strings.TrimRight cutset ### Arguments | name | description | | --- | --- | | `cutset` | _(required)_ the set of characters to cut | | `input` | _(required)_ the input | ### Examples $ gomplate -i '{{ "hello, world! " | strings.TrimRight " " }}' hello, world! `strings.TrimSpace` ------------------- **Alias:** `trimSpace` Trims a string by removing whitespace from the beginning and end of the string. _Added in gomplate [v1.9.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.9.0) _ ### Usage strings.TrimSpace input input | strings.TrimSpace ### Arguments | name | description | | --- | --- | | `input` | _(required)_ the input | ### Examples $ gomplate -i '{{ " \n\t foo" | strings.TrimSpace }}' foo `strings.TrimSuffix` -------------------- Returns a string without the provided trailing suffix string, if the suffix is present. This wraps Go’s [`strings.TrimSuffix`](https://pkg.go.dev/strings/#TrimSuffix) . _Added in gomplate [v2.6.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.6.0) _ ### Usage strings.TrimSuffix suffix input input | strings.TrimSuffix suffix ### Arguments | name | description | | --- | --- | | `suffix` | _(required)_ the suffix to trim | | `input` | _(required)_ the input | ### Examples $ gomplate -i '{{ "hello, world" | strings.TrimSuffix "world" }}jello' hello, jello `strings.Trunc` --------------- Returns a string truncated to the given length. _Also see [`strings.Abbrev`](#stringsabbrev) ._ _Added in gomplate [v2.6.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.6.0) _ ### Usage strings.Trunc length input input | strings.Trunc length ### Arguments | name | description | | --- | --- | | `length` | _(required)_ the maximum length of the output | | `input` | _(required)_ the input | ### Examples $ gomplate -i '{{ "hello, world" | strings.Trunc 5 }}' hello `strings.CamelCase` ------------------- Converts a sentence to CamelCase, i.e. `The quick brown fox` becomes `TheQuickBrownFox`. All non-alphanumeric characters are stripped, and the beginnings of words are upper-cased. If the input begins with a lower-case letter, the result will also begin with a lower-case letter. See [CamelCase on Wikipedia](https://en.wikipedia.org/wiki/Camel_case) for more details. _Added in gomplate [v3.3.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.3.0) _ ### Usage strings.CamelCase in in | strings.CamelCase ### Arguments | name | description | | --- | --- | | `in` | _(required)_ The input | ### Examples $ gomplate -i '{{ "Hello, World!" | strings.CamelCase }}' HelloWorld $ gomplate -i '{{ "hello jello" | strings.CamelCase }}' helloJello `strings.SnakeCase` ------------------- Converts a sentence to snake\_case, i.e. `The quick brown fox` becomes `The_quick_brown_fox`. All non-alphanumeric characters are stripped, and spaces are replaced with an underscore (`_`). If the input begins with a lower-case letter, the result will also begin with a lower-case letter. See [Snake Case on Wikipedia](https://en.wikipedia.org/wiki/Snake_case) for more details. _Added in gomplate [v3.3.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.3.0) _ ### Usage strings.SnakeCase in in | strings.SnakeCase ### Arguments | name | description | | --- | --- | | `in` | _(required)_ The input | ### Examples $ gomplate -i '{{ "Hello, World!" | strings.SnakeCase }}' Hello_world $ gomplate -i '{{ "hello jello" | strings.SnakeCase }}' hello_jello `strings.KebabCase` ------------------- Converts a sentence to kebab-case, i.e. `The quick brown fox` becomes `The-quick-brown-fox`. All non-alphanumeric characters are stripped, and spaces are replaced with a hyphen (`-`). If the input begins with a lower-case letter, the result will also begin with a lower-case letter. See [Kebab Case on Wikipedia](https://en.wikipedia.org/wiki/Kebab_case) for more details. _Added in gomplate [v3.3.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.3.0) _ ### Usage strings.KebabCase in in | strings.KebabCase ### Arguments | name | description | | --- | --- | | `in` | _(required)_ The input | ### Examples $ gomplate -i '{{ "Hello, World!" | strings.KebabCase }}' Hello-world $ gomplate -i '{{ "hello jello" | strings.KebabCase }}' hello-jello `strings.WordWrap` ------------------ Inserts new line breaks into the input string so it ends up with lines that are at most `width` characters wide. The line-breaking algorithm is _naïve_ and _greedy_: lines are only broken between words (i.e. on whitespace characters), and no effort is made to “smooth” the line endings. When words that are longer than the desired width are encountered (e.g. long URLs), they are not broken up. Correctness is valued above line length. The line-break sequence defaults to `\n` (i.e. the LF/Line Feed character), regardless of OS. _Added in gomplate [v3.3.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.3.0) _ ### Usage strings.WordWrap [width] [lbseq] in in | strings.WordWrap [width] [lbseq] ### Arguments | name | description | | --- | --- | | `width` | _(optional)_ The desired maximum line length (number of characters - defaults to `80`) | | `lbseq` | _(optional)_ The line-break sequence to use (defaults to `\n`) | | `in` | _(required)_ The input | ### Examples $ gomplate -i '{{ "Hello, World!" | strings.WordWrap 7 }}' Hello, World! $ gomplate -i '{{ strings.WordWrap 20 "\\\n" "a string with a long url http://example.com/a/very/long/url which should not be broken" }}' a string with a long url http://example.com/a/very/long/url which should not be broken `strings.RuneCount` ------------------- Return the number of _runes_ (Unicode code-points) contained within the input. This is similar to the built-in `len` function, but `len` counts the length in _bytes_. The length of an input containing multi-byte code-points should therefore be measured with `strings.RuneCount`. Inputs will first be converted to strings, and multiple inputs are concatenated. This wraps Go’s [`utf8.RuneCountInString`](https://pkg.go.dev/unicode/utf8/#RuneCountInString) function. _Added in gomplate [v3.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.4.0) _ ### Usage strings.RuneCount input input | strings.RuneCount ### Arguments | name | description | | --- | --- | | `input` | _(required)_ the input(s) to measure | ### Examples $ gomplate -i '{{ range (coll.Slice "\u03a9" "\u0030" "\u1430") }}{{ printf "%s is %d bytes and %d runes\n" . (len .) (strings.RuneCount .) }}{{ end }}' Ω is 2 bytes and 1 runes 0 is 1 bytes and 1 runes ᐰ is 3 bytes and 1 runes `contains` _(deprecated)_ ------------------------- **Deprecation Notice:** Use [`strings.Contains`](#stringscontains) instead **See [`strings.Contains`](#stringscontains) for a pipeline-compatible version** Contains reports whether the second string is contained within the first. Equivalent to [strings.Contains](https://pkg.go.dev/strings#Contains) _Added in gomplate [v1.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.4.0) _ ### Usage contains input substring ### Arguments | name | description | | --- | --- | | `input` | _(required)_ the string to search | | `substring` | _(required)_ the string to search for | ### Examples _`input.tmpl`:_ {{if contains .Env.FOO "f"}}yes{{else}}no{{end}} $ FOO=foo gomplate < input.tmpl yes $ FOO=bar gomplate < input.tmpl no `hasPrefix` _(deprecated)_ -------------------------- **Deprecation Notice:** Use [`strings.HasPrefix`](#stringshasprefix) instead **See [`strings.HasPrefix`](#stringshasprefix) for a pipeline-compatible version** Tests whether the string begins with a certain substring. Equivalent to [strings.HasPrefix](https://pkg.go.dev/strings#HasPrefix) _Added in gomplate [v1.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.4.0) _ ### Usage hasPrefix input prefix ### Arguments | name | description | | --- | --- | | `input` | _(required)_ the string to search | | `prefix` | _(required)_ the prefix to search for | ### Examples _`input.tmpl`:_ {{if hasPrefix .Env.URL "https"}}foo{{else}}bar{{end}} $ URL=http://example.com gomplate < input.tmpl bar $ URL=https://example.com gomplate < input.tmpl foo `hasSuffix` _(deprecated)_ -------------------------- **Deprecation Notice:** Use [`strings.HasSuffix`](#stringshassuffix) instead **See [`strings.HasSuffix`](#stringshassuffix) for a pipeline-compatible version** Tests whether the string ends with a certain substring. Equivalent to [strings.HasSuffix](https://pkg.go.dev/strings#HasSuffix) _Added in gomplate [v1.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.4.0) _ ### Usage hasSuffix input suffix ### Arguments | name | description | | --- | --- | | `input` | _(required)_ the input to search | | `suffix` | _(required)_ the suffix to search for | ### Examples _`input.tmpl`:_ {{.Env.URL}}{{if not (hasSuffix .Env.URL ":80")}}:80{{end}} $ URL=http://example.com gomplate < input.tmpl http://example.com:80 `split` _(deprecated)_ ---------------------- **Deprecation Notice:** Use [`strings.Split`](#stringssplit) instead **See [`strings.Split`](#stringssplit) for a pipeline-compatible version** Creates a slice by splitting a string on a given delimiter. Equivalent to [strings.Split](https://pkg.go.dev/strings#Split) _Added in gomplate [v1.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.4.0) _ ### Usage split input separator ### Arguments | name | description | | --- | --- | | `input` | _(required)_ the input string | | `separator` | _(required)_ the string sequence to split | ### Examples $ gomplate -i '{{range split "Bart,Lisa,Maggie" ","}}Hello, {{.}} {{end}}' Hello, Bart Hello, Lisa Hello, Maggie `splitN` _(deprecated)_ ----------------------- **Deprecation Notice:** Use [`strings.SplitN`](#stringssplitn) instead **See [`strings.SplitN`](#stringssplitn) for a pipeline-compatible version** Creates a slice by splitting a string on a given delimiter. The count determines the number of substrings to return. Equivalent to [strings.SplitN](https://pkg.go.dev/strings#SplitN) _Added in gomplate [v1.7.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.7.0) _ ### Usage splitN input separator count ### Arguments | name | description | | --- | --- | | `input` | _(required)_ the input string | | `separator` | _(required)_ the string sequence to split | | `count` | _(required)_ the maximum number of substrings to return | ### Examples $ gomplate -i '{{ range splitN "foo:bar:baz" ":" 2 }}{{.}} {{end}}' foo bar:baz `trim` _(deprecated)_ --------------------- **Deprecation Notice:** Use [`strings.Trim`](#stringstrim) instead **See [`strings.Trim`](#stringstrim) for a pipeline-compatible version** Trims a string by removing the given characters from the beginning and end of the string. Equivalent to [strings.Trim](https://pkg.go.dev/strings/#Trim) _Added in gomplate [v1.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v1.4.0) _ ### Usage trim input cutset ### Arguments | name | description | | --- | --- | | `input` | _(required)_ the input | | `cutset` | _(required)_ the set of characters to cut | ### Examples _`input.tmpl`:_ Hello, {{trim .Env.FOO " "}}! $ FOO=" world " | gomplate < input.tmpl Hello, world! --- # sockaddr functions - gomplate documentation sockaddr functions ================== This namespace wraps the [`github.com/hashicorp/go-sockaddr`](https://github.com/hashicorp/go-sockaddr) package, which makes it easy to discover information about a system’s network interfaces. These functions are _partly_ documented here for convenience, but the canonical documentation is at [https://godoc.org/github.com/hashicorp/go-sockaddr](https://godoc.org/github.com/hashicorp/go-sockaddr) . Aside from some convenience functions, the general method of working with these functions is through a _pipeline_. There are _source_ functions, which select interfaces ([`IfAddr`](https://godoc.org/github.com/hashicorp/go-sockaddr#IfAddr) ), and there are functions to further filter, refine, and finally to select the specific attributes you’re interested in. To demonstrate how this can be used, here’s an example that lists all of the IPv4 addresses available on the system: _in.tmpl:_ {{ range (sockaddr.GetAllInterfaces | sockaddr.Include "type" "ipv4") -}} {{ . | sockaddr.Attr "address" }} {{end}} $ gomplate -f in.tmpl 127.0.0.1 10.0.0.8 132.79.79.79 `sockaddr.GetAllInterfaces` --------------------------- Iterates over all available network interfaces and finds all available IP addresses on each interface and converts them to `sockaddr.IPAddrs`, and returning the result as an array of `IfAddr`. Should be piped through a further function to refine and extract attributes. _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage sockaddr.GetAllInterfaces `sockaddr.GetDefaultInterfaces` ------------------------------- Returns `IfAddrs` of the addresses attached to the default route. Should be piped through a further function to refine and extract attributes. _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage sockaddr.GetDefaultInterfaces `sockaddr.GetPrivateInterfaces` ------------------------------- Returns an array of `IfAddr`s containing every IP that matches [RFC 6890](http://tools.ietf.org/html/rfc6890) , is attached to the interface with the default route, and is a forwardable IP address. **Note:** [RFC 6890](http://tools.ietf.org/html/rfc6890) is a more exhaustive version of [RFC 1918](http://tools.ietf.org/html/rfc1918) because it spans IPv4 and IPv6, however it does permit the inclusion of likely undesired addresses such as multicast, therefore our definition of a “private” address also excludes non-forwardable IP addresses (as defined by the IETF). Should be piped through a further function to refine and extract attributes. _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage sockaddr.GetPrivateInterfaces `sockaddr.GetPublicInterfaces` ------------------------------ Returns an array of `IfAddr`s that do not match [RFC 6890](http://tools.ietf.org/html/rfc6890) , are attached to the default route, and are forwardable. Should be piped through a further function to refine and extract attributes. _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage sockaddr.GetPublicInterfaces `sockaddr.Sort` --------------- Returns an array of `IfAddr`s sorted based on the given selector. Multiple sort clauses can be passed in as a comma-delimited list without whitespace. ### Selectors The valid selectors are: | selector | sorts by… | | --- | --- | | `address` | the network address | | `default` | whether or not the `IfAddr` has a default route | | `name` | the interface name | | `port` | the port, if included in the `IfAddr` | | `size` | the size of the network mask, smaller mask (larger number of hosts per network) to largest (e.g. a /24 sorts before a /32) | | `type` | the type of the `IfAddr`. Order is Unix, IPv4, then IPv6 | Each of these selectors sort _ascending_, but a _descending_ sort may be chosen by prefixing the selector with a `-` (e.g. `-address`). You may prefix with a `+` to make explicit that the sort is ascending. `IfAddr`s that are not comparable will be at the end of the list and in a non-deterministic order. _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage sockaddr.Sort selector | sockaddr.Sort selector ### Arguments | name | description | | --- | --- | | `selector` | _(required)_ which selector to use (see above for values) | | `` | _(required)_ the array of `IfAddr`s to sort | ### Examples To sort first by interface name, then by address (descending): $ gomplate -i '{{ sockaddr.GetAllInterfaces | sockaddr.Sort "name,-address" }}' `sockaddr.Exclude` ------------------ Returns an array of `IfAddr`s filtered by interfaces that do not match the given selector’s value. ### Selectors The valid selectors are: | selector | excludes by… | | --- | --- | | `address` | the network address | | `flag` | the specified flags (see below) | | `name` | the interface name | | `network` | being part of the given IP network (in net/mask format) | | `port` | the port, if included in the `IfAddr` | | `rfc` | being included in networks defined by the given RFC. See [the source code](https://github.com/hashicorp/go-sockaddr/blob/master/rfc.go#L38)
for a list of valid RFCs | | `size` | the size of the network mask, as number of bits (e.g. `"24"` for a /24) | | `type` | the type of the `IfAddr`. `unix`, `ipv4`, or `ipv6` | #### supported flags These flags are supported by the `flag` selector: `broadcast`, `down`, `forwardable`, `global unicast`, `interface-local multicast`, `link-local multicast`, `link-local unicast`, `loopback`, `multicast`, `point-to-point`, `unspecified`, `up` _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage sockaddr.Exclude selector value | sockaddr.Exclude selector value ### Arguments | name | description | | --- | --- | | `selector` | _(required)_ which selector to use (see above for values) | | `value` | _(required)_ the selector value to exclude | | `` | _(required)_ the array of `IfAddr`s to consider | ### Examples To exclude all IPv6 interfaces: $ gomplate -i '{{ sockaddr.GetAllInterfaces | sockaddr.Exclude "type" "ipv6" }}' `sockaddr.Include` ------------------ Returns an array of `IfAddr`s filtered by interfaces that match the given selector’s value. This is the inverse of `sockaddr.Exclude`. See [`sockaddr.Exclude`](#sockaddrexclude) for details. _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage sockaddr.Include selector value | sockaddr.Include selector value ### Arguments | name | description | | --- | --- | | `selector` | _(required)_ which selector to use (see above for values) | | `value` | _(required)_ the selector value to include | | `` | _(required)_ the array of `IfAddr`s to consider | `sockaddr.Attr` --------------- Returns the named attribute as a string. _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage sockaddr.Attr selector | sockaddr.Attr selector ### Arguments | name | description | | --- | --- | | `selector` | _(required)_ the attribute to return | | `` | _(required)_ the array of `IfAddr`s to inspect | ### Examples $ gomplate -i '{{ range (sockaddr.GetAllInterfaces | sockaddr.Include "type" "ipv4") }}{{ . | sockaddr.Attr "name" }} {{end}}' lo0 en0 `sockaddr.Join` --------------- Selects the given attribute from each `IfAddr` in the source array, and joins the results with the given separator. _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage sockaddr.Join selector separator | sockaddr.Join selector separator ### Arguments | name | description | | --- | --- | | `selector` | _(required)_ the attribute to select | | `separator` | _(required)_ the separator | | `` | _(required)_ the array of `IfAddr`s to join | ### Examples $ gomplate -i '{{ sockaddr.GetAllInterfaces | sockaddr.Join "name" "," }}' lo0,lo0,lo0,en0,en0 `sockaddr.Limit` ---------------- Returns a slice of `IfAddr`s based on the specified limit. _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage sockaddr.Limit limit | sockaddr.Limit limit ### Arguments | name | description | | --- | --- | | `limit` | _(required)_ the maximum number of `IfAddrs` | | `` | _(required)_ the array of `IfAddr`s | ### Examples $ gomplate -i '{{ sockaddr.GetAllInterfaces | sockaddr.Limit 2 | sockaddr.Join "name" "|" }}' lo0|lo0 `sockaddr.Offset` ----------------- Returns a slice of `IfAddr`s based on the specified offset. _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage sockaddr.Offset offset | sockaddr.Offset offset ### Arguments | name | description | | --- | --- | | `offset` | _(required)_ the offset | | `` | _(required)_ the array of `IfAddr`s | ### Examples $ gomplate -i '{{ sockaddr.GetAllInterfaces | sockaddr.Limit 2 | sockaddr.Offset 1 | sockaddr.Attr "address" }}' ::1 `sockaddr.Unique` ----------------- Creates a unique array of `IfAddr`s based on the matching selector. Assumes the input has already been sorted. _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage sockaddr.Unique selector | sockaddr.Unique selector ### Arguments | name | description | | --- | --- | | `selector` | _(required)_ the attribute to select | | `` | _(required)_ the array of `IfAddr`s | ### Examples $ gomplate -i '{{ sockaddr.GetAllInterfaces | sockaddr.Unique "name" | sockaddr.Join "name" ", " }}' lo0, en0 `sockaddr.Math` --------------- Applies a math operation to each `IfAddr` in the input. Any failure will result in zero results. See [the source code](https://github.com/hashicorp/go-sockaddr/blob/master/ifaddrs.go#L725) for details. _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage sockaddr.Math selector operation | sockaddr.Math selector operation ### Arguments | name | description | | --- | --- | | `selector` | _(required)_ the attribute to operate on | | `operation` | _(required)_ the operation | | `` | _(required)_ the array of `IfAddr`s | ### Examples $ gomplate -i '{{ sockaddr.GetAllInterfaces | sockaddr.Math "address" "+5" | sockaddr.Attr "address" }}' 127.0.0.6 `sockaddr.GetPrivateIP` ----------------------- Returns a string with a single IP address that is part of [RFC 6890](http://tools.ietf.org/html/rfc6890) and has a default route. If the system can’t determine its IP address or find an [RFC 6890](http://tools.ietf.org/html/rfc6890) IP address, an empty string will be returned instead. _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage sockaddr.GetPrivateIP ### Examples $ gomplate -i '{{ sockaddr.GetPrivateIP }}' 10.0.0.28 `sockaddr.GetPrivateIPs` ------------------------ Returns a space-separated string with all IP addresses that are part of [RFC 6890](http://tools.ietf.org/html/rfc6890) (regardless of whether or not there is a default route, unlike `GetPublicIP`). If the system can’t find any [RFC 6890](http://tools.ietf.org/html/rfc6890) IP addresses, an empty string will be returned instead. _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage sockaddr.GetPrivateIPs ### Examples $ gomplate -i '{{ sockaddr.GetPrivateIPs }}' 10.0.0.28 192.168.0.1 `sockaddr.GetPublicIP` ---------------------- Returns a string with a single IP address that is NOT part of [RFC 6890](http://tools.ietf.org/html/rfc6890) and has a default route. If the system can’t determine its IP address or find a non-[RFC 6890](http://tools.ietf.org/html/rfc6890) IP address, an empty string will be returned instead. _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage sockaddr.GetPublicIP ### Examples $ gomplate -i '{{ sockaddr.GetPublicIP }}' 8.1.2.3 `sockaddr.GetPublicIPs` ----------------------- Returns a space-separated string with all IP addresses that are NOT part of [RFC 6890](http://tools.ietf.org/html/rfc6890) (regardless of whether or not there is a default route, unlike `GetPublicIP`). If the system can’t find any non-[RFC 6890](http://tools.ietf.org/html/rfc6890) IP addresses, an empty string will be returned instead. _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage sockaddr.GetPublicIPs ### Examples $ gomplate -i '{{ sockaddr.GetPublicIPs }}' 8.1.2.3 8.2.3.4 `sockaddr.GetInterfaceIP` ------------------------- Returns a string with a single IP address sorted by the size of the network (i.e. IP addresses with a smaller netmask, larger network size, are sorted first). _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage sockaddr.GetInterfaceIP name ### Arguments | name | description | | --- | --- | | `name` | _(required)_ the interface name | ### Examples $ gomplate -i '{{ sockaddr.GetInterfaceIP "en0" }}' 10.0.0.28 `sockaddr.GetInterfaceIPs` -------------------------- Returns a string with all IPs, sorted by the size of the network (i.e. IP addresses with a smaller netmask, larger network size, are sorted first), on a named interface. _Added in gomplate [v2.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.4.0) _ ### Usage sockaddr.GetInterfaceIPs name ### Arguments | name | description | | --- | --- | | `name` | _(required)_ the interface name | ### Examples $ gomplate -i '{{ sockaddr.GetInterfaceIPs "en0" }}' 10.0.0.28 fe80::1f9a:5582:4b41:bd18 --- # uuid functions - gomplate documentation uuid functions ============== Functions for generating, parsing, and manipulating UUIDs. A UUID is a 128 bit (16 byte) _Universal Unique IDentifier_ as defined in [RFC 4122](https://en.wikipedia.org/wiki/Universally_unique_identifier) . Only RFC 4112-variant UUIDs can be generated, but all variants (even invalid ones) can be parsed and manipulated. Also, gomplate only supports generating version 1 and 4 UUIDs (with 4 being the most commonly-used variety these days). Versions 2, 3, and 5 are able to be supported: [log an issue](https://github.com/hairyhenderson/gomplate/issues/new) if this is required for your use-case. `uuid.V1` --------- Create a version 1 UUID (based on the current MAC address and the current date/time). Use [`uuid.V4`](#uuidv4) instead in most cases. _Added in gomplate [v3.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.4.0) _ ### Usage uuid.V1 ### Examples $ gomplate -i '{{ uuid.V1 }}' 4d757e54-446d-11e9-a8fa-72000877c7b0 `uuid.V4` --------- Create a version 4 UUID (randomly generated). This function consumes entropy. _Added in gomplate [v3.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.4.0) _ ### Usage uuid.V4 ### Examples $ gomplate -i '{{ uuid.V4 }}' 40b3c2d2-e491-4b19-94cd-461e6fa35a60 `uuid.Nil` ---------- Returns the _nil_ UUID, that is, `00000000-0000-0000-0000-000000000000`, mostly for testing scenarios. _Added in gomplate [v3.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.4.0) _ ### Usage uuid.Nil ### Examples $ gomplate -i '{{ uuid.Nil }}' 00000000-0000-0000-0000-000000000000 `uuid.IsValid` -------------- Checks that the given UUID is in the correct format. It does not validate whether the version or variant are correct. _Added in gomplate [v3.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.4.0) _ ### Usage uuid.IsValid uuid uuid | uuid.IsValid ### Arguments | name | description | | --- | --- | | `uuid` | _(required)_ The uuid to check | ### Examples $ gomplate -i '{{ if uuid.IsValid "totally invalid" }}valid{{ else }}invalid{{ end }}' invalid $ gomplate -i '{{ uuid.IsValid "urn:uuid:12345678-90ab-cdef-fedc-ba9876543210" }}' true `uuid.Parse` ------------ Parse a UUID for further manipulation or inspection. This function returns a `UUID` struct, as defined in the [github.com/google/uuid](https://godoc.org/github.com/google/uuid#UUID) package. See the docs for examples of functions or fields you can call. Both the standard UUID forms of `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` and `urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` are decoded as well as the Microsoft encoding `{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}` and the raw hex encoding (`xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`). _Added in gomplate [v3.4.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.4.0) _ ### Usage uuid.Parse uuid uuid | uuid.Parse ### Arguments | name | description | | --- | --- | | `uuid` | _(required)_ The uuid to parse | ### Examples $ gomplate -i '{{ $u := uuid.Parse uuid.V4 }}{{ $u.Version }}, {{ $u.Variant}}' VERSION_4, RFC4122 $ gomplate -i '{{ (uuid.Parse "000001f5-4470-21e9-9b00-72000877c7b0").Domain }}' Person --- # gcp functions - gomplate documentation gcp functions ============= The functions in the `gcp` namespace interface with various Google Cloud Platform APIs to make it possible for a template to render differently based on the GCP environment and metadata. ### Configuring GCP A number of environment variables can be used to control how gomplate communicates with GCP APIs. | Environment Variable | Description | | --- | --- | | `GCP_META_ENDPOINT` | _(Default `http://metadata.google.internal`)_ Sets the base address of the instance metadata service. | | `GCP_TIMEOUT` | _(Default `500`)_ Adjusts timeout for API requests, in milliseconds. | `gcp.Meta` ---------- Queries GCP [Instance Metadata](https://cloud.google.com/compute/docs/storing-retrieving-metadata) for information. For times when running outside GCP, or when the metadata API can’t be reached, a `default` value can be provided. _Added in gomplate [v3.8.0](https://github.com/hairyhenderson/gomplate/releases/tag/v3.8.0) _ ### Usage gcp.Meta key [default] ### Arguments | name | description | | --- | --- | | `key` | _(required)_ the metadata key to query | | `default` | _(optional)_ the default value | ### Examples $ echo '{{gcp.Meta "id"}}' | gomplate 1334999446930701104 $ echo '{{gcp.Meta "network-interfaces/0/ip"}}' | gomplate 10.128.0.23 --- # time functions - gomplate documentation time functions ============== This namespace wraps Go’s [`time` package](https://pkg.go.dev/time/) , and a few of the functions return a `time.Time` value. All of the [`time.Time` functions](https://pkg.go.dev/time/#Time) can then be used to convert, adjust, or format the time in your template. ### Reference time An important difference between this and many other time/date utilities is how parsing and formatting is accomplished. Instead of relying solely on pre-defined formats, or having a complex system of variables, formatting is accomplished by declaring an example of the layout you wish to display. This uses a _reference time_, which is: Mon Jan 2 15:04:05 -0700 MST 2006 ### Constants #### format layouts Some pre-defined layouts have been provided for convenience: | layout name | value | | --- | --- | | `time.ANSIC` | `"Mon Jan _2 15:04:05 2006"` | | `time.UnixDate` | `"Mon Jan _2 15:04:05 MST 2006"` | | `time.RubyDate` | `"Mon Jan 02 15:04:05 -0700 2006"` | | `time.RFC822` | `"02 Jan 06 15:04 MST"` | | `time.RFC822Z` | `"02 Jan 06 15:04 -0700"` // RFC822 with numeric zone | | `time.RFC850` | `"Monday, 02-Jan-06 15:04:05 MST"` | | `time.RFC1123` | `"Mon, 02 Jan 2006 15:04:05 MST"` | | `time.RFC1123Z` | `"Mon, 02 Jan 2006 15:04:05 -0700"` // RFC1123 with numeric zone | | `time.RFC3339` | `"2006-01-02T15:04:05Z07:00"` | | `time.RFC3339Nano` | `"2006-01-02T15:04:05.999999999Z07:00"` | | `time.Kitchen` | `"3:04PM"` | | `time.Stamp` | `"Jan _2 15:04:05"` | | `time.StampMilli` | `"Jan _2 15:04:05.000"` | | `time.StampMicro` | `"Jan _2 15:04:05.000000"` | | `time.StampNano` | `"Jan _2 15:04:05.000000000"` | See below for examples of how these layouts can be used. #### durations Some operations (such as [`Time.Add`](https://pkg.go.dev/time/#Time.Add) and [`Time.Round`](https://pkg.go.dev/time/#Time.Round) ) require a [`Duration`](https://pkg.go.dev/time/#Duration) value. These can be created conveniently with the following functions: * `time.Nanosecond` * `time.Microsecond` * `time.Millisecond` * `time.Second` * `time.Minute` * `time.Hour` For example: $ gomplate -i '{{ (time.Now).Format time.Kitchen }} {{ ((time.Now).Add (time.Hour 2)).Format time.Kitchen }}' 9:05AM 11:05AM For other durations, such as `2h10m`, [`time.ParseDuration`](#timeparseduration) can be used. `time.Now` ---------- Returns the current local time, as a `time.Time`. This wraps [`time.Now`](https://pkg.go.dev/time/#Now) . Usually, further functions are called using the value returned by `Now`. _Added in gomplate [v2.1.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.1.0) _ ### Usage time.Now ### Examples Usage with [`UTC`](https://pkg.go.dev/time/#Time.UTC) and [`Format`](https://pkg.go.dev/time/#Time.Format) : $ gomplate -i '{{ (time.Now).UTC.Format "Day 2 of month 1 in year 2006 (timezone MST)" }}' Day 14 of month 10 in year 2017 (timezone UTC) Usage with [`AddDate`](https://pkg.go.dev/time/#Time.AddDate) : $ date Sat Oct 14 09:57:02 EDT 2017 $ gomplate -i '{{ ((time.Now).AddDate 0 1 0).Format "Mon Jan 2 15:04:05 MST 2006" }}' Tue Nov 14 09:57:02 EST 2017 _(notice how the TZ adjusted for daylight savings!)_ Usage with [`IsDST`](https://pkg.go.dev/time/#Time.IsDST) : $ gomplate -i '{{ $t := time.Now }}At the tone, the time will be {{ ($t.Round (time.Minute 1)).Add (time.Minute 1) }}. It is{{ if not $t.IsDST }} not{{ end }} daylight savings time. ... ... BEEP' At the tone, the time will be 2022-02-10 09:01:00 -0500 EST. It is not daylight savings time. ... ... BEEP `time.Parse` ------------ Parses a timestamp defined by the given layout. This wraps [`time.Parse`](https://pkg.go.dev/time/#Parse) . A number of pre-defined layouts are provided as constants, defined [here](https://pkg.go.dev/time/#pkg-constants) . Just like [`time.Now`](#timenow) , this is usually used in conjunction with other functions. _Note: In the absence of a time zone indicator, `time.Parse` returns a time in UTC._ _Added in gomplate [v2.1.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.1.0) _ ### Usage time.Parse layout timestamp timestamp | time.Parse layout ### Arguments | name | description | | --- | --- | | `layout` | _(required)_ The layout string to parse with | | `timestamp` | _(required)_ The timestamp to parse | ### Examples Usage with [`Format`](https://pkg.go.dev/time/#Time.Format) : $ gomplate -i '{{ (time.Parse "2006-01-02" "1993-10-23").Format "Monday January 2, 2006 MST" }}' Saturday October 23, 1993 UTC `time.ParseDuration` -------------------- Parses a duration string. This wraps [`time.ParseDuration`](https://pkg.go.dev/time/#ParseDuration) . A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, such as `300ms`, `-1.5h` or `2h45m`. Valid time units are `ns`, `us` (or `µs`), `ms`, `s`, `m`, `h`. _Added in gomplate [v2.1.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.1.0) _ ### Usage time.ParseDuration duration duration | time.ParseDuration ### Arguments | name | description | | --- | --- | | `duration` | _(required)_ The duration string to parse | ### Examples $ gomplate -i '{{ (time.Now).Format time.Kitchen }} {{ ((time.Now).Add (time.ParseDuration "2h30m")).Format time.Kitchen }}' 12:43AM 3:13AM `time.ParseLocal` ----------------- Same as [`time.Parse`](#timeparse) , except that in the absence of a time zone indicator, the timestamp will be parsed in the local timezone. _Added in gomplate [v2.2.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.2.0) _ ### Usage time.ParseLocal layout timestamp timestamp | time.ParseLocal layout ### Arguments | name | description | | --- | --- | | `layout` | _(required)_ The layout string to parse with | | `timestamp` | _(required)_ The timestamp to parse | ### Examples Usage with [`Format`](https://pkg.go.dev/time/#Time.Format) : $ bin/gomplate -i '{{ (time.ParseLocal time.Kitchen "6:00AM").Format "15:04 MST" }}' 06:00 EST `time.ParseInLocation` ---------------------- Same as [`time.Parse`](#timeparse) , except that the time is parsed in the given location’s time zone. This wraps [`time.ParseInLocation`](https://pkg.go.dev/time/#ParseInLocation) . _Added in gomplate [v2.2.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.2.0) _ ### Usage time.ParseInLocation layout location timestamp timestamp | time.ParseInLocation layout location ### Arguments | name | description | | --- | --- | | `layout` | _(required)_ The layout string to parse with | | `location` | _(required)_ The location to parse in | | `timestamp` | _(required)_ The timestamp to parse | ### Examples Usage with [`Format`](https://pkg.go.dev/time/#Time.Format) : $ gomplate -i '{{ (time.ParseInLocation time.Kitchen "Africa/Luanda" "6:00AM").Format "15:04 MST" }}' 06:00 LMT `time.Since` ------------ Returns the time elapsed since a given time. This wraps [`time.Since`](https://pkg.go.dev/time/#Since) . It is shorthand for `time.Now.Sub t`. _Added in gomplate [v2.5.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.5.0) _ ### Usage time.Since t t | time.Since ### Arguments | name | description | | --- | --- | | `t` | _(required)_ the `Time` to calculate since | ### Examples $ gomplate -i '{{ $t := time.Parse time.RFC3339 "1970-01-01T00:00:00Z" }}time since the epoch:{{ time.Since $t }}' time since the epoch:423365h0m24.353828924s `time.Unix` ----------- Returns the local `Time` corresponding to the given Unix time, in seconds since January 1, 1970 UTC. Note that fractional seconds can be used to denote milliseconds, but must be specified as a string, not a floating point number. _Added in gomplate [v2.1.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.1.0) _ ### Usage time.Unix time time | time.Unix ### Arguments | name | description | | --- | --- | | `time` | _(required)_ the time to parse | ### Examples _with whole seconds:_ $ gomplate -i '{{ (time.Unix 42).UTC.Format time.Stamp}}' Jan 1, 00:00:42 _with fractional seconds:_ $ gomplate -i '{{ (time.Unix "123456.789").UTC.Format time.StampMilli}}' Jan 2 10:17:36.789 `time.Until` ------------ Returns the duration until a given time. This wraps [`time.Until`](https://pkg.go.dev/time/#Until) . It is shorthand for `$t.Sub time.Now`. _Added in gomplate [v2.5.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.5.0) _ ### Usage time.Until t t | time.Until ### Arguments | name | description | | --- | --- | | `t` | _(required)_ the `Time` to calculate until | ### Examples $ gomplate -i '{{ $t := time.Parse time.RFC3339 "2020-01-01T00:00:00Z" }}only {{ time.Until $t }} to go...' only 14922h56m46.578625891s to go... Or, less precise: $ bin/gomplate -i '{{ $t := time.Parse time.RFC3339 "2020-01-01T00:00:00Z" }}only {{ (time.Until $t).Round (time.Hour 1) }} to go...' only 14923h0m0s to go... `time.ZoneName` --------------- Return the local system’s time zone’s name. _Added in gomplate [v2.1.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.1.0) _ ### Usage time.ZoneName ### Examples $ gomplate -i '{{time.ZoneName}}' EDT `time.ZoneOffset` ----------------- Return the local system’s time zone offset, in seconds east of UTC. _Added in gomplate [v2.2.0](https://github.com/hairyhenderson/gomplate/releases/tag/v2.2.0) _ ### Usage time.ZoneOffset ### Examples $ gomplate -i '{{time.ZoneOffset}}' -14400 ---