• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..20-Dec-2019-

child/H20-Dec-2019-429278

config/H20-Dec-2019-3,3382,259

dependency/H20-Dec-2019-3,1132,273

logging/H20-Dec-2019-14398

manager/H20-Dec-2019-1,8511,224

renderer/H20-Dec-2019-216140

signals/H20-Dec-2019-143107

template/H20-Dec-2019-1,8301,330

version/H20-Dec-2019-138

watch/H20-Dec-2019-563354

CHANGELOG.mdH A D20-Dec-201940 KiB1,057753

LICENSEH A D20-Dec-201915.6 KiB354256

MakefileH A D20-Dec-20197.2 KiB254193

README.mdH A D20-Dec-201971 KiB2,4681,832

cli.goH A D20-Dec-201922 KiB805591

flags.goH A D20-Dec-20191.5 KiB5739

go.modH A D20-Dec-20191.7 KiB4439

go.sumH A D20-Dec-201921.5 KiB228227

main.goH A D20-Dec-2019156 96

README.md

1# Consul Template
2
3[![CircleCI](https://circleci.com/gh/hashicorp/consul-template.svg?style=svg)](https://circleci.com/gh/hashicorp/consul-template)
4[![Go Documentation](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](https://godoc.org/github.com/hashicorp/consul-template)
5
6This project provides a convenient way to populate values from [Consul][consul]
7into the file system using the `consul-template` daemon.
8
9The daemon `consul-template` queries a [Consul][consul] or [Vault][vault]
10cluster and updates any number of specified templates on the file system. As an
11added bonus, it can optionally run arbitrary commands when the update process
12completes. Please see the [examples folder][examples] for some scenarios where
13this functionality might prove useful.
14
15---
16
17**The documentation in this README corresponds to the master branch of Consul Template. It may contain unreleased features or different APIs than the most recently released version.**
18
19**Please see the [Git tag](https://github.com/hashicorp/consul-template/releases) that corresponds to your version of Consul Template for the proper documentation.**
20
21---
22
23## Table of Contents
24
25- [Community Support](#community-support)
26- [Installation](#installation)
27- [Quick Example](#quick-example)
28- [Usage](#usage)
29  - [Command Line Flags](#command-line-flags)
30  - [Configuration File Format](#configuration-file-format)
31  - [Templating Language](#templating-language)
32    - [API Functions](#api-functions)
33      - [datacenters](#datacenters)
34      - [file](#file)
35      - [key](#key)
36      - [keyExists](#keyexists)
37      - [keyOrDefault](#keyordefault)
38      - [ls](#ls)
39      - [safeLs](#safels)
40      - [node](#node)
41      - [nodes](#nodes)
42      - [secret](#secret)
43      - [secrets](#secrets)
44      - [service](#service)
45      - [services](#services)
46      - [tree](#tree)
47      - [safeTree](#safetree)
48    - [Scratch](#scratch)
49      - [scratch.Key](#scratchkey)
50      - [scratch.Get](#scratchget)
51      - [scratch.Set](#scratchset)
52      - [scratch.SetX](#scratchsetx)
53      - [scratch.MapSet](#scratchmapset)
54      - [scratch.MapSetX](#scratchmapsetx)
55      - [scratch.MapValues](#scratchmapvalues)
56    - [Helper Functions](#helper-functions)
57      - [base64Decode](#base64decode)
58      - [base64Encode](#base64encode)
59      - [base64URLDecode](#base64urldecode)
60      - [base64URLEncode](#base64urlencode)
61      - [byKey](#bykey)
62      - [byTag](#bytag)
63      - [byMeta](#bymeta)
64      - [contains](#contains)
65      - [containsAll](#containsall)
66      - [containsAny](#containsany)
67      - [containsNone](#containsnone)
68      - [containsNotAll](#containsnotall)
69      - [env](#env)
70      - [executeTemplate](#executetemplate)
71      - [explode](#explode)
72      - [explodeMap](#explodemap)
73      - [indent](#indent)
74      - [in](#in)
75      - [loop](#loop)
76      - [join](#join)
77      - [trimSpace](#trimspace)
78      - [parseBool](#parsebool)
79      - [parseFloat](#parsefloat)
80      - [parseInt](#parseint)
81      - [parseJSON](#parsejson)
82      - [parseUint](#parseuint)
83      - [plugin](#plugin)
84      - [regexMatch](#regexmatch)
85      - [regexReplaceAll](#regexreplaceall)
86      - [replaceAll](#replaceall)
87      - [split](#split)
88      - [timestamp](#timestamp)
89      - [toJSON](#tojson)
90      - [toJSONPretty](#tojsonpretty)
91      - [toLower](#tolower)
92      - [toTitle](#totitle)
93      - [toTOML](#totoml)
94      - [toUpper](#toupper)
95      - [toYAML](#toyaml)
96      - [sockaddr](#sockaddr)
97    - [Math Functions](#math-functions)
98      - [add](#add)
99      - [subtract](#subtract)
100      - [multiply](#multiply)
101      - [divide](#divide)
102      - [modulo](#modulo)
103- [Plugins](#plugins)
104  - [Authoring Plugins](#authoring-plugins)
105    - [Important Notes](#important-notes)
106- [Caveats](#caveats)
107  - [Dots in Service Names](#dots-in-service-names)
108  - [Once Mode](#once-mode)
109  - [Exec Mode](#exec-mode)
110  - [De-Duplication Mode](#de-duplication-mode)
111  - [Termination on Error](#termination-on-error)
112  - [Command Environment](#command-environment)
113  - [Multi-phase Execution](#multi-phase-execution)
114- [Running and Process Lifecycle](#running-and-process-lifecycle)
115- [Debugging](#debugging)
116- [FAQ](#faq)
117- [Contributing](#contributing)
118
119
120## Community Support
121
122If you have questions about how consul-template works, its capabilities or
123anything other than a bug or feature request (use github's issue tracker for
124those), please see our community support resources.
125
126Community portal: https://discuss.hashicorp.com/c/consul
127
128Other resources: https://www.consul.io/community.html
129
130Additionally, for issues and pull requests, we'll be using the :+1: reactions
131as a rough voting system to help gauge community priorities. So please add :+1:
132to any issue or pull request you'd like to see worked on. Thanks.
133
134
135## Installation
136
1371. Download a pre-compiled, released version from the [Consul Template releases page][releases].
138
1391. Extract the binary using `unzip` or `tar`.
140
1411. Move the binary into `$PATH`.
142
143To compile from source, please see the instructions in the
144[contributing section](#contributing).
145
146## Quick Example
147
148This short example assumes Consul is installed locally.
149
1501. Start a Consul cluster in dev mode:
151
152    ```shell
153    $ consul agent -dev
154    ```
155
1561. Author a template `in.tpl` to query the kv store:
157
158    ```liquid
159    {{ key "foo" }}
160    ```
161
1621. Start Consul Template:
163
164    ```shell
165    $ consul-template -template "in.tpl:out.txt" -once
166    ```
167
1681. Write data to the key in Consul:
169
170    ```shell
171    $ consul kv put foo bar
172    ```
173
1741. Observe Consul Template has written the file `out.txt`:
175
176    ```shell
177    $ cat out.txt
178    bar
179    ```
180
181For more examples and use cases, please see the [examples folder][examples] in
182this repository.
183
184## Usage
185
186For the full list of options:
187
188```shell
189$ consul-template -h
190```
191
192### Command Line Flags
193
194The CLI interface supports all options in the configuration file and vice-versa. Here are a few examples of common integrations on the command line.
195
196Render the template on disk at `/tmp/template.ctmpl` to `/tmp/result`:
197
198```shell
199$ consul-template \
200    -template "/tmp/template.ctmpl:/tmp/result"
201```
202
203Render multiple templates in the same process. The optional third argument to
204the template is a command that will execute each time the template changes.
205
206```shell
207$ consul-template \
208    -template "/tmp/nginx.ctmpl:/var/nginx/nginx.conf:nginx -s reload" \
209    -template "/tmp/redis.ctmpl:/var/redis/redis.conf:service redis restart" \
210    -template "/tmp/haproxy.ctmpl:/var/haproxy/haproxy.conf"
211```
212
213Render a template using a custom Consul and Vault address:
214
215```shell
216$ consul-template \
217    -consul-addr "10.4.4.6:8500" \
218    -vault-addr "https://10.5.32.5:8200"
219```
220
221Render all templates and then spawn and monitor a child process as a supervisor:
222
223```shell
224$ consul-template \
225  -template "/tmp/in.ctmpl:/tmp/result" \
226  -exec "/sbin/my-server"
227```
228
229For more information on supervising, please see the
230[Consul Template Exec Mode documentation](#exec-mode).
231
232### Configuration File Format
233
234Configuration files are written in the [HashiCorp Configuration Language][hcl].
235By proxy, this means the configuration is also JSON compatible.
236
237```hcl
238# This denotes the start of the configuration section for Consul. All values
239# contained in this section pertain to Consul.
240consul {
241  # This block specifies the basic authentication information to pass with the
242  # request. For more information on authentication, please see the Consul
243  # documentation.
244  auth {
245    enabled  = true
246    username = "test"
247    password = "test"
248  }
249
250  # This is the address of the Consul agent. By default, this is
251  # 127.0.0.1:8500, which is the default bind and port for a local Consul
252  # agent. It is not recommended that you communicate directly with a Consul
253  # server, and instead communicate with the local Consul agent. There are many
254  # reasons for this, most importantly the Consul agent is able to multiplex
255  # connections to the Consul server and reduce the number of open HTTP
256  # connections. Additionally, it provides a "well-known" IP address for which
257  # clients can connect.
258  address = "127.0.0.1:8500"
259
260  # This is the ACL token to use when connecting to Consul. If you did not
261  # enable ACLs on your Consul cluster, you do not need to set this option.
262  #
263  # This option is also available via the environment variable CONSUL_TOKEN.
264  token = "abcd1234"
265
266  # This controls the retry behavior when an error is returned from Consul.
267  # Consul Template is highly fault tolerant, meaning it does not exit in the
268  # face of failure. Instead, it uses exponential back-off and retry functions
269  # to wait for the cluster to become available, as is customary in distributed
270  # systems.
271  retry {
272    # This enabled retries. Retries are enabled by default, so this is
273    # redundant.
274    enabled = true
275
276    # This specifies the number of attempts to make before giving up. Each
277    # attempt adds the exponential backoff sleep time. Setting this to
278    # zero will implement an unlimited number of retries.
279    attempts = 12
280
281    # This is the base amount of time to sleep between retry attempts. Each
282    # retry sleeps for an exponent of 2 longer than this base. For 5 retries,
283    # the sleep times would be: 250ms, 500ms, 1s, 2s, then 4s.
284    backoff = "250ms"
285
286    # This is the maximum amount of time to sleep between retry attempts.
287    # When max_backoff is set to zero, there is no upper limit to the
288    # exponential sleep between retry attempts.
289    # If max_backoff is set to 10s and backoff is set to 1s, sleep times
290    # would be: 1s, 2s, 4s, 8s, 10s, 10s, ...
291    max_backoff = "1m"
292  }
293
294  # This block configures the SSL options for connecting to the Consul server.
295  ssl {
296    # This enables SSL. Specifying any option for SSL will also enable it.
297    enabled = true
298
299    # This enables SSL peer verification. The default value is "true", which
300    # will check the global CA chain to make sure the given certificates are
301    # valid. If you are using a self-signed certificate that you have not added
302    # to the CA chain, you may want to disable SSL verification. However, please
303    # understand this is a potential security vulnerability.
304    verify = false
305
306    # This is the path to the certificate to use to authenticate. If just a
307    # certificate is provided, it is assumed to contain both the certificate and
308    # the key to convert to an X509 certificate. If both the certificate and
309    # key are specified, Consul Template will automatically combine them into an
310    # X509 certificate for you.
311    cert = "/path/to/client/cert"
312    key  = "/path/to/client/key"
313
314    # This is the path to the certificate authority to use as a CA. This is
315    # useful for self-signed certificates or for organizations using their own
316    # internal certificate authority.
317    ca_cert = "/path/to/ca"
318
319    # This is the path to a directory of PEM-encoded CA cert files. If both
320    # `ca_cert` and `ca_path` is specified, `ca_cert` is preferred.
321    ca_path = "path/to/certs/"
322
323    # This sets the SNI server name to use for validation.
324    server_name = "my-server.com"
325  }
326}
327
328# This is the signal to listen for to trigger a reload event. The default
329# value is shown below. Setting this value to the empty string will cause CT
330# to not listen for any reload signals.
331reload_signal = "SIGHUP"
332
333# This is the signal to listen for to trigger a graceful stop. The default
334# value is shown below. Setting this value to the empty string will cause CT
335# to not listen for any graceful stop signals.
336kill_signal = "SIGINT"
337
338# This is the maximum interval to allow "stale" data. By default, only the
339# Consul leader will respond to queries; any requests to a follower will
340# forward to the leader. In large clusters with many requests, this is not as
341# scalable, so this option allows any follower to respond to a query, so long
342# as the last-replicated data is within these bounds. Higher values result in
343# less cluster load, but are more likely to have outdated data.
344max_stale = "10m"
345
346# This is the log level. If you find a bug in Consul Template, please enable
347# debug logs so we can help identify the issue. This is also available as a
348# command line flag.
349log_level = "warn"
350
351# This is the path to store a PID file which will contain the process ID of the
352# Consul Template process. This is useful if you plan to send custom signals
353# to the process.
354pid_file = "/path/to/pid"
355
356# This is the quiescence timers; it defines the minimum and maximum amount of
357# time to wait for the cluster to reach a consistent state before rendering a
358# template. This is useful to enable in systems that have a lot of flapping,
359# because it will reduce the the number of times a template is rendered.
360wait {
361  min = "5s"
362  max = "10s"
363}
364
365# This denotes the start of the configuration section for Vault. All values
366# contained in this section pertain to Vault.
367vault {
368  # This is the address of the Vault leader. The protocol (http(s)) portion
369  # of the address is required.
370  address = "https://vault.service.consul:8200"
371
372  # This is a Vault Enterprise namespace to use for reading/writing secrets.
373  #
374  # This value can also be specified via the environment variable VAULT_NAMESPACE.
375  namespace = "foo"
376
377  # This is the token to use when communicating with the Vault server.
378  # Like other tools that integrate with Vault, Consul Template makes the
379  # assumption that you provide it with a Vault token; it does not have the
380  # incorporated logic to generate tokens via Vault's auth methods.
381  #
382  # This value can also be specified via the environment variable VAULT_TOKEN.
383  # When using a token from Vault Agent, the vault_agent_token_file setting
384  # should be used instead, as that will take precedence over this field.
385  token = "abcd1234"
386
387  # This tells Consul Template to load the Vault token from the contents of a file.
388  # If this field is specified:
389  # - by default Consul Template will not try to renew the Vault token, if you want it
390  # to renew you will nee dto specify renew_token = true as below.
391  # - Consul Template will periodically stat the file and update the token if it has
392  # changed.
393  # vault_agent_token_file = "/tmp/vault/agent/token"
394
395  # This tells Consul Template that the provided token is actually a wrapped
396  # token that should be unwrapped using Vault's cubbyhole response wrapping
397  # before being used. Please see Vault's cubbyhole response wrapping
398  # documentation for more information.
399  unwrap_token = true
400
401  # This option tells Consul Template to automatically renew the Vault token
402  # given. If you are unfamiliar with Vault's architecture, Vault requires
403  # tokens be renewed at some regular interval or they will be revoked. Consul
404  # Template will automatically renew the token at half the lease duration of
405  # the token. The default value is true, but this option can be disabled if
406  # you want to renew the Vault token using an out-of-band process.
407  #
408  # Note that secrets specified in a template (using {{secret}} for example)
409  # are always renewed, even if this option is set to false. This option only
410  # applies to the top-level Vault token itself.
411  renew_token = true
412
413  # This section details the retry options for connecting to Vault. Please see
414  # the retry options in the Consul section for more information (they are the
415  # same).
416  retry {
417    # ...
418  }
419
420  # This section details the SSL options for connecting to the Vault server.
421  # Please see the SSL options in the Consul section for more information (they
422  # are the same).
423  ssl {
424    # ...
425  }
426}
427
428# This block defines the configuration for connecting to a syslog server for
429# logging.
430syslog {
431  # This enables syslog logging. Specifying any other option also enables
432  # syslog logging.
433  enabled = true
434
435  # This is the name of the syslog facility to log to.
436  facility = "LOCAL5"
437}
438
439# This block defines the configuration for de-duplication mode. Please see the
440# de-duplication mode documentation later in the README for more information
441# on how de-duplication mode operates.
442deduplicate {
443  # This enables de-duplication mode. Specifying any other options also enables
444  # de-duplication mode.
445  enabled = true
446
447  # This is the prefix to the path in Consul's KV store where de-duplication
448  # templates will be pre-rendered and stored.
449  prefix = "consul-template/dedup/"
450}
451
452# This block defines the configuration for exec mode. Please see the exec mode
453# documentation at the bottom of this README for more information on how exec
454# mode operates and the caveats of this mode.
455exec {
456  # This is the command to exec as a child process. There can be only one
457  # command per Consul Template process.
458  command = "/usr/bin/app"
459
460  # This is a random splay to wait before killing the command. The default
461  # value is 0 (no wait), but large clusters should consider setting a splay
462  # value to prevent all child processes from reloading at the same time when
463  # data changes occur. When this value is set to non-zero, Consul Template
464  # will wait a random period of time up to the splay value before reloading
465  # or killing the child process. This can be used to prevent the thundering
466  # herd problem on applications that do not gracefully reload.
467  splay = "5s"
468
469  env {
470    # This specifies if the child process should not inherit the parent
471    # process's environment. By default, the child will have full access to the
472    # environment variables of the parent. Setting this to true will send only
473    # the values specified in `custom_env` to the child process.
474    pristine = false
475
476    # This specifies additional custom environment variables in the form shown
477    # below to inject into the child's runtime environment. If a custom
478    # environment variable shares its name with a system environment variable,
479    # the custom environment variable takes precedence. Even if pristine,
480    # whitelist, or blacklist is specified, all values in this option
481    # are given to the child process.
482    custom = ["PATH=$PATH:/etc/myapp/bin"]
483
484    # This specifies a list of environment variables to exclusively include in
485    # the list of environment variables exposed to the child process. If
486    # specified, only those environment variables matching the given patterns
487    # are exposed to the child process. These strings are matched using Go's
488    # glob function, so wildcards are permitted.
489    whitelist = ["CONSUL_*"]
490
491    # This specifies a list of environment variables to exclusively prohibit in
492    # the list of environment variables exposed to the child process. If
493    # specified, any environment variables matching the given patterns will not
494    # be exposed to the child process, even if they are whitelisted. The values
495    # in this option take precedence over the values in the whitelist.
496    # These strings are matched using Go's glob function, so wildcards are
497    # permitted.
498    blacklist = ["VAULT_*"]
499  }
500
501  # This defines the signal that will be sent to the child process when a
502  # change occurs in a watched template. The signal will only be sent after the
503  # process is started, and the process will only be started after all
504  # dependent templates have been rendered at least once. The default value is
505  # nil, which tells Consul Template to stop the child process and spawn a new
506  # one instead of sending it a signal. This is useful for legacy applications
507  # or applications that cannot properly reload their configuration without a
508  # full reload.
509  reload_signal = ""
510
511  # This defines the signal sent to the child process when Consul Template is
512  # gracefully shutting down. The application should begin a graceful cleanup.
513  # If the application does not terminate before the `kill_timeout`, it will
514  # be terminated (effectively "kill -9"). The default value is "SIGTERM".
515  kill_signal = "SIGINT"
516
517  # This defines the amount of time to wait for the child process to gracefully
518  # terminate when Consul Template exits. After this specified time, the child
519  # process will be force-killed (effectively "kill -9"). The default value is
520  # "30s".
521  kill_timeout = "2s"
522}
523
524# This block defines the configuration for a template. Unlike other blocks,
525# this block may be specified multiple times to configure multiple templates.
526# It is also possible to configure templates via the CLI directly.
527template {
528  # This is the source file on disk to use as the input template. This is often
529  # called the "Consul Template template". This option is required if not using
530  # the `contents` option.
531  source = "/path/on/disk/to/template.ctmpl"
532
533  # This is the destination path on disk where the source template will render.
534  # If the parent directories do not exist, Consul Template will attempt to
535  # create them, unless create_dest_dirs is false.
536  destination = "/path/on/disk/where/template/will/render.txt"
537
538  # This options tells Consul Template to create the parent directories of the
539  # destination path if they do not exist. The default value is true.
540  create_dest_dirs = true
541
542  # This option allows embedding the contents of a template in the configuration
543  # file rather then supplying the `source` path to the template file. This is
544  # useful for short templates. This option is mutually exclusive with the
545  # `source` option.
546  contents = "{{ keyOrDefault \"service/redis/maxconns@east-aws\" \"5\" }}"
547
548  # This is the optional command to run when the template is rendered. The
549  # command will only run if the resulting template changes. The command must
550  # return within 30s (configurable), and it must have a successful exit code.
551  # Consul Template is not a replacement for a process monitor or init system.
552  command = "restart service foo"
553
554  # This is the maximum amount of time to wait for the optional command to
555  # return. Default is 30s.
556  command_timeout = "60s"
557
558  # Exit with an error when accessing a struct or map field/key that does not
559  # exist. The default behavior will print "<no value>" when accessing a field
560  # that does not exist. It is highly recommended you set this to "true" when
561  # retrieving secrets from Vault.
562  error_on_missing_key = false
563
564  # This is the permission to render the file. If this option is left
565  # unspecified, Consul Template will attempt to match the permissions of the
566  # file that already exists at the destination path. If no file exists at that
567  # path, the permissions are 0644.
568  perms = 0600
569
570  # This option backs up the previously rendered template at the destination
571  # path before writing a new one. It keeps exactly one backup. This option is
572  # useful for preventing accidental changes to the data without having a
573  # rollback strategy.
574  backup = true
575
576  # These are the delimiters to use in the template. The default is "{{" and
577  # "}}", but for some templates, it may be easier to use a different delimiter
578  # that does not conflict with the output file itself.
579  left_delimiter  = "{{"
580  right_delimiter = "}}"
581
582  # These are functions that are not permitted in the template. If a template
583  # includes one of these functions, it will exit with an error.
584  function_blacklist = []
585
586  # If a sandbox path is provided, any path provided to the `file` function is
587  # checked that it falls within the sandbox path. Relative paths that try to
588  # traverse outside the sandbox path will exit with an error.
589  sandbox_path = ""
590
591  # This is the `minimum(:maximum)` to wait before rendering a new template to
592  # disk and triggering a command, separated by a colon (`:`). If the optional
593  # maximum value is omitted, it is assumed to be 4x the required minimum value.
594  # This is a numeric time with a unit suffix ("5s"). There is no default value.
595  # The wait value for a template takes precedence over any globally-configured
596  # wait.
597  wait {
598    min = "2s"
599    max = "10s"
600  }
601}
602
603```
604
605Note that not all fields are required. If you are not retrieving secrets from
606Vault, you do not need to specify a Vault configuration section. Similarly, if
607you are not logging to syslog, you do not need to specify a syslog
608configuration.
609
610For additional security, tokens may also be read from the environment using the
611`CONSUL_TOKEN` or `VAULT_TOKEN` environment variables respectively. It is highly
612recommended that you do not put your tokens in plain-text in a configuration
613file.
614
615Instruct Consul Template to use a configuration file with the `-config` flag:
616
617```shell
618$ consul-template -config "/my/config.hcl"
619```
620
621This argument may be specified multiple times to load multiple configuration
622files. The right-most configuration takes the highest precedence. If the path to
623a directory is provided (as opposed to the path to a file), all of the files in
624the given directory will be merged in
625[lexical order](http://golang.org/pkg/path/filepath/#Walk), recursively. Please
626note that symbolic links are _not_ followed.
627
628**Commands specified on the CLI take precedence over a config file!**
629
630### Templating Language
631
632Consul Template parses files authored in the [Go Template][text-template]
633format. If you are not familiar with the syntax, please read Go's documentation
634and examples. In addition to the Go-provided template functions, Consul Template
635provides the following functions:
636
637#### API Functions
638
639API functions interact with remote API calls, communicating with external
640services like [Consul][consul] and [Vault][vault].
641
642##### `datacenters`
643
644Query [Consul][consul] for all datacenters in its catalog.
645
646```liquid
647{{ datacenters }}
648```
649
650For example:
651
652```liquid
653{{ range datacenters }}
654{{ . }}{{ end }}
655```
656
657renders
658
659```text
660dc1
661dc2
662```
663
664An optional boolean can be specified which instructs Consul Template to ignore
665datacenters which are inaccessible or do not have a current leader. Enabling
666this option requires an O(N+1) operation and therefore is not recommended in
667environments where performance is a factor.
668
669```liquid
670// Ignores datacenters which are inaccessible
671{{ datacenters true }}
672```
673
674##### `file`
675
676Read and output the contents of a local file on disk. If the file cannot be
677read, an error will occur. When the file changes, Consul Template will pick up
678the change and re-render the template.
679
680```liquid
681{{ file "<PATH>" }}
682```
683
684For example:
685
686```liquid
687{{ file "/path/to/my/file" }}
688```
689
690renders
691
692```text
693file contents
694```
695
696This does not process nested templates. See
697[`executeTemplate`](#executeTemplate) for a way to render nested templates.
698
699##### `key`
700
701Query [Consul][consul] for the value at the given key path. If the key does not
702exist, Consul Template will block rendering until the key is present. To avoid
703blocking, use `keyOrDefault` or `keyExists`.
704
705```liquid
706{{ key "<PATH>@<DATACENTER>" }}
707```
708
709The `<DATACENTER>` attribute is optional; if omitted, the local datacenter is
710used.
711
712For example:
713
714```liquid
715{{ key "service/redis/maxconns" }}
716```
717
718renders
719
720```text
72115
722```
723
724##### `keyExists`
725
726Query [Consul][consul] for the value at the given key path. If the key exists,
727this will return true, false otherwise. Unlike `key`, this function will not
728block if the key does not exist. This is useful for controlling flow.
729
730```liquid
731{{ keyExists "<PATH>@<DATACENTER>" }}
732```
733
734The `<DATACENTER>` attribute is optional; if omitted, the local datacenter is
735used.
736
737For example:
738
739```liquid
740{{ if keyExists "app/beta_active" }}
741  # ...
742{{ else }}
743  # ...
744{{ end }}
745```
746
747##### `keyOrDefault`
748
749Query [Consul][consul] for the value at the given key path. If the key does not
750exist, the default value will be used instead. Unlike `key`, this function will
751not block if the key does not exist.
752
753```liquid
754{{ keyOrDefault "<PATH>@<DATACENTER>" "<DEFAULT>" }}
755```
756
757The `<DATACENTER>` attribute is optional; if omitted, the local datacenter is
758used.
759
760For example:
761
762```liquid
763{{ keyOrDefault "service/redis/maxconns" "5" }}
764```
765
766renders
767
768```text
7695
770```
771
772Note that Consul Template uses a [multi-phase
773execution](#multi-phase-execution). During the first phase of evaluation, Consul
774Template will have no data from Consul and thus will _always_ fall back to the
775default value. Subsequent reads from Consul will pull in the real value from
776Consul (if the key exists) on the next template pass. This is important because
777it means that Consul Template will never "block" the rendering of a template due
778to a missing key from a `keyOrDefault`. Even if the key exists, if Consul has
779not yet returned data for the key, the default value will be used instead.
780
781##### `ls`
782
783Query [Consul][consul] for all top-level kv pairs at the given key path.
784
785```liquid
786{{ ls "<PATH>@<DATACENTER>" }}
787```
788
789The `<DATACENTER>` attribute is optional; if omitted, the local datacenter is
790used.
791
792For example:
793
794```liquid
795{{ range ls "service/redis" }}
796{{ .Key }}:{{ .Value }}{{ end }}
797```
798
799renders
800
801```text
802maxconns:15
803minconns:5
804```
805
806##### `safeLs`
807
808Same as [ls](#ls), but refuse to render template, if the KV prefix query return blank/empty data.
809
810This is especially useful, for rendering mission critical files, that are being populated by consul-template.
811
812For example:
813
814```text
815/root/.ssh/authorized_keys
816/etc/sysconfig/iptables
817```
818
819Using `safeLs` on empty prefixes will result in template output not being rendered at all.
820
821To learn how `safeLs` was born see [CT-1131](https://github.com/hashicorp/consul-template/issues/1131) [C-3975](https://github.com/hashicorp/consul/issues/3975) and [CR-82](https://github.com/hashicorp/consul-replicate/issues/82).
822
823##### `node`
824
825Query [Consul][consul] for a node in the catalog.
826
827```liquid
828{{node "<NAME>@<DATACENTER>"}}
829```
830
831The `<NAME>` attribute is optional; if omitted, the local agent node is used.
832
833The `<DATACENTER>` attribute is optional; if omitted, the local datacenter is
834used.
835
836For example:
837
838```liquid
839{{ with node }}
840{{ .Node.Address }}{{ end }}
841```
842
843renders
844
845```text
84610.5.2.6
847```
848
849To query a different node:
850
851```liquid
852{{ with node "node1@dc2" }}
853{{ .Node.Address }}{{ end }}
854```
855
856renders
857
858```text
85910.4.2.6
860```
861
862To access map data such as `TaggedAddresses` or `Meta`, use
863[Go's text/template][text-template] map indexing.
864
865##### `nodes`
866
867Query [Consul][consul] for all nodes in the catalog.
868
869```liquid
870{{ nodes "@<DATACENTER>~<NEAR>" }}
871```
872
873The `<DATACENTER>` attribute is optional; if omitted, the local datacenter is
874used.
875
876The `<NEAR>` attribute is optional; if omitted, results are specified in lexical
877order. If provided a node name, results are ordered by shortest round-trip time
878to the provided node. If provided `_agent`, results are ordered by shortest
879round-trip time to the local agent.
880
881For example:
882
883```liquid
884{{ range nodes }}
885{{ .Address }}{{ end }}
886```
887
888renders
889
890```text
89110.4.2.13
89210.46.2.5
893```
894
895To query a different data center and order by shortest trip time to ourselves:
896
897```liquid
898{{ range nodes "@dc2~_agent" }}
899{{ .Address }}{{ end }}
900```
901
902To access map data such as `TaggedAddresses` or `Meta`, use
903[Go's text/template][text-template] map indexing.
904
905##### `secret`
906
907Query [Vault][vault] for the secret at the given path.
908
909```liquid
910{{ secret "<PATH>" "<DATA>" }}
911```
912
913The `<DATA>` attribute is optional; if omitted, the request will be a `vault
914read` (HTTP GET) request. If provided, the request will be a `vault write` (HTTP
915PUT/POST) request.
916
917For example:
918
919```liquid
920{{ with secret "secret/passwords" }}
921{{ .Data.wifi }}{{ end }}
922```
923
924renders
925
926```text
927FORWARDSoneword
928```
929
930To access a versioned secret value (for the K/V version 2 backend):
931
932```liquid
933{{ with secret "secret/passwords?version=1" }}
934{{ .Data.data.wifi }}{{ end }}
935```
936
937When omitting the `?version` parameter, the latest version of the secret will be
938fetched. Note the nested `.Data.data` syntax when referencing the secret value.
939For more information about using the K/V v2 backend, see the
940[Vault Documentation](https://www.vaultproject.io/docs/secrets/kv/kv-v2.html).
941
942When using Vault versions 0.10.0/0.10.1, the secret path will have to be prefixed
943with "data", i.e. `secret/data/passwords` for the example above. This is not
944necessary for Vault versions after 0.10.1, as consul-template will detect the KV
945backend version being used. The version 2 KV backend did not exist prior to 0.10.0,
946so these are the only affected versions.
947
948An example using write to generate PKI certificates:
949
950```liquid
951{{ with secret "pki/issue/my-domain-dot-com" "common_name=foo.example.com" }}
952{{ .Data.certificate }}{{ end }}
953```
954
955The parameters must be `key=value` pairs, and each pair must be its own argument
956to the function:
957
958Please always consider the security implications of having the contents of a
959secret in plain-text on disk. If an attacker is able to get access to the file,
960they will have access to plain-text secrets.
961
962Please note that Vault does not support blocking queries. As a result, Consul
963Template will not immediately reload in the event a secret is changed as it
964does with Consul's key-value store. Consul Template will renew the secret with
965Vault's [Renewer API](https://godoc.org/github.com/hashicorp/vault/api#Renewer).
966The Renew API tries to use most of the time the secret is good, renewing at
967around 90% of the lease time (as set by Vault).
968
969Also consider enabling `error_on_missing_key` when working with templates that
970will interact with Vault. By default, Consul Template uses Go's templating
971language. When accessing a struct field or map key that does not exist, it
972defaults to printing `<no value>`. This may not be the desired behavior,
973especially when working with passwords or other data. As such, it is recommended
974you set:
975
976```hcl
977template {
978  error_on_missing_key = true
979}
980```
981
982You can also guard against empty values using `if` or `with` blocks.
983
984```liquid
985{{ with secret "secret/foo"}}
986{{ if .Data.password }}
987password = "{{ .Data.password }}"
988{{ end }}
989{{ end }}
990```
991
992##### `secrets`
993
994Query [Vault][vault] for the list of secrets at the given path. Not all
995endpoints support listing.
996
997```liquid
998{{ secrets "<PATH>" }}
999```
1000
1001For example:
1002
1003```liquid
1004{{ range secrets "secret/" }}
1005{{ . }}{{ end }}
1006```
1007
1008renders
1009
1010```text
1011bar
1012foo
1013zip
1014```
1015
1016To iterate and list over every secret in the generic secret backend in Vault:
1017
1018```liquid
1019{{ range secrets "secret/" }}
1020{{ with secret (printf "secret/%s" .) }}{{ range $k, $v := .Data }}
1021{{ $k }}: {{ $v }}
1022{{ end }}{{ end }}{{ end }}
1023```
1024
1025You should probably never do this.
1026
1027Please also note that Vault does not support
1028blocking queries. To understand the implications, please read the note at the
1029end of the `secret` function.
1030
1031##### `service`
1032
1033Query [Consul][consul] for services based on their health.
1034
1035```liquid
1036{{ service "<TAG>.<NAME>@<DATACENTER>~<NEAR>|<FILTER>" }}
1037```
1038
1039The `<TAG>` attribute is optional; if omitted, all nodes will be queried.
1040
1041The `<DATACENTER>` attribute is optional; if omitted, the local datacenter is
1042used.
1043
1044The `<NEAR>` attribute is optional; if omitted, results are specified in lexical
1045order. If provided a node name, results are ordered by shortest round-trip time
1046to the provided node. If provided `_agent`, results are ordered by shortest
1047round-trip time to the local agent.
1048
1049The `<FILTER>` attribute is optional; if omitted, only health services are
1050returned. Providing a filter allows for client-side filtering of services.
1051
1052For example:
1053
1054The example above is querying Consul for healthy "web" services, in the "east-aws" data center. The tag and data center attributes are optional. To query all nodes of the "web" service (regardless of tag) for the current data center:
1055
1056```liquid
1057{{ range service "web" }}
1058server {{ .Name }} {{ .Address }}:{{ .Port }}{{ end }}
1059```
1060
1061renders the IP addresses of all _healthy_ nodes with a logical service named
1062"web":
1063
1064```text
1065server web01 10.5.2.45:2492
1066server web02 10.2.6.61:2904
1067```
1068
1069To access map data such as `NodeTaggedAddresses` or `NodeMeta`, use
1070[Go's text/template][text-template] map indexing.
1071
1072By default only healthy services are returned. To list all services, pass the
1073"any" filter:
1074
1075```liquid
1076{{ service "web|any" }}
1077```
1078
1079This will return all services registered to the agent, regardless of their
1080status.
1081
1082To filter services by a specific set of healths, specify a comma-separated list
1083of health statuses:
1084
1085```liquid
1086{{ service "web|passing,warning" }}
1087```
1088
1089This will returns services which are deemed "passing" or "warning" according to
1090their node and service-level checks defined in Consul. Please note that the
1091comma implies an "or", not an "and".
1092
1093**Note:** Due to the use of dot `.` to delimit TAG, the `service` command will
1094not recognize service names containing dots.
1095
1096**Note:** There is an architectural difference between the following:
1097
1098```liquid
1099{{ service "web" }}
1100{{ service "web|passing" }}
1101```
1102
1103The former will return all services which Consul considers "healthy" and
1104passing. The latter will return all services registered with the Consul agent
1105and perform client-side filtering. As a general rule, do not use the "passing"
1106argument alone if you want only healthy services - simply omit the second
1107argument instead.
1108
1109
1110##### `services`
1111
1112Query [Consul][consul] for all services in the catalog.
1113
1114```liquid
1115{{ services "@<DATACENTER>" }}
1116```
1117
1118The `<DATACENTER>` attribute is optional; if omitted, the local datacenter is
1119used.
1120
1121For example:
1122
1123```liquid
1124{{ range services }}
1125{{ .Name }}: {{ .Tags | join "," }}{{ end }}
1126```
1127
1128renders
1129
1130```text
1131node01 tag1,tag2,tag3
1132```
1133
1134##### `tree`
1135
1136Query [Consul][consul] for all kv pairs at the given key path.
1137
1138```liquid
1139{{ tree "<PATH>@<DATACENTER>" }}
1140```
1141
1142The `<DATACENTER>` attribute is optional; if omitted, the local datacenter is
1143used.
1144
1145For example:
1146
1147```liquid
1148{{ range tree "service/redis" }}
1149{{ .Key }}:{{ .Value }}{{ end }}
1150```
1151renders
1152
1153```text
1154minconns 2
1155maxconns 12
1156nested/config/value "value"
1157```
1158
1159Unlike `ls`, `tree` returns **all** keys under the prefix, just like the Unix
1160`tree` command.
1161
1162##### `safeTree`
1163
1164Same as [tree](#tree), but refuse to render template, if the KV prefix query return blank/empty data.
1165
1166This is especially useful, for rendering mission critical files, that are being populated by consul-template.
1167
1168For example:
1169
1170```text
1171/root/.ssh/authorized_keys
1172/etc/sysconfig/iptables
1173```
1174
1175Using `safeTree` on empty prefixes will result in template output not being rendered at all.
1176
1177To learn how `safeTree` was born see [CT-1131](https://github.com/hashicorp/consul-template/issues/1131) [C-3975](https://github.com/hashicorp/consul/issues/3975) and [CR-82](https://github.com/hashicorp/consul-replicate/issues/82).
1178
1179---
1180
1181#### Scratch
1182
1183The scratchpad (or "scratch" for short) is available within the context of a
1184template to store temporary data or computations. Scratch data is not shared
1185between templates and is not cached between invocations.
1186
1187##### `scratch.Key`
1188
1189Returns a boolean if data exists in the scratchpad at the named key. Even if the
1190data at that key is "nil", this still returns true.
1191
1192```liquid
1193{{ scratch.Key "foo" }}
1194```
1195
1196##### `scratch.Get`
1197
1198Returns the value in the scratchpad at the named key. If the data does not
1199exist, this will return "nil".
1200
1201```liquid
1202{{ scratch.Get "foo" }}
1203```
1204
1205##### `scratch.Set`
1206
1207Saves the given value at the given key. If data already exists at that key, it
1208is overwritten.
1209
1210```liquid
1211{{ scratch.Set "foo" "bar" }}
1212```
1213
1214##### `scratch.SetX`
1215
1216This behaves exactly the same as `Set`, but does not overwrite if the value
1217already exists.
1218
1219```liquid
1220{{ scratch.SetX "foo" "bar" }}
1221```
1222
1223##### `scratch.MapSet`
1224
1225Saves a value in a named key in the map. If data already exists at that key, it
1226is overwritten.
1227
1228```liquid
1229{{ scratch.MapSet "vars" "foo" "bar" }}
1230```
1231
1232##### `scratch.MapSetX`
1233
1234This behaves exactly the same as `MapSet`, but does not overwrite if the value
1235already exists.
1236
1237```liquid
1238{{ scratch.MapSetX "vars" "foo" "bar" }}
1239```
1240
1241##### `scratch.MapValues`
1242
1243Returns a sorted list (by key) of all values in the named map.
1244
1245```liquid
1246{{ scratch.MapValues "vars" }}
1247```
1248
1249---
1250
1251#### Helper Functions
1252
1253Unlike API functions, helper functions do not query remote services. These
1254functions are useful for parsing data, formatting data, performing math, etc.
1255
1256##### `base64Decode`
1257
1258Accepts a base64-encoded string and returns the decoded result, or an error if
1259the given string is not a valid base64 string.
1260
1261```liquid
1262{{ base64Decode "aGVsbG8=" }}
1263```
1264
1265renders
1266
1267```text
1268hello
1269```
1270
1271##### `base64Encode`
1272
1273Accepts a string and returns a base64-encoded string.
1274
1275```liquid
1276{{ base64Encode "hello" }}
1277```
1278
1279renders
1280
1281```text
1282aGVsbG8=
1283```
1284
1285##### `base64URLDecode`
1286
1287Accepts a base64-encoded URL-safe string and returns the decoded result, or an
1288error if the given string is not a valid base64 URL-safe string.
1289
1290```liquid
1291{{ base64URLDecode "aGVsbG8=" }}
1292```
1293
1294renders
1295
1296```text
1297hello
1298```
1299
1300##### `base64URLEncode`
1301
1302Accepts a string and returns a base-64 encoded URL-safe string.
1303
1304```liquid
1305{{ base64Encode "hello" }}
1306```
1307
1308renders
1309
1310```text
1311aGVsbG8=
1312```
1313
1314##### `byKey`
1315
1316Accepts a list of pairs returned from a [`tree`](#tree) call and creates a map that groups pairs by their top-level directory.
1317
1318For example:
1319
1320```text
1321groups/elasticsearch/es1
1322groups/elasticsearch/es2
1323groups/elasticsearch/es3
1324services/elasticsearch/check_elasticsearch
1325services/elasticsearch/check_indexes
1326```
1327
1328with the following template
1329
1330```liquid
1331{{ range $key, $pairs := tree "groups" | byKey }}{{ $key }}:
1332{{ range $pair := $pairs }}  {{ .Key }}={{ .Value }}
1333{{ end }}{{ end }}
1334```
1335
1336renders
1337
1338```text
1339elasticsearch:
1340  es1=1
1341  es2=1
1342  es3=1
1343```
1344
1345Note that the top-most key is stripped from the Key value. Keys that have no
1346prefix after stripping are removed from the list.
1347
1348The resulting pairs are keyed as a map, so it is possible to look up a single
1349value by key:
1350
1351```liquid
1352{{ $weights := tree "weights" }}
1353{{ range service "release.web" }}
1354  {{ $weight := or (index $weights .Node) 100 }}
1355  server {{ .Node }} {{ .Address }}:{{ .Port }} weight {{ $weight }}{{ end }}
1356```
1357
1358##### `byTag`
1359
1360Takes the list of services returned by the [`service`](#service) or
1361[`services`](#services) function and creates a map that groups services by tag.
1362
1363```liquid
1364{{ range $tag, $services := service "web" | byTag }}{{ $tag }}
1365{{ range $services }} server {{ .Name }} {{ .Address }}:{{ .Port }}
1366{{ end }}{{ end }}
1367```
1368
1369##### `byMeta`
1370
1371Takes a list of services returned by the [`service`](#service) or
1372[`services`](#services) and returns a map that groups services by ServiceMeta values.
1373Multiple service meta keys can be passed as a comma separated string. `|int` can be added to
1374a meta key to convert numbers from service meta values to padded numbers in `printf "%05d" % value`
1375format (useful for sorting as Go Template sorts maps by keys).
1376
1377**Example**:
1378
1379If we have the following services registered in Consul:
1380
1381```json
1382{
1383  "Services": [
1384     {
1385       "ID": "redis-dev-1",
1386       "Name": "redis",
1387       "ServiceMeta": {
1388         "environment": "dev",
1389         "shard_number": "1"
1390       },
1391       ...
1392     },
1393     {
1394       "ID": "redis-prod-1",
1395       "Name": "redis",
1396       "ServiceMeta": {
1397         "environment": "prod",
1398         "shard_number": "1"
1399       },
1400       ...
1401     },
1402     {
1403       "ID": "redis-prod-2",
1404       "Name": "redis",
1405       "ServiceMeta": {
1406         "environment": "prod",
1407         "shard_number": "2",
1408       },
1409       ...
1410     }
1411   ]
1412}
1413```
1414
1415```liquid
1416{{ service "redis|any" | byMeta "environment,shard_number|int" | toJSON }}
1417```
1418
1419The code above will produce a map of services grouped by meta:
1420
1421```json
1422{
1423  "dev_00001": [
1424    {
1425      "ID": "redis-dev-1",
1426      ...
1427    }
1428  ],
1429  "prod_00001": [
1430    {
1431      "ID": "redis-prod-1",
1432      ...
1433    }
1434  ],
1435  "prod_00002": [
1436    {
1437      "ID": "redis-prod-2",
1438      ...
1439    }
1440  ]
1441}
1442```
1443
1444##### `contains`
1445
1446Determines if a needle is within an iterable element.
1447
1448```liquid
1449{{ if .Tags | contains "production" }}
1450# ...
1451{{ end }}
1452```
1453
1454##### `containsAll`
1455
1456Returns `true` if all needles are within an iterable element, or `false`
1457otherwise. Returns `true` if the list of needles is empty.
1458
1459```liquid
1460{{ if containsAll $requiredTags .Tags }}
1461# ...
1462{{ end }}
1463```
1464
1465##### `containsAny`
1466
1467Returns `true` if any needle is within an iterable element, or `false`
1468otherwise. Returns `false` if the list of needles is empty.
1469
1470```liquid
1471{{ if containsAny $acceptableTags .Tags }}
1472# ...
1473{{ end }}
1474```
1475
1476##### `containsNone`
1477
1478Returns `true` if no needles are within an iterable element, or `false`
1479otherwise. Returns `true` if the list of needles is empty.
1480
1481```liquid
1482{{ if containsNone $forbiddenTags .Tags }}
1483# ...
1484{{ end }}
1485```
1486
1487##### `containsNotAll`
1488
1489Returns `true` if some needle is not within an iterable element, or `false`
1490otherwise. Returns `false` if the list of needles is empty.
1491
1492```liquid
1493{{ if containsNotAll $excludingTags .Tags }}
1494# ...
1495{{ end }}
1496```
1497
1498##### `env`
1499
1500Reads the given environment variable accessible to the current process.
1501
1502```liquid
1503{{ env "CLUSTER_ID" }}
1504```
1505
1506This function can be chained to manipulate the output:
1507
1508```liquid
1509{{ env "CLUSTER_ID" | toLower }}
1510```
1511
1512Reads the given environment variable and if it does not exist or is blank use a default value, ex `12345`.
1513
1514```liquid
1515{{ or (env "CLUSTER_ID") "12345" }}
1516```
1517
1518##### `executeTemplate`
1519
1520Executes and returns a defined template.
1521
1522```liquid
1523{{ define "custom" }}my custom template{{ end }}
1524
1525This is my other template:
1526{{ executeTemplate "custom" }}
1527
1528And I can call it multiple times:
1529{{ executeTemplate "custom" }}
1530
1531Even with a new context:
1532{{ executeTemplate "custom" 42 }}
1533
1534Or save it to a variable:
1535{{ $var := executeTemplate "custom" }}
1536```
1537
1538##### `explode`
1539
1540Takes the result from a `tree` or `ls` call and converts it into a deeply-nested
1541map for parsing/traversing.
1542
1543```liquid
1544{{ tree "config" | explode }}
1545```
1546
1547Note: You will lose any metadata about the key-pair after it has been exploded.
1548You can also access deeply nested values:
1549
1550```liquid
1551{{ with tree "config" | explode }}
1552{{ .a.b.c }}{{ end }}
1553```
1554
1555You will need to have a reasonable format about your data in Consul. Please see
1556[Go's text/template package][text-template] for more information.
1557
1558
1559##### `explodeMap`
1560
1561Takes the value of a map and converts it into a deeply-nested map for parsing/traversing,
1562using the same logic as `explode`.
1563
1564```liquid
1565{{ scratch.MapSet "example", "foo/bar", "a" }}
1566{{ scratch.MapSet "example", "foo/baz", "b" }}
1567{{ scratch.Get "example" | explodeMap | toYAML }}
1568```
1569
1570##### `indent`
1571
1572Indents a block of text by prefixing N number of spaces per line.
1573
1574```liquid
1575{{ tree "foo" | explode | toYAML | indent 4 }}
1576```
1577
1578##### `in`
1579
1580Determines if a needle is within an iterable element.
1581
1582```liquid
1583{{ if in .Tags "production" }}
1584# ...
1585{{ end }}
1586```
1587
1588##### `loop`
1589
1590Accepts varying parameters and differs its behavior based on those parameters.
1591
1592If `loop` is given one integer, it will return a goroutine that begins at zero
1593and loops up to but not including the given integer:
1594
1595```liquid
1596{{ range loop 5 }}
1597# Comment{{end}}
1598```
1599
1600If given two integers, this function will return a goroutine that begins at
1601the first integer and loops up to but not including the second integer:
1602
1603```liquid
1604{{ range $i := loop 5 8 }}
1605stanza-{{ $i }}{{ end }}
1606```
1607
1608which would render:
1609
1610```text
1611stanza-5
1612stanza-6
1613stanza-7
1614```
1615
1616Note: It is not possible to get the index and the element since the function
1617returns a goroutine, not a slice. In other words, the following is **not
1618valid**:
1619
1620```liquid
1621# Will NOT work!
1622{{ range $i, $e := loop 5 8 }}
1623# ...{{ end }}
1624```
1625
1626##### `join`
1627
1628Takes the given list of strings as a pipe and joins them on the provided string:
1629
1630```liquid
1631{{ $items | join "," }}
1632```
1633
1634##### `trimSpace`
1635
1636Takes the provided input and trims all whitespace, tabs and newlines:
1637
1638```liquid
1639{{ file "/etc/ec2_version" | trimSpace }}
1640```
1641
1642##### `parseBool`
1643
1644Takes the given string and parses it as a boolean:
1645
1646```liquid
1647{{ "true" | parseBool }}
1648```
1649
1650This can be combined with a key and a conditional check, for example:
1651
1652```liquid
1653{{ if key "feature/enabled" | parseBool }}{{ end }}
1654```
1655
1656##### `parseFloat`
1657
1658Takes the given string and parses it as a base-10 float64:
1659
1660```liquid
1661{{ "1.2" | parseFloat }}
1662```
1663
1664##### `parseInt`
1665
1666Takes the given string and parses it as a base-10 int64:
1667
1668```liquid
1669{{ "1" | parseInt }}
1670```
1671
1672This can be combined with other helpers, for example:
1673
1674```liquid
1675{{ range $i := loop key "config/pool_size" | parseInt }}
1676# ...{{ end }}
1677```
1678
1679##### `parseJSON`
1680
1681Takes the given input (usually the value from a key) and parses the result as
1682JSON:
1683
1684```liquid
1685{{ with $d := key "user/info" | parseJSON }}{{ $d.name }}{{ end }}
1686```
1687
1688Note: Consul Template evaluates the template multiple times, and on the first
1689evaluation the value of the key will be empty (because no data has been loaded
1690yet). This means that templates must guard against empty responses.
1691
1692##### `parseUint`
1693
1694Takes the given string and parses it as a base-10 int64:
1695
1696```liquid
1697{{ "1" | parseUint }}
1698```
1699
1700##### `plugin`
1701
1702Takes the name of a plugin and optional payload and executes a Consul Template
1703plugin.
1704
1705```liquid
1706{{ plugin "my-plugin" }}
1707```
1708
1709The plugin can take an arbitrary number of string arguments, and can be the
1710target of a pipeline that produces strings as well. This is most commonly
1711combined with a JSON filter for customization:
1712
1713```liquid
1714{{ tree "foo" | explode | toJSON | plugin "my-plugin" }}
1715```
1716
1717Please see the [plugins](#plugins) section for more information about plugins.
1718
1719##### `regexMatch`
1720
1721Takes the argument as a regular expression and will return `true` if it matches
1722on the given string, or `false` otherwise.
1723
1724```liquid
1725{{ if "foo.bar" | regexMatch "foo([.a-z]+)" }}
1726# ...
1727{{ else }}
1728# ...
1729{{ end }}
1730```
1731
1732##### `regexReplaceAll`
1733
1734Takes the argument as a regular expression and replaces all occurrences of the
1735regex with the given string. As in go, you can use variables like $1 to refer to
1736subexpressions in the replacement string.
1737
1738```liquid
1739{{ "foo.bar" | regexReplaceAll "foo([.a-z]+)" "$1" }}
1740```
1741
1742##### `replaceAll`
1743
1744Takes the argument as a string and replaces all occurrences of the given string
1745with the given string.
1746
1747```liquid
1748{{ "foo.bar" | replaceAll "." "_" }}
1749```
1750
1751This function can be chained with other functions as well:
1752
1753```liquid
1754{{ service "web" }}{{ .Name | replaceAll ":" "_" }}{{ end }}
1755```
1756
1757##### `split`
1758
1759Splits the given string on the provided separator:
1760
1761```liquid
1762{{ "foo\nbar\n" | split "\n" }}
1763```
1764
1765This can be combined with chained and piped with other functions:
1766
1767```liquid
1768{{ key "foo" | toUpper | split "\n" | join "," }}
1769```
1770
1771##### `timestamp`
1772
1773Returns the current timestamp as a string (UTC). If no arguments are given, the
1774result is the current RFC3339 timestamp:
1775
1776```liquid
1777{{ timestamp }} // e.g. 1970-01-01T00:00:00Z
1778```
1779
1780If the optional parameter is given, it is used to format the timestamp. The
1781magic reference date **Mon Jan 2 15:04:05 -0700 MST 2006** can be used to format
1782the date as required:
1783
1784```liquid
1785{{ timestamp "2006-01-02" }} // e.g. 1970-01-01
1786```
1787
1788See [Go's `time.Format`](http://golang.org/pkg/time/#Time.Format) for more
1789information.
1790
1791As a special case, if the optional parameter is `"unix"`, the unix timestamp in
1792seconds is returned as a string.
1793
1794```liquid
1795{{ timestamp "unix" }} // e.g. 0
1796```
1797
1798##### `toJSON`
1799
1800Takes the result from a `tree` or `ls` call and converts it into a JSON object.
1801
1802```liquid
1803{{ tree "config" | explode | toJSON }}
1804```
1805
1806renders
1807
1808```javascript
1809{"admin":{"port":"1234"},"maxconns":"5","minconns":"2"}
1810```
1811
1812Note: Consul stores all KV data as strings. Thus true is "true", 1 is "1", etc.
1813
1814##### `toJSONPretty`
1815
1816Takes the result from a `tree` or `ls` call and converts it into a
1817pretty-printed JSON object, indented by two spaces.
1818
1819```liquid
1820{{ tree "config" | explode | toJSONPretty }}
1821```
1822
1823renders
1824
1825```javascript
1826{
1827  "admin": {
1828    "port": "1234"
1829  },
1830  "maxconns": "5",
1831  "minconns": "2",
1832}
1833```
1834
1835Note: Consul stores all KV data as strings. Thus true is "true", 1 is "1", etc.
1836
1837##### `toLower`
1838
1839Takes the argument as a string and converts it to lowercase.
1840
1841```liquid
1842{{ key "user/name" | toLower }}
1843```
1844
1845See [Go's `strings.ToLower`](http://golang.org/pkg/strings/#ToLower) for more
1846information.
1847
1848##### `toTitle`
1849
1850Takes the argument as a string and converts it to titlecase.
1851
1852```liquid
1853{{ key "user/name" | toTitle }}
1854```
1855
1856See [Go's `strings.Title`](http://golang.org/pkg/strings/#Title) for more
1857information.
1858
1859##### `toTOML`
1860
1861Takes the result from a `tree` or `ls` call and converts it into a TOML object.
1862
1863```liquid
1864{{ tree "config" | explode | toTOML }}
1865```
1866
1867renders
1868
1869```toml
1870maxconns = "5"
1871minconns = "2"
1872
1873[admin]
1874  port = "1134"
1875```
1876
1877Note: Consul stores all KV data as strings. Thus true is "true", 1 is "1", etc.
1878
1879##### `toUpper`
1880
1881Takes the argument as a string and converts it to uppercase.
1882
1883```liquid
1884{{ key "user/name" | toUpper }}
1885```
1886
1887See [Go's `strings.ToUpper`](http://golang.org/pkg/strings/#ToUpper) for more
1888information.
1889
1890##### `toYAML`
1891
1892Takes the result from a `tree` or `ls` call and converts it into a
1893pretty-printed YAML object, indented by two spaces.
1894
1895```liquid
1896{{ tree "config" | explode | toYAML }}
1897```
1898
1899renders
1900
1901```yaml
1902admin:
1903  port: "1234"
1904maxconns: "5"
1905minconns: "2"
1906```
1907
1908Note: Consul stores all KV data as strings. Thus true is "true", 1 is "1", etc.
1909
1910##### `sockaddr`
1911
1912Takes a quote-escaped template string as an argument and passes it on to
1913[hashicorp/go-sockaddr](https://github.com/hashicorp/go-sockaddr) templating engine.
1914
1915```liquid
1916{{ sockaddr "GetPrivateIP" }}
1917```
1918
1919See [hashicorp/go-sockaddr documentation](https://godoc.org/github.com/hashicorp/go-sockaddr)
1920for more information.
1921
1922---
1923
1924#### Math Functions
1925
1926The following functions are available on floats and integer values.
1927
1928##### `add`
1929
1930Returns the sum of the two values.
1931
1932```liquid
1933{{ add 1 2 }} // 3
1934```
1935
1936This can also be used with a pipe function.
1937
1938```liquid
1939{{ 1 | add 2 }} // 3
1940```
1941
1942##### `subtract`
1943
1944Returns the difference of the second value from the first.
1945
1946```liquid
1947{{ subtract 2 5 }} // 3
1948```
1949
1950This can also be used with a pipe function.
1951
1952```liquid
1953{{ 5 | subtract 2 }} // 3
1954```
1955
1956Please take careful note of the order of arguments.
1957
1958##### `multiply`
1959
1960Returns the product of the two values.
1961
1962```liquid
1963{{ multiply 2 2 }} // 4
1964```
1965
1966This can also be used with a pipe function.
1967
1968```liquid
1969{{ 2 | multiply 2 }} // 4
1970```
1971
1972##### `divide`
1973
1974Returns the division of the second value from the first.
1975
1976```liquid
1977{{ divide 2 10 }} // 5
1978```
1979
1980This can also be used with a pipe function.
1981
1982```liquid
1983{{ 10 | divide 2 }} // 5
1984```
1985
1986Please take careful note of the order or arguments.
1987
1988##### `modulo`
1989
1990Returns the modulo of the second value from the first.
1991
1992```liquid
1993{{ modulo 2 5 }} // 1
1994```
1995
1996This can also be used with a pipe function.
1997
1998```liquid
1999{{ 5 | modulo 2 }} // 1
2000```
2001
2002Please take careful note of the order of arguments.
2003
2004## Plugins
2005
2006### Authoring Plugins
2007
2008For some use cases, it may be necessary to write a plugin that offloads work to
2009another system. This is especially useful for things that may not fit in the
2010"standard library" of Consul Template, but still need to be shared across
2011multiple instances.
2012
2013Consul Template plugins must have the following API:
2014
2015```shell
2016$ NAME [INPUT...]
2017```
2018
2019- `NAME` - the name of the plugin - this is also the name of the binary, either
2020  a full path or just the program name.  It will be executed in a shell with the
2021  inherited `PATH` so e.g. the plugin `cat` will run the first executable `cat`
2022  that is found on the `PATH`.
2023
2024- `INPUT` - input from the template. There will be one INPUT for every argument passed
2025  to the `plugin` function. If the arguments contain whitespace, that whitespace
2026  will be passed as if the argument were quoted by the shell.
2027
2028#### Important Notes
2029
2030- Plugins execute user-provided scripts and pass in potentially sensitive data
2031  from Consul or Vault. Nothing is validated or protected by Consul Template,
2032  so all necessary precautions and considerations should be made by template
2033  authors
2034
2035- Plugin output must be returned as a string on stdout. Only stdout will be
2036  parsed for output. Be sure to log all errors, debugging messages onto stderr
2037  to avoid errors when Consul Template returns the value. Note that output to
2038  stderr will only be output if the plugin returns a non-zero exit code.
2039
2040- Always `exit 0` or Consul Template will assume the plugin failed to execute
2041
2042- Ensure the empty input case is handled correctly (see [Multi-phase execution](#multi-phase-execution))
2043
2044- Data piped into the plugin is appended after any parameters given explicitly (eg `{{ "sample-data" | plugin "my-plugin" "some-parameter"}}` will call `my-plugin some-parameter sample-data`)
2045
2046Here is a sample plugin in a few different languages that removes any JSON keys
2047that start with an underscore and returns the JSON string:
2048
2049```ruby
2050#! /usr/bin/env ruby
2051require "json"
2052
2053if ARGV.empty?
2054  puts JSON.fast_generate({})
2055  Kernel.exit(0)
2056end
2057
2058hash = JSON.parse(ARGV.first)
2059hash.reject! { |k, _| k.start_with?("_")  }
2060puts JSON.fast_generate(hash)
2061Kernel.exit(0)
2062```
2063
2064```go
2065func main() {
2066  arg := []byte(os.Args[1])
2067
2068  var parsed map[string]interface{}
2069  if err := json.Unmarshal(arg, &parsed); err != nil {
2070    fmt.Fprintln(os.Stderr, fmt.Sprintf("err: %s", err))
2071    os.Exit(1)
2072  }
2073
2074  for k, _ := range parsed {
2075    if string(k[0]) == "_" {
2076      delete(parsed, k)
2077    }
2078  }
2079
2080  result, err := json.Marshal(parsed)
2081  if err != nil {
2082    fmt.Fprintln(os.Stderr, fmt.Sprintf("err: %s", err))
2083    os.Exit(1)
2084  }
2085
2086  fmt.Fprintln(os.Stdout, fmt.Sprintf("%s", result))
2087  os.Exit(0)
2088}
2089```
2090
2091## Caveats
2092
2093### Dots in Service Names
2094
2095Using dots `.` in service names will conflict with the use of dots for [TAG
2096delineation](https://github.com/hashicorp/consul-template#service) in the
2097template. Dots already [interfere with using
2098DNS](https://www.consul.io/docs/agent/services.html#service-and-tag-names-with-dns)
2099for service names, so we recommend avoiding dots wherever possible.
2100
2101### Once Mode
2102
2103In Once mode, Consul Template will wait for all dependencies to be rendered. If
2104a template specifies a dependency (a request) that does not exist in Consul,
2105once mode will wait until Consul returns data for that dependency. Please note
2106that "returned data" and "empty data" are not mutually exclusive.
2107
2108When you query for all healthy services named "foo" (`{{ service "foo" }}`), you
2109are asking Consul - "give me all the healthy services named foo". If there are
2110no services named foo, the response is the empty array. This is also the same
2111response if there are no _healthy_ services named foo.
2112
2113Consul template processes input templates multiple times, since the first result
2114could impact later dependencies:
2115
2116```liquid
2117{{ range services }}
2118{{ range service .Name }}
2119{{ end }}
2120{{ end }}
2121```
2122
2123In this example, we have to process the output of `services` before we can
2124lookup each `service`, since the inner loops cannot be evaluated until the outer
2125loop returns a response. Consul Template waits until it gets a response from
2126Consul for all dependencies before rendering a template. It does not wait until
2127that response is non-empty though.
2128
2129**Note:** Once mode implicitly disables any wait/quiescence timers specified in configuration files or passed on the command line.
2130
2131### Exec Mode
2132
2133As of version 0.16.0, Consul Template has the ability to maintain an arbitrary
2134child process (similar to [envconsul](https://github.com/hashicorp/envconsul)).
2135This mode is most beneficial when running Consul Template in a container or on a
2136scheduler like [Nomad](https://www.nomadproject.io) or Kubernetes. When
2137activated, Consul Template will spawn and manage the lifecycle of the child
2138process.
2139
2140This mode is best-explained through example. Consider a simple application that
2141reads a configuration file from disk and spawns a server from that
2142configuration.
2143
2144```sh
2145$ consul-template \
2146    -template "/tmp/config.ctmpl:/tmp/server.conf" \
2147    -exec "/bin/my-server -config /tmp/server.conf"
2148```
2149
2150When Consul Template starts, it will pull the required dependencies and populate
2151the `/tmp/server.conf`, which the `my-server` binary consumes. After that
2152template is rendered completely the first time, Consul Template spawns and
2153manages a child process. When any of the list templates change, Consul Template
2154will send a configurable reload signal to the child process. Additionally,
2155Consul Template will proxy any signals it receives to the child process. This
2156enables a scheduler to control the lifecycle of the process and also eases the
2157friction of running inside a container.
2158
2159A common point of confusion is that the command string behaves the same as the
2160shell; it does not. In the shell, when you run `foo | bar` or `foo > bar`, that
2161is actually running as a subprocess of your shell (bash, zsh, csh, etc.). When
2162Consul Template spawns the exec process, it runs outside of your shell. This
2163behavior is _different_ from when Consul Template executes the template-specific
2164reload command. If you want the ability to pipe or redirect in the exec command,
2165you will need to spawn the process in subshell, for example:
2166
2167```hcl
2168exec {
2169  command = "/bin/bash -c 'my-server > /var/log/my-server.log'"
2170}
2171```
2172
2173Note that when spawning like this, most shells do not proxy signals to their
2174child by default, so your child process will not receive the signals that Consul
2175Template sends to the shell. You can avoid this by writing a tiny shell wrapper
2176and executing that instead:
2177
2178```bash
2179#!/usr/bin/env bash
2180trap "kill -TERM $child" SIGTERM
2181
2182/bin/my-server -config /tmp/server.conf
2183child=$!
2184wait "$child"
2185```
2186
2187Alternatively, you can use your shell's exec function directly, if it exists:
2188
2189```bash
2190#!/usr/bin/env bash
2191exec /bin/my-server -config /tmp/server.conf > /var/log/my-server.log
2192```
2193
2194There are some additional caveats with Exec Mode, which should be considered
2195carefully before use:
2196
2197- If the child process dies, the Consul Template process will also die. Consul
2198  Template **does not supervise the process!** This is generally the
2199  responsibility of the scheduler or init system.
2200
2201- The child process must remain in the foreground. This is a requirement for
2202  Consul Template to manage the process and send signals.
2203
2204- The exec command will only start after _all_ templates have been rendered at
2205  least once. One may have multiple templates for a single Consul Template
2206  process, all of which must be rendered before the process starts. Consider
2207  something like an nginx or apache configuration where both the process
2208  configuration file and individual site configuration must be written in order
2209  for the service to successfully start.
2210
2211- After the child process is started, any change to any dependent template will
2212  cause the reload signal to be sent to the child process. If no reload signal
2213  is provided, Consul Template will kill the process and spawn a new instance.
2214  The reload signal can be specified and customized via the CLI or configuration
2215  file.
2216
2217- When Consul Template is stopped gracefully, it will send the configurable kill
2218  signal to the child process. The default value is SIGTERM, but it can be
2219  customized via the CLI or configuration file.
2220
2221- Consul Template will forward all signals it receives to the child process
2222  **except** its defined `reload_signal` and `kill_signal`. If you disable these
2223  signals, Consul Template will forward them to the child process.
2224
2225- It is not possible to have more than one exec command (although each template
2226  can still have its own reload command).
2227
2228- Individual template reload commands still fire independently of the exec
2229  command.
2230
2231### De-Duplication Mode
2232
2233Consul Template works by parsing templates to determine what data is needed and
2234then watching Consul for any changes to that data. This allows Consul Template
2235to efficiently re-render templates when a change occurs. However, if there are
2236many instances of Consul Template rendering a common template there is a linear
2237duplication of work as each instance is querying the same data.
2238
2239To make this pattern more efficient Consul Template supports work de-duplication
2240across instances. This can be enabled with the `-dedup` flag or via the
2241`deduplicate` configuration block. Once enabled, Consul Template uses leader
2242election on a per-template basis to have only a single node perform the queries.
2243Results are shared among other instances rendering the same template by passing
2244compressed data through the Consul K/V store.
2245
2246Please note that no Vault data will be stored in the compressed template.
2247Because ACLs around Vault are typically more closely controlled than those ACLs
2248around Consul's KV, Consul Template will still request the secret from Vault on
2249each iteration.
2250
2251When running in de-duplication mode, it is important that local template
2252functions resolve correctly. For example, you may have a local template function
2253that relies on the `env` helper like this:
2254
2255```hcl
2256{{ key (env "KEY") }}
2257```
2258
2259It is crucial that the environment variable `KEY` in this example is consistent
2260across all machines engaged in de-duplicating this template. If the values are
2261different, Consul Template will be unable to resolve the template, and you will
2262not get a successful render.
2263
2264### Termination on Error
2265
2266By default Consul Template is highly fault-tolerant. If Consul is unreachable or
2267a template changes, Consul Template will happily continue running. The only
2268exception to this rule is if the optional `command` exits non-zero. In this
2269case, Consul Template will also exit non-zero. The reason for this decision is
2270so the user can easily configure something like Upstart or God to manage Consul
2271Template as a service.
2272
2273If you want Consul Template to continue watching for changes, even if the
2274optional command argument fails, you can append `|| true` to your command. Note
2275that `||` is a "shell-ism", not a built-in function. You will also need to run
2276your command under a shell:
2277
2278```shell
2279$ consul-template \
2280  -template "in.ctmpl:out.file:/bin/bash -c 'service nginx restart || true'"
2281```
2282
2283In this example, even if the Nginx restart command returns non-zero, the overall
2284function will still return an OK exit code; Consul Template will continue to run
2285as a service. Additionally, if you have complex logic for restarting your
2286service, you can intelligently choose when you want Consul Template to exit and
2287when you want it to continue to watch for changes. For these types of complex
2288scripts, we recommend using a custom sh or bash script instead of putting the
2289logic directly in the `consul-template` command or configuration file.
2290
2291### Command Environment
2292
2293The current processes environment is used when executing commands with the following additional environment variables:
2294
2295- `CONSUL_HTTP_ADDR`
2296- `CONSUL_HTTP_TOKEN`
2297- `CONSUL_HTTP_AUTH`
2298- `CONSUL_HTTP_SSL`
2299- `CONSUL_HTTP_SSL_VERIFY`
2300
2301These environment variables are exported with their current values when the
2302command executes. Other Consul tooling reads these environment variables,
2303providing smooth integration with other Consul tools (like `consul maint` or
2304`consul lock`). Additionally, exposing these environment variables gives power
2305users the ability to further customize their command script.
2306
2307### Multi-phase Execution
2308
2309Consul Template does an n-pass evaluation of templates, accumulating
2310dependencies on each pass. This is required due to nested dependencies, such as:
2311
2312```liquid
2313{{ range services }}
2314{{ range service .Name }}
2315  {{ .Address }}
2316{{ end }}{{ end }}
2317```
2318
2319During the first pass, Consul Template does not know any of the services in
2320Consul, so it has to perform a query. When those results are returned, the
2321inner-loop is then evaluated with that result, potentially creating more queries
2322and watches.
2323
2324Because of this implementation, template functions need a default value that is
2325an acceptable parameter to a `range` function (or similar), but does not
2326actually execute the inner loop (which would cause a panic). This is important
2327to mention because complex templates **must** account for the "empty" case. For
2328example, the following **will not work**:
2329
2330```liquid
2331{{ with index (service "foo") 0 }}
2332# ...
2333{{ end }}
2334```
2335
2336This will raise an error like:
2337
2338```text
2339<index $services 0>: error calling index: index out of range: 0
2340```
2341
2342That is because, during the _first_ evaluation of the template, the `service`
2343key is returning an empty slice. You can account for this in your template like
2344so:
2345
2346```liquid
2347{{ with service "foo" }}
2348{{ with index . 0 }}
2349{{ .Node }}{{ end }}{{ end }}
2350```
2351
2352This will still add the dependency to the list of watches, but will not
2353evaluate the inner-if, avoiding the out-of-index error.
2354
2355## Running and Process Lifecycle
2356
2357While there are multiple ways to run Consul Template, the most common pattern is
2358to run Consul Template as a system service. When Consul Template first starts,
2359it reads any configuration files and templates from disk and loads them into
2360memory. From that point forward, changes to the files on disk do not propagate
2361to running process without a reload.
2362
2363The reason for this behavior is simple and aligns with other tools like haproxy.
2364A user may want to perform pre-flight validation checks on the configuration or
2365templates before loading them into the process. Additionally, a user may want to
2366update configuration and templates simultaneously. Having Consul Template
2367automatically watch and reload those files on changes is both operationally
2368dangerous and against some of the paradigms of modern infrastructure. Instead,
2369Consul Template listens for the `SIGHUP` syscall to trigger a configuration
2370reload. If you update configuration or templates, simply send `HUP` to the
2371running Consul Template process and Consul Template will reload all the
2372configurations and templates from disk.
2373
2374## Debugging
2375
2376Consul Template can print verbose debugging output. To set the log level for
2377Consul Template, use the `-log-level` flag:
2378
2379```shell
2380$ consul-template -log-level info ...
2381```
2382
2383```text
2384<timestamp> [INFO] (cli) received redis from Watcher
2385<timestamp> [INFO] (cli) invoking Runner
2386# ...
2387```
2388
2389You can also specify the level as debug:
2390
2391```shell
2392$ consul-template -log-level debug ...
2393```
2394
2395```text
2396<timestamp> [DEBUG] (cli) creating Runner
2397<timestamp> [DEBUG] (cli) creating Consul API client
2398<timestamp> [DEBUG] (cli) creating Watcher
2399<timestamp> [DEBUG] (cli) looping for data
2400<timestamp> [DEBUG] (watcher) starting watch
2401<timestamp> [DEBUG] (watcher) all pollers have started, waiting for finish
2402<timestamp> [DEBUG] (redis) starting poll
2403<timestamp> [DEBUG] (service redis) querying Consul with &{...}
2404<timestamp> [DEBUG] (service redis) Consul returned 2 services
2405<timestamp> [DEBUG] (redis) writing data to channel
2406<timestamp> [DEBUG] (redis) starting poll
2407<timestamp> [INFO] (cli) received redis from Watcher
2408<timestamp> [INFO] (cli) invoking Runner
2409<timestamp> [DEBUG] (service redis) querying Consul with &{...}
2410# ...
2411```
2412
2413
2414## FAQ
2415
2416**Q: How is this different than confd?**<br>
2417A: The answer is simple: Service Discovery as a first class citizen. You are also encouraged to read [this Pull Request](https://github.com/kelseyhightower/confd/pull/102) on the project for more background information. We think confd is a great project, but Consul Template fills a missing gap. Additionally, Consul Template has first class integration with [Vault](https://vaultproject.io), making it easy to incorporate secret material like database credentials or API tokens into configuration files.
2418
2419**Q: How is this different than Puppet/Chef/Ansible/Salt?**<br>
2420A: Configuration management tools are designed to be used in unison with Consul Template. Instead of rendering a stale configuration file, use your configuration management software to render a dynamic template that will be populated by [Consul][].
2421
2422
2423## Contributing
2424
2425To build and install Envconsul locally, you will need to [install Go][go].
2426
2427Clone the repository:
2428
2429```shell
2430$ git clone https://github.com/hashicorp/consul-template.git
2431```
2432
2433To compile the `consul-template` binary for your local machine:
2434
2435```shell
2436$ make dev
2437```
2438
2439This will compile the `consul-template` binary into `bin/consul-template` as
2440well as your `$GOPATH` and run the test suite.
2441
2442If you want to compile a specific binary, set `XC_OS` and `XC_ARCH` or run the
2443following to generate all binaries:
2444
2445```shell
2446$ make build
2447```
2448
2449If you want to run the tests, first install [consul](https://www.consul.io/docs/install/index.html) and [vault](https://www.vaultproject.io/docs/install/) locally, then:
2450
2451```shell
2452$ make test
2453```
2454
2455Or to run a specific test in the suite:
2456
2457```shell
2458go test ./... -run SomeTestFunction_name
2459```
2460
2461[consul]: https://www.consul.io "Consul by HashiCorp"
2462[examples]: (https://github.com/hashicorp/consul-template/tree/master/examples) "Consul Template Examples"
2463[hcl]: https://github.com/hashicorp/hcl "HashiCorp Configuration Language (hcl)"
2464[releases]: https://releases.hashicorp.com/consul-template "Consul Template Releases"
2465[text-template]: https://golang.org/pkg/text/template/ "Go's text/template package"
2466[vault]: https://www.vaultproject.io "Vault by HashiCorp"
2467[go]: https://golang.org "Go programming language"
2468