{"id":13459339,"url":"https://github.com/hashicorp/consul-template","last_synced_at":"2025-05-12T16:32:53.873Z","repository":{"id":21578250,"uuid":"24898177","full_name":"hashicorp/consul-template","owner":"hashicorp","description":"Template rendering, notifier, and supervisor for @HashiCorp Consul and Vault data.","archived":false,"fork":false,"pushed_at":"2025-05-05T07:08:13.000Z","size":58134,"stargazers_count":4797,"open_issues_count":208,"forks_count":783,"subscribers_count":336,"default_branch":"main","last_synced_at":"2025-05-05T14:53:55.695Z","etag":null,"topics":["consul","golang","vault"],"latest_commit_sha":null,"homepage":"https://www.hashicorp.com/","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mpl-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hashicorp.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":".github/CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2014-10-07T15:52:00.000Z","updated_at":"2025-04-29T10:56:02.000Z","dependencies_parsed_at":"2023-10-04T19:45:12.218Z","dependency_job_id":"c9adc6c3-69e0-4b0d-bba5-cf8d6a00d7c9","html_url":"https://github.com/hashicorp/consul-template","commit_stats":{"total_commits":2192,"total_committers":223,"mean_commits":9.829596412556054,"dds":0.5260036496350364,"last_synced_commit":"08826810124703e7593e825a772e92f14edc77d4"},"previous_names":[],"tags_count":90,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hashicorp%2Fconsul-template","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hashicorp%2Fconsul-template/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hashicorp%2Fconsul-template/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hashicorp%2Fconsul-template/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hashicorp","download_url":"https://codeload.github.com/hashicorp/consul-template/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253777047,"owners_count":21962621,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["consul","golang","vault"],"created_at":"2024-07-31T09:01:16.800Z","updated_at":"2025-05-12T16:32:53.848Z","avatar_url":"https://github.com/hashicorp.png","language":"Go","funding_links":[],"categories":["Go","微服务","\u003ca id=\"1d9dec1320a5d774dc8e0e7604edfcd3\"\u003e\u003c/a\u003e工具-新添加的","Projects"],"sub_categories":["docker","\u003ca id=\"8f1b9c5c2737493524809684b934d49a\"\u003e\u003c/a\u003e文章\u0026\u0026视频","Configuration Management"],"readme":"\n---\n# Consul Template\n\n[![build](https://github.com/hashicorp/consul-template/actions/workflows/build.yml/badge.svg)](https://github.com/hashicorp/consul-template/actions/workflows/build.yml)\n[![ci](https://github.com/hashicorp/consul-template/actions/workflows/ci.yml/badge.svg)](https://github.com/hashicorp/consul-template/actions/workflows/ci.yml)\n[![Go Documentation](http://img.shields.io/badge/go-documentation-%2300acd7)](https://godoc.org/github.com/hashicorp/consul-template)\n\nThis project provides a convenient way to populate values from [Consul][consul]\ninto the file system using the `consul-template` daemon.\n\nThe daemon `consul-template` queries a [Consul][consul], [Vault][vault], or [Nomad][nomad]\ncluster and updates any number of specified templates on the file system. As an\nadded bonus, it can optionally run arbitrary commands when the update process\ncompletes. Please see the [examples folder][examples] for some scenarios where\nthis functionality might prove useful.\n\n---\n\n**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.**\n\n**Please see the [Git tag](https://github.com/hashicorp/consul-template/releases) that corresponds to your version of Consul Template for the proper documentation.**\n\n---\n\n## Table of Contents\n\n- [Community Support](#community-support)\n- [Installation](#installation)\n- [Quick Example](#quick-example)\n- [Learn Guides](#learn-guides)\n- [Configuration](docs/configuration.md)\n- [Command Line Flags](docs/configuration.md#command-line-flags)\n- [Configuration File](docs/configuration.md#configuration-file)\n- [Reload Configuration and Templates](#reload-configuration-and-templates)\n- [Templating Language](docs/templating-language.md)\n  - [API Functions](docs/templating-language.md#api-functions)\n  - [Scratch](docs/templating-language.md#scratch)\n  - [Helper Functions](docs/templating-language.md#helper-functions)\n  - [Math Functions](docs/templating-language.md#math-functions)\n- [Observability](docs/observability.md)\n- [Logging](docs/observability.md#logging)\n  - [Logging to file](docs/observability.md#logging-to-file)\n- [Modes](docs/modes.md)\n- [Once Mode](docs/modes.md#once-mode)\n- [De-Duplication Mode](docs/modes.md#de-duplication-mode)\n- [Exec Mode](docs/modes.md#exec-mode)\n- [Plugins](docs/plugins.md)\n- [Caveats](#caveats)\n- [Docker Image Use](#docker-image-use)\n- [Dots in Service Names](#dots-in-service-names)\n- [Termination on Error](#termination-on-error)\n- [Commands](#commands)\n  - [Environment](#environment)\n  - [Multiple Commands](#multiple-commands)\n- [Multi-phase Execution](#multi-phase-execution)\n- [Debugging](#debugging)\n- [FAQ](#faq)\n- [Contributing](#contributing)\n\n\n## Community Support\n\nIf you have questions about how consul-template works, its capabilities or\nanything other than a bug or feature request (use github's issue tracker for\nthose), please see our community support resources.\n\nCommunity portal: https://discuss.hashicorp.com/tags/c/consul/29/consul-template\n\nOther resources: https://www.consul.io/community.html\n\nAdditionally, for issues and pull requests, we'll be using the :+1: reactions\nas a rough voting system to help gauge community priorities. So please add :+1:\nto any issue or pull request you'd like to see worked on. Thanks.\n\n\n## Installation\n\n1. Download a pre-compiled, released version from the [Consul Template releases page][releases].\n\n1. Extract the binary using `unzip` or `tar`.\n\n1. Move the binary into `$PATH`.\n\nTo compile from source, please see the instructions in the\n[contributing section](#contributing).\n\n## Quick Example\n\nThis short example assumes Consul is installed locally.\n\n1. Start a Consul cluster in dev mode:\n\n  ```shell\n  $ consul agent -dev\n  ```\n\n1. Author a template `in.tpl` to query the kv store:\n\n  ```liquid\n  {{ key \"foo\" }}\n  ```\n\n1. Start Consul Template:\n\n  ```shell\n  $ consul-template -template \"in.tpl:out.txt\" -once\n  ```\n\n1. Write data to the key in Consul:\n\n  ```shell\n  $ consul kv put foo bar\n  ```\n\n1. Observe Consul Template has written the file `out.txt`:\n\n  ```shell\n  $ cat out.txt\n  bar\n  ```\n\nFor more examples and use cases, please see the [examples folder][examples] in\nthis repository.\n\n## Learn Guides\n\nIn addition to these [examples][examples], HashiCorp has published guides and\nofficial documentation to help walk through a few common use cases for Consul\nTemplate.\n* [Consul KV](https://learn.hashicorp.com/consul/developer-configuration/consul-template#use-case-consul-kv)\n* [Consul Catalog](https://learn.hashicorp.com/consul/developer-configuration/consul-template#use-case-discover-all-services)\n* [Vault Agent Templates](https://learn.hashicorp.com/vault/identity-access-management/agent-templates)\n* [Vault Secrets](https://www.vaultproject.io/docs/agent/template#example-template)\n* [Nomad Native Service Discovery](https://learn.hashicorp.com/tutorials/nomad/schedule-edge-services)\n\n## Configuration\n\nConfiguration documentation has been moved to [docs/configuration.md](docs/configuration.md).\n\n## Reload Configuration and Templates\n\nWhile there are multiple ways to run Consul Template, the most common pattern is\nto run Consul Template as a system service. When Consul Template first starts,\nit reads any configuration files and templates from disk and loads them into\nmemory. From that point forward, changes to the files on disk do not propagate\nto running process without a reload.\n\nThe reason for this behavior is simple and aligns with other tools like haproxy.\nA user may want to perform pre-flight validation checks on the configuration or\ntemplates before loading them into the process. Additionally, a user may want to\nupdate configuration and templates simultaneously. Having Consul Template\nautomatically watch and reload those files on changes is both operationally\ndangerous and against some of the paradigms of modern infrastructure. Instead,\nConsul Template listens for the `SIGHUP` syscall to trigger a configuration\nreload. If you update configuration or templates, simply send `HUP` to the\nrunning Consul Template process and Consul Template will reload all the\nconfigurations and templates from disk.\n\n## Templating Language\n\nTemplating Language documentation has been moved to\n[docs/templating-language.md](docs/templating-language.md).\n\n## Caveats\n\n### Docker Image Use\n\nThe Alpine Docker image is configured to support an external volume to render\nshared templates to. If mounted you will need to make sure that the\nconsul-template user in the docker image has write permissions to the\ndirectory. Also if you build your own image using these you need to be sure you\nhave the permissions correct.\n\n**The consul-template user in docker has a UID of 100 and a GID of 1000.**\n\nThis effects the in image directories /consul-template/config, used to add\nconfiguration when using this as a parent image, and /consul-template/data,\nexported as a VOLUME as a location to render shared results.\n\nPreviously the image initially ran as root in order to ensure the permissions\nallowed it. But this ran against docker best practices and security policies.\n\nIf you build your own image based on ours you can override these values with\n`--build-arg` parameters.\n\n### Dots in Service Names\n\nUsing dots `.` in service names will conflict with the use of dots for [TAG\ndelineation](https://github.com/hashicorp/consul-template#service) in the\ntemplate. Dots already [interfere with using\nDNS](https://www.consul.io/docs/agent/services.html#service-and-tag-names-with-dns)\nfor service names, so we recommend avoiding dots wherever possible.\n\n### Termination on Error\n\nBy default Consul Template is highly fault-tolerant. If Consul is unreachable or\na template changes, Consul Template will happily continue running. The only\nexception to this rule is if the optional `command` exits non-zero. In this\ncase, Consul Template will also exit non-zero. The reason for this decision is\nso the user can easily configure something like Upstart or God to manage Consul\nTemplate as a service.\n\nIf you want Consul Template to continue watching for changes, even if the\noptional command argument fails, you can append `|| true` to your command. Note\nthat `||` is a \"shell-ism\", not a built-in function. You will also need to run\nyour command under a shell:\n\n```shell\n$ consul-template \\\n  -template \"in.ctmpl:out.file:/bin/bash -c 'service nginx restart || true'\"\n```\n\nIn this example, even if the Nginx restart command returns non-zero, the overall\nfunction will still return an OK exit code; Consul Template will continue to run\nas a service. Additionally, if you have complex logic for restarting your\nservice, you can intelligently choose when you want Consul Template to exit and\nwhen you want it to continue to watch for changes. For these types of complex\nscripts, we recommend using a custom sh or bash script instead of putting the\nlogic directly in the `consul-template` command or configuration file.\n\n### Commands\n\n#### Environment\n\nThe current processes environment is used when executing commands with the following additional environment variables:\n\n- `CONSUL_HTTP_ADDR`\n- `CONSUL_HTTP_TOKEN`\n- `CONSUL_HTTP_TOKEN_FILE`\n- `CONSUL_HTTP_AUTH`\n- `CONSUL_HTTP_SSL`\n- `CONSUL_HTTP_SSL_VERIFY`\n- `NOMAD_ADDR`\n- `NOMAD_NAMESPACE`\n- `NOMAD_TOKEN`\n\nThese environment variables are exported with their current values when the\ncommand executes. Other Consul tooling reads these environment variables,\nproviding smooth integration with other Consul tools (like `consul maint` or\n`consul lock`). Additionally, exposing these environment variables gives power\nusers the ability to further customize their command script.\n\n#### Multiple Commands\n\nThe command configured for running on template rendering must take one of two\nforms.\n\nThe first is as a list of the command and arguments split at spaces. The\ncommand can use an absolute path or be found on the execution environment's\nPATH and must be the first item in the list. This form allows for single or\nmulti-word commands that can be executed directly with a system call. For\nexample...\n\n`command = [\"echo\", \"hello\"]`\n`command = [\"/opt/foo-package/bin/run-foo\"]`\n`command = [\"foo\"]`\n\nNote that if you give a single command without the list denoting square\nbrackets (`[]`) it is converted into a list with a single argument.\n\nThis:\n`command = \"foo\"`\nis equivalent to:\n`command = [\"foo\"]`\n\nThe second form is as a single quoted command using system shell features. This\nform **requires** a shell named `sh` be on the executable search path (eg. PATH\non \\*nix). This is the standard on all \\*nix systems and should work out of the\nbox on those systems. This won't work on, for example, Docker images with only\nthe executable and without a minimal system like Alpine. Using this form you\ncan join multiple commands with logical operators, `\u0026\u0026` and `||`, use pipelines\nwith `|`, conditionals, etc. Note that the shell `sh` is normally `/bin/sh` on\n\\*nix systems and is either a POSIX shell or a shell run in POSIX compatible\nmode, so it is best to stick to POSIX shell syntax in this command. For\nexample..\n\n`command = \"/opt/foo \u0026\u0026 /opt/bar\"`\n\n`command = \"if /opt/foo ; then /opt/bar ; fi\"`\n\nUsing this method you can run as many shell commands as you need with whatever\nlogic you need. Though it is suggested that if it gets too long you might want\nto wrap it in a shell script, deploy and run that.\n\n#### Shell Commands and Exec Mode\n\nUsing the system shell based command has one additional caveat when used for\nthe Exec mode process (the managed, executed process to which it will propagate\nsignals). That is to get signals to work correctly means not only does anything\nthe shell runs need to handle signals, but the shell itself needs to handle\nthem. This needs to be managed by you as shells will exit upon receiving most\nsignals.\n\nA common example of this would be wanting the SIGHUP signal to trigger a reload\nof the underlying process and to be ignored by the shell process. To get this\nyou have 2 options, you can use `trap` to ignore the signal or you can use\n`exec` to replace the shell with another process.\n\nTo use `trap` to ignore the signal, you call `trap` to catch the signal in the\nshell with no action. For example if you had an underlying nginx process you\nwanted to run with a shell command and have the shell ignore it you'd do..\n\n`command = \"trap '' HUP; /usr/sbin/nginx -c /etc/nginx/nginx.conf\"`\n\nThe `trap '' HUP;` bit is enough to get the shell to ignore the HUP signal. If\nyou left off the `trap` command nginx would reload but the shell command would\nexit but leave the nginx still running, not unmanaged.\n\nAlternatively using `exec` will replace the shell's process with a sub-process,\nkeeping the same PID and process grouping (allowing the sub-process to be\nmanaged). This is simpler, but a bit less flexible than `trap`, and looks\nlike..\n\n`command = \"exec /usr/sbin/nginx -c /etc/nginx/nginx.conf\"`\n\nWhere the nginx process would replace the enclosing shell process to be managed\nby consul-template, receiving the Signals directly. Basically `exec` eliminates\nthe shell from the equation.\n\nSee your shell's documentation on `trap` and/or `exec` for more details on this.\n\n### Multi-phase Execution\n\nConsul Template does an n-pass evaluation of templates, accumulating\ndependencies on each pass. This is required due to nested dependencies, such as:\n\n```liquid\n{{ range services }}\n{{ range service .Name }}\n  {{ .Address }}\n{{ end }}{{ end }}\n```\n\nDuring the first pass, Consul Template does not know any of the services in\nConsul, so it has to perform a query. When those results are returned, the\ninner-loop is then evaluated with that result, potentially creating more queries\nand watches.\n\nBecause of this implementation, template functions need a default value that is\nan acceptable parameter to a `range` function (or similar), but does not\nactually execute the inner loop (which would cause a panic). This is important\nto mention because complex templates **must** account for the \"empty\" case. For\nexample, the following **will not work**:\n\n```liquid\n{{ with index (service \"foo\") 0 }}\n# ...\n{{ end }}\n```\n\nThis will raise an error like:\n\n```text\n\u003cindex $services 0\u003e: error calling index: index out of range: 0\n```\n\nThat is because, during the _first_ evaluation of the template, the `service`\nkey is returning an empty slice. You can account for this in your template like\nso:\n\n```liquid\n{{ with service \"foo\" }}\n{{ with index . 0 }}\n{{ .Node }}{{ end }}{{ end }}\n```\n\nThis will still add the dependency to the list of watches, but will not\nevaluate the inner-if, avoiding the out-of-index error.\n\n## Debugging\n\nConsul Template can print verbose debugging output. To set the log level for\nConsul Template, use the `-log-level` flag:\n\n```shell\n$ consul-template -log-level info ...\n```\n\n```text\n\u003ctimestamp\u003e [INFO] (cli) received redis from Watcher\n\u003ctimestamp\u003e [INFO] (cli) invoking Runner\n# ...\n```\n\nYou can also specify the level as debug:\n\n```shell\n$ consul-template -log-level debug ...\n```\n\n```text\n\u003ctimestamp\u003e [DEBUG] (cli) creating Runner\n\u003ctimestamp\u003e [DEBUG] (cli) creating Consul API client\n\u003ctimestamp\u003e [DEBUG] (cli) creating Watcher\n\u003ctimestamp\u003e [DEBUG] (cli) looping for data\n\u003ctimestamp\u003e [DEBUG] (watcher) starting watch\n\u003ctimestamp\u003e [DEBUG] (watcher) all pollers have started, waiting for finish\n\u003ctimestamp\u003e [DEBUG] (redis) starting poll\n\u003ctimestamp\u003e [DEBUG] (service redis) querying Consul with \u0026{...}\n\u003ctimestamp\u003e [DEBUG] (service redis) Consul returned 2 services\n\u003ctimestamp\u003e [DEBUG] (redis) writing data to channel\n\u003ctimestamp\u003e [DEBUG] (redis) starting poll\n\u003ctimestamp\u003e [INFO] (cli) received redis from Watcher\n\u003ctimestamp\u003e [INFO] (cli) invoking Runner\n\u003ctimestamp\u003e [DEBUG] (service redis) querying Consul with \u0026{...}\n# ...\n```\n\n## FAQ\n\n**Q: How is this different than confd?**\u003cbr\u003e\nA: 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][vault], making it easy to incorporate secret material like database credentials or API tokens into configuration files.\n\n**Q: How is this different than Puppet/Chef/Ansible/Salt?**\u003cbr\u003e\nA: 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][consul].\n\n\n**Q: How does compatibility with Consul look like?**\u003cbr\u003e\nA: The following table shows the compatibility of Consul Template with Consul versions:\n|               | Consul v1.16  | Consul v1.17  | Consul v1.18  | Consul v1.16+ent  | Consul v1.17+ent  |\n| ------------- | ------------- | ------------- | ------------- | ----------------- | ----------------- |\n| CT v0.37      | ✅            | ✅            | ✅            | ✅                | ✅                |\n| CT v0.36      | ✅            | ✅            | ✅            | N/A               | N/A               |\n| CT v0.35      | ✅            | ✅            | ✅            | N/A               | N/A               |\n| CT v0.34      | ✅            | ✅            | ✅            | N/A               | N/A               |\n\nN/A = ENT tests were not supported before this version\n\n\n## Contributing\n\nTo build and install Consul-Template locally, you will need to [install Go][go].\n\nClone the repository:\n\n```shell\n$ git clone https://github.com/hashicorp/consul-template.git\n```\n\nTo compile the `consul-template` binary for your local machine:\n\n```shell\n$ make dev\n```\n\nThis will compile the `consul-template` binary into `bin/consul-template` as\nwell as your `$GOPATH` and run the test suite.\n\nIf you want to run the tests, first install [consul](https://www.consul.io/docs/install/index.html), [nomad](https://learn.hashicorp.com/tutorials/nomad/get-started-install) and [vault](https://www.vaultproject.io/docs/install/) locally, then:\n\n```shell\n$ make test\n```\n\nOr to run a specific test in the suite:\n\n```shell\ngo test ./... -run SomeTestFunction_name\n```\n\n[consul]: https://www.consul.io \"Consul by HashiCorp\"\n[connect]: https://www.consul.io/docs/connect/ \"Connect\"\n[examples]: (https://github.com/hashicorp/consul-template/tree/main/examples) \"Consul Template Examples\"\n[releases]: https://releases.hashicorp.com/consul-template \"Consul Template Releases\"\n[vault]: https://www.vaultproject.io \"Vault by HashiCorp\"\n[go]: https://golang.org \"Go programming language\"\n[nomad]: https://www.nomadproject.io \"Nomad By HashiCorp\"\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhashicorp%2Fconsul-template","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhashicorp%2Fconsul-template","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhashicorp%2Fconsul-template/lists"}