• Stars
    star
    4,750
  • Rank 8,898 (Top 0.2 %)
  • Language
    Go
  • License
    Mozilla Public Li...
  • Created about 10 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Template rendering, notifier, and supervisor for @HashiCorp Consul and Vault data.

Consul Template

build ci Go Documentation

This project provides a convenient way to populate values from Consul into the file system using the consul-template daemon.

The daemon consul-template queries a Consul, Vault, or Nomad cluster and updates any number of specified templates on the file system. As an added bonus, it can optionally run arbitrary commands when the update process completes. Please see the examples folder for some scenarios where this functionality might prove useful.


The documentation in this README corresponds to the main branch of Consul Template. It may contain unreleased features or different APIs than the most recently released version.

Please see the Git tag that corresponds to your version of Consul Template for the proper documentation.


Table of Contents

Community Support

If you have questions about how consul-template works, its capabilities or anything other than a bug or feature request (use github's issue tracker for those), please see our community support resources.

Community portal: https://discuss.hashicorp.com/tags/c/consul/29/consul-template

Other resources: https://www.consul.io/community.html

Additionally, for issues and pull requests, we'll be using the 👍 reactions as a rough voting system to help gauge community priorities. So please add 👍 to any issue or pull request you'd like to see worked on. Thanks.

Installation

  1. Download a pre-compiled, released version from the Consul Template releases page.

  2. Extract the binary using unzip or tar.

  3. Move the binary into $PATH.

To compile from source, please see the instructions in the contributing section.

Quick Example

This short example assumes Consul is installed locally.

  1. Start a Consul cluster in dev mode:
$ consul agent -dev
  1. Author a template in.tpl to query the kv store:
{{ key "foo" }}
  1. Start Consul Template:
$ consul-template -template "in.tpl:out.txt" -once
  1. Write data to the key in Consul:
$ consul kv put foo bar
  1. Observe Consul Template has written the file out.txt:
$ cat out.txt
bar

For more examples and use cases, please see the examples folder in this repository.

Learn Guides

In addition to these examples, HashiCorp has published guides and official documentation to help walk through a few common use cases for Consul Template.

Configuration

Configuration documentation has been moved to docs/configuration.md.

Reload Configuration and Templates

While there are multiple ways to run Consul Template, the most common pattern is to run Consul Template as a system service. When Consul Template first starts, it reads any configuration files and templates from disk and loads them into memory. From that point forward, changes to the files on disk do not propagate to running process without a reload.

The reason for this behavior is simple and aligns with other tools like haproxy. A user may want to perform pre-flight validation checks on the configuration or templates before loading them into the process. Additionally, a user may want to update configuration and templates simultaneously. Having Consul Template automatically watch and reload those files on changes is both operationally dangerous and against some of the paradigms of modern infrastructure. Instead, Consul Template listens for the SIGHUP syscall to trigger a configuration reload. If you update configuration or templates, simply send HUP to the running Consul Template process and Consul Template will reload all the configurations and templates from disk.

Templating Language

Templating Language documentation has been moved to docs/templating-language.md.

Caveats

Docker Image Use

The Alpine Docker image is configured to support an external volume to render shared templates to. If mounted you will need to make sure that the consul-template user in the docker image has write permissions to the directory. Also if you build your own image using these you need to be sure you have the permissions correct.

The consul-template user in docker has a UID of 100 and a GID of 1000.

This effects the in image directories /consul-template/config, used to add configuration when using this as a parent image, and /consul-template/data, exported as a VOLUME as a location to render shared results.

Previously the image initially ran as root in order to ensure the permissions allowed it. But this ran against docker best practices and security policies.

If you build your own image based on ours you can override these values with --build-arg parameters.

Dots in Service Names

Using dots . in service names will conflict with the use of dots for TAG delineation in the template. Dots already interfere with using DNS for service names, so we recommend avoiding dots wherever possible.

Termination on Error

By default Consul Template is highly fault-tolerant. If Consul is unreachable or a template changes, Consul Template will happily continue running. The only exception to this rule is if the optional command exits non-zero. In this case, Consul Template will also exit non-zero. The reason for this decision is so the user can easily configure something like Upstart or God to manage Consul Template as a service.

If you want Consul Template to continue watching for changes, even if the optional command argument fails, you can append || true to your command. Note that || is a "shell-ism", not a built-in function. You will also need to run your command under a shell:

$ consul-template \
  -template "in.ctmpl:out.file:/bin/bash -c 'service nginx restart || true'"

In this example, even if the Nginx restart command returns non-zero, the overall function will still return an OK exit code; Consul Template will continue to run as a service. Additionally, if you have complex logic for restarting your service, you can intelligently choose when you want Consul Template to exit and when you want it to continue to watch for changes. For these types of complex scripts, we recommend using a custom sh or bash script instead of putting the logic directly in the consul-template command or configuration file.

Commands

Environment

The current processes environment is used when executing commands with the following additional environment variables:

  • CONSUL_HTTP_ADDR
  • CONSUL_HTTP_TOKEN
  • CONSUL_HTTP_TOKEN_FILE
  • CONSUL_HTTP_AUTH
  • CONSUL_HTTP_SSL
  • CONSUL_HTTP_SSL_VERIFY
  • NOMAD_ADDR
  • NOMAD_NAMESPACE
  • NOMAD_TOKEN

These environment variables are exported with their current values when the command executes. Other Consul tooling reads these environment variables, providing smooth integration with other Consul tools (like consul maint or consul lock). Additionally, exposing these environment variables gives power users the ability to further customize their command script.

Multiple Commands

The command configured for running on template rendering must take one of two forms.

The first is as a list of the command and arguments split at spaces. The command can use an absolute path or be found on the execution environment's PATH and must be the first item in the list. This form allows for single or multi-word commands that can be executed directly with a system call. For example...

command = ["echo", "hello"] command = ["/opt/foo-package/bin/run-foo"] command = ["foo"]

Note that if you give a single command without the list denoting square brackets ([]) it is converted into a list with a single argument.

This: command = "foo" is equivalent to: command = ["foo"]

The second form is as a single quoted command using system shell features. This form requires a shell named sh be on the executable search path (eg. PATH on *nix). This is the standard on all *nix systems and should work out of the box on those systems. This won't work on, for example, Docker images with only the executable and without a minimal system like Alpine. Using this form you can join multiple commands with logical operators, && and ||, use pipelines with |, conditionals, etc. Note that the shell sh is normally /bin/sh on *nix systems and is either a POSIX shell or a shell run in POSIX compatible mode, so it is best to stick to POSIX shell syntax in this command. For example..

command = "/opt/foo && /opt/bar"

command = "if /opt/foo ; then /opt/bar ; fi"

Using this method you can run as many shell commands as you need with whatever logic you need. Though it is suggested that if it gets too long you might want to wrap it in a shell script, deploy and run that.

Shell Commands and Exec Mode

Using the system shell based command has one additional caveat when used for the Exec mode process (the managed, executed process to which it will propagate signals). That is to get signals to work correctly means not only does anything the shell runs need to handle signals, but the shell itself needs to handle them. This needs to be managed by you as shells will exit upon receiving most signals.

A common example of this would be wanting the SIGHUP signal to trigger a reload of the underlying process and to be ignored by the shell process. To get this you have 2 options, you can use trap to ignore the signal or you can use exec to replace the shell with another process.

To use trap to ignore the signal, you call trap to catch the signal in the shell with no action. For example if you had an underlying nginx process you wanted to run with a shell command and have the shell ignore it you'd do..

command = "trap '' HUP; /usr/sbin/nginx -c /etc/nginx/nginx.conf"

The trap '' HUP; bit is enough to get the shell to ignore the HUP signal. If you left off the trap command nginx would reload but the shell command would exit but leave the nginx still running, not unmanaged.

Alternatively using exec will replace the shell's process with a sub-process, keeping the same PID and process grouping (allowing the sub-process to be managed). This is simpler, but a bit less flexible than trap, and looks like..

command = "exec /usr/sbin/nginx -c /etc/nginx/nginx.conf"

Where the nginx process would replace the enclosing shell process to be managed by consul-template, receiving the Signals directly. Basically exec eliminates the shell from the equation.

See your shell's documentation on trap and/or exec for more details on this.

Multi-phase Execution

Consul Template does an n-pass evaluation of templates, accumulating dependencies on each pass. This is required due to nested dependencies, such as:

{{ range services }}
{{ range service .Name }}
  {{ .Address }}
{{ end }}{{ end }}

During the first pass, Consul Template does not know any of the services in Consul, so it has to perform a query. When those results are returned, the inner-loop is then evaluated with that result, potentially creating more queries and watches.

Because of this implementation, template functions need a default value that is an acceptable parameter to a range function (or similar), but does not actually execute the inner loop (which would cause a panic). This is important to mention because complex templates must account for the "empty" case. For example, the following will not work:

{{ with index (service "foo") 0 }}
# ...
{{ end }}

This will raise an error like:

<index $services 0>: error calling index: index out of range: 0

That is because, during the first evaluation of the template, the service key is returning an empty slice. You can account for this in your template like so:

{{ with service "foo" }}
{{ with index . 0 }}
{{ .Node }}{{ end }}{{ end }}

This will still add the dependency to the list of watches, but will not evaluate the inner-if, avoiding the out-of-index error.

Debugging

Consul Template can print verbose debugging output. To set the log level for Consul Template, use the -log-level flag:

$ consul-template -log-level info ...
<timestamp> [INFO] (cli) received redis from Watcher
<timestamp> [INFO] (cli) invoking Runner
# ...

You can also specify the level as debug:

$ consul-template -log-level debug ...
<timestamp> [DEBUG] (cli) creating Runner
<timestamp> [DEBUG] (cli) creating Consul API client
<timestamp> [DEBUG] (cli) creating Watcher
<timestamp> [DEBUG] (cli) looping for data
<timestamp> [DEBUG] (watcher) starting watch
<timestamp> [DEBUG] (watcher) all pollers have started, waiting for finish
<timestamp> [DEBUG] (redis) starting poll
<timestamp> [DEBUG] (service redis) querying Consul with &{...}
<timestamp> [DEBUG] (service redis) Consul returned 2 services
<timestamp> [DEBUG] (redis) writing data to channel
<timestamp> [DEBUG] (redis) starting poll
<timestamp> [INFO] (cli) received redis from Watcher
<timestamp> [INFO] (cli) invoking Runner
<timestamp> [DEBUG] (service redis) querying Consul with &{...}
# ...

FAQ

Q: How is this different than confd?
A: The answer is simple: Service Discovery as a first class citizen. You are also encouraged to read this Pull Request 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, making it easy to incorporate secret material like database credentials or API tokens into configuration files.

Q: How is this different than Puppet/Chef/Ansible/Salt?
A: 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.

Contributing

To build and install Consul-Template locally, you will need to install Go.

Clone the repository:

$ git clone https://github.com/hashicorp/consul-template.git

To compile the consul-template binary for your local machine:

$ make dev

This will compile the consul-template binary into bin/consul-template as well as your $GOPATH and run the test suite.

If you want to compile a specific binary, set XC_OS and XC_ARCH or run the following to generate all binaries:

$ make build

If you want to run the tests, first install consul, nomad and vault locally, then:

$ make test

Or to run a specific test in the suite:

go test ./... -run SomeTestFunction_name

More Repositories

1

terraform

Terraform enables you to safely and predictably create, change, and improve infrastructure. It is a source-available tool that codifies APIs into declarative configuration files that can be shared amongst team members, treated as code, edited, reviewed, and versioned.
Go
42,550
star
2

vault

A tool for secrets management, encryption as a service, and privileged access management
Go
30,858
star
3

consul

Consul is a distributed, highly available, and data center aware solution to connect and configure applications across dynamic, distributed infrastructure.
Go
28,256
star
4

vagrant

Vagrant is a tool for building and distributing development environments.
Ruby
26,132
star
5

packer

Packer is a tool for creating identical machine images for multiple platforms from a single source configuration.
Go
15,086
star
6

nomad

Nomad is an easy-to-use, flexible, and performant workload orchestrator that can deploy a mix of microservice, batch, containerized, and non-containerized applications. Nomad is easy to operate and scale and has native Consul and Vault integrations.
Go
14,809
star
7

terraform-provider-aws

The AWS Provider enables Terraform to manage AWS resources.
Go
9,761
star
8

raft

Golang implementation of the Raft consensus protocol
Go
7,383
star
9

serf

Service orchestration and management tool.
Go
5,692
star
10

hcl

HCL is the HashiCorp configuration language.
Go
5,236
star
11

go-plugin

Golang plugin system over RPC.
Go
4,874
star
12

terraform-cdk

Define infrastructure resources using programming constructs and provision them using HashiCorp Terraform
TypeScript
4,868
star
13

waypoint

A tool to build, deploy, and release any application on any platform.
Go
4,789
star
14

terraform-provider-azurerm

Terraform provider for Azure Resource Manager
Go
4,528
star
15

otto

Development and deployment made easy.
HTML
4,282
star
16

golang-lru

Golang LRU cache
Go
4,221
star
17

boundary

Boundary enables identity-based access management for dynamic infrastructure.
Go
3,847
star
18

memberlist

Golang package for gossip based membership and failure detection
Go
3,303
star
19

go-memdb

Golang in-memory database built on immutable radix trees
Go
2,937
star
20

next-mdx-remote

Load mdx content from anywhere through getStaticProps in next.js
TypeScript
2,405
star
21

terraform-provider-google

Terraform Provider for Google Cloud Platform
Go
2,325
star
22

go-multierror

A Go (golang) package for representing a list of errors as a single error.
Go
2,029
star
23

yamux

Golang connection multiplexing library
Go
2,003
star
24

envconsul

Launch a subprocess with environment variables using data from @HashiCorp Consul and Vault.
Go
1,967
star
25

go-retryablehttp

Retryable HTTP client in Go
Go
1,702
star
26

terraform-provider-kubernetes

Terraform Kubernetes provider
Go
1,580
star
27

go-getter

Package for downloading things from a string URL using a variety of protocols.
Go
1,541
star
28

best-practices

HCL
1,490
star
29

go-version

A Go (golang) library for parsing and verifying versions and version constraints.
Go
1,459
star
30

go-metrics

A Golang library for exporting performance and runtime metrics to external metrics systems (i.e. statsite, statsd)
Go
1,453
star
31

setup-terraform

Sets up Terraform CLI in your GitHub Actions workflow.
JavaScript
1,352
star
32

terraform-guides

Example usage of HashiCorp Terraform
HCL
1,324
star
33

mdns

Simple mDNS client/server library in Golang
Go
1,020
star
34

terraform-provider-helm

Terraform Helm provider
Go
997
star
35

vault-guides

Example usage of HashiCorp Vault secrets management
Shell
990
star
36

go-immutable-radix

An immutable radix tree implementation in Golang
Go
926
star
37

vault-helm

Helm chart to install Vault and other associated components.
Shell
904
star
38

terraform-ls

Terraform Language Server
Go
896
star
39

vscode-terraform

HashiCorp Terraform VSCode extension
TypeScript
870
star
40

levant

An open source templating and deployment tool for HashiCorp Nomad jobs
Go
825
star
41

vault-k8s

First-class support for Vault and Kubernetes.
Go
697
star
42

terraform-exec

Terraform CLI commands via Go.
Go
675
star
43

consul-k8s

First-class support for Consul Service Mesh on Kubernetes
Go
665
star
44

terraform-aws-vault

A Terraform Module for how to run Vault on AWS using Terraform and Packer
HCL
659
star
45

terraform-github-actions

Terraform GitHub Actions
Shell
624
star
46

terraform-provider-vsphere

Terraform Provider for VMware vSphere
Go
617
star
47

raft-boltdb

Raft backend implementation using BoltDB
Go
585
star
48

nextjs-bundle-analysis

A github action that provides detailed bundle analysis on PRs for next.js apps
JavaScript
562
star
49

go-discover

Discover nodes in cloud environments
Go
562
star
50

consul-replicate

Consul cross-DC KV replication daemon.
Go
504
star
51

next-mdx-enhanced

A Next.js plugin that enables MDX pages, layouts, and front matter
JavaScript
500
star
52

docker-vault

Official Docker images for Vault
Shell
492
star
53

terraform-provider-kubernetes-alpha

A Terraform provider for Kubernetes that uses dynamic resource types and server-side apply. Supports all Kubernetes resources.
Go
490
star
54

vault-secrets-operator

The Vault Secrets Operator (VSO) allows Pods to consume Vault secrets natively from Kubernetes Secrets.
Go
466
star
55

terraform-k8s

Terraform Cloud Operator for Kubernetes
Go
454
star
56

puppet-bootstrap

A collection of single-file scripts to bootstrap your machines with Puppet.
Shell
444
star
57

cap

A collection of authentication Go packages related to OIDC, JWKs, Distributed Claims, LDAP
Go
436
star
58

terraform-provider-vault

Terraform Vault provider
Go
431
star
59

damon

A terminal UI (TUI) for HashiCorp Nomad
Go
427
star
60

nomad-autoscaler

Nomad Autoscaler brings autoscaling to your Nomad workloads.
Go
424
star
61

consul-helm

Helm chart to install Consul and other associated components.
Shell
422
star
62

terraform-provider-azuread

Terraform provider for Azure Active Directory
Go
419
star
63

vault-ssh-helper

Vault SSH Agent is used to enable one time keys and passwords
Go
404
star
64

terraform-provider-scaffolding

Quick start repository for creating a Terraform provider
Go
402
star
65

terraform-aws-consul

A Terraform Module for how to run Consul on AWS using Terraform and Packer
HCL
401
star
66

docker-consul

Official Docker images for Consul.
Dockerfile
399
star
67

nomad-pack

Go
393
star
68

hil

HIL is a small embedded language for string interpolations.
Go
392
star
69

vault-action

A GitHub Action that simplifies using HashiCorp Vault™ secrets as build variables.
JavaScript
391
star
70

learn-terraform-provision-eks-cluster

HCL
389
star
71

terraform-plugin-sdk

Terraform Plugin SDK enables building plugins (providers) to manage any service providers or custom in-house solutions
Go
383
star
72

terraform-config-inspect

A helper library for shallow inspection of Terraform configurations
Go
380
star
73

hcl2

Former temporary home for experimental new version of HCL
Go
375
star
74

errwrap

Errwrap is a Go (golang) library for wrapping and querying errors.
Go
373
star
75

go-cleanhttp

Go
366
star
76

design-system

Helios Design System
TypeScript
358
star
77

logutils

Utilities for slightly better logging in Go (Golang).
Go
356
star
78

vault-ruby

The official Ruby client for HashiCorp's Vault
Ruby
336
star
79

vault-rails

A Rails plugin for easily integrating Vault secrets
Ruby
334
star
80

next-remote-watch

Decorated local server for next.js that enables reloads from remote data changes
JavaScript
325
star
81

waypoint-examples

Example Apps that can be deployed with Waypoint
PHP
325
star
82

go-hclog

A common logging package for HashiCorp tools
Go
319
star
83

vault-csi-provider

HashiCorp Vault Provider for Secret Store CSI Driver
Go
308
star
84

nomad-guides

Example usage of HashiCorp Nomad
HCL
281
star
85

consul-haproxy

Consul HAProxy connector for real-time configuration
Go
279
star
86

terraform-provider-google-beta

Terraform Provider for Google Cloud Platform (Beta)
Go
265
star
87

consul-esm

External service monitoring for Consul
Go
262
star
88

http-echo

A tiny go web server that echos what you start it with!
Makefile
257
star
89

terraform-provider-awscc

Terraform AWS Cloud Control provider
HCL
256
star
90

terraform-aws-nomad

A Terraform Module for how to run Nomad on AWS using Terraform and Packer
HCL
254
star
91

faas-nomad

OpenFaaS plugin for Nomad
Go
252
star
92

go-sockaddr

IP Address/UNIX Socket convenience functions for Go
Go
250
star
93

terraform-foundational-policies-library

Sentinel is a language and framework for policy built to be embedded in existing software to enable fine-grained, logic-based policy decisions. This repository contains a library of Sentinel policies, developed by HashiCorp, that can be consumed directly within the Terraform Cloud platform.
HCL
233
star
94

nomad-driver-podman

A nomad task driver plugin for sandboxing workloads in podman containers
Go
226
star
95

vagrant-vmware-desktop

Official provider for VMware desktop products: Fusion, Player, and Workstation.
Go
225
star
96

go-tfe

HCP Terraform/Enterprise API Client/SDK in Golang
Go
224
star
97

nomad-pack-community-registry

A repo for Packs written and maintained by Nomad community members
HCL
215
star
98

boundary-reference-architecture

Example reference architecture for a high availability Boundary deployment on AWS.
HCL
211
star
99

terraform-plugin-framework

A next-generation framework for building Terraform providers.
Go
204
star
100

vault-plugin-auth-kubernetes

Vault authentication plugin for Kubernetes Service Accounts
Go
192
star