HashiCorp Certified: Consul Associate Certification

Access the Consul KeyValue KV

Using consul template

Consul Template is a HashiCorp tool designed to render configuration files dynamically using data from a Consul cluster. Running as a standalone daemon alongside a Consul agent, it continuously watches key/value entries and regenerates files when values change. This ensures seamless configuration updates without manual restarts.

Workflow

  1. Define a template file with placeholders (e.g., app.ctmpl).
  2. Start the Consul agent on your server:
    consul agent -config-dir=/etc/consul.d
    
  3. Launch the consul-template process, specifying the template and target:
    consul-template \
      -template "/etc/templates/app.ctmpl:/etc/app/config.yaml" \
      -config /etc/consul-template/config.hcl
    
  4. The daemon retrieves key/value pairs from Consul.
  5. Placeholders in the template are replaced with live data.
  6. The rendered file is saved to disk.
  7. An optional command (like a service reload) is executed to apply updates.

Note

By default, Consul Template polls Consul every two seconds. Adjust the interval with the -wait flag or in HCL.

The image is a flowchart explaining the process of using a consul-template, starting from a VM launch, executing the consul-template, creating a config file, and launching an application, with interactions with a Consul Cluster.

Key Benefits

BenefitDescription
Dynamic UpdatesAutomatically re-renders files when Consul KV entries change.
Automatic ReloadsExecutes custom commands (e.g., systemctl reload) on changes.
Powerful TemplatingLeverages Go templates with conditionals, loops, and functions.

Example HCL Configuration

Create /etc/consul-template/config.hcl:

template {
  source      = "/etc/templates/app.ctmpl"
  destination = "/etc/app/config.yaml"
  command     = "systemctl reload my-app.service"
  left_delimiter  = "{{"
  right_delimiter = "}}"
}

Run the daemon:

consul-template -config /etc/consul-template/config.hcl

Warning

Ensure the Consul agent is running and reachable. When ACLs are enabled, include the token parameter in your HCL or CLI invocation.

Watch Video

Watch video content

Previous
Demo Using Envconsul to monitor Changes to Consul KV