vault Use static secret caching with Vault Proxy to cache key value data in Vault Improve Vault traffic resiliency with Vault Proxy page title Improve Vault traffic resiliency layout docs handle updates and reduce direct requests to Vault from clients

Answer:
---
layout: docs
page_title: Improve Vault traffic resiliency
description: >-
  Use static secret caching with Vault Proxy to cache key/value data in Vault,
  handle updates, and reduce direct requests to Vault from clients.
---

# Improve Vault traffic resiliency with Vault Proxy

@include 'alerts/enterprise-only.mdx'

Use static secret caching with Vault Proxy to cache KVv1 and KVv2 secrets to
minimize requests made to Vault and provide resilient connections for clients.

Vault Proxy utilizes the Enterprise only [Vault event notification system](/vault/docs/concepts/events)
feature for cache freshness. As a result, static secret caching can only be used
with Vault Enterprise installations.

When using a Vault cluster with performance standbys, Proxy may receive secret update events
before the secret update has been fully replicated. To make sure that Proxy can get updated
secret values after receiving an event notification, Proxy must be configured to point to the
address of the active node in its [Vault stanza](/vault/docs/agent-and-proxy/proxy#vault-stanza),
or [allow_forwarding_via_header must be set to true](/vault/docs/configuration/replication#allow_forwarding_via_header)
on the cluster. When `allow_forwarding_via_header` is configured, Proxy will only forward
requests to update a secret in its cache after receiving an event indicating that secret got updated.
This approach would be recommended if access to Vault was behind, for example, a load balancer.

## Step 1: Subscribe Vault Proxy to KV events

Vault Proxy uses Vault events and auto-auth to monitor secret status and make
appropriate cache updates.
1. Enable [auto-auth](/vault/docs/agent-and-proxy/autoauth).
1. Create an auto-auth token with permission to subscribe to KV event updates
with the [Vault event notification system](/vault/docs/concepts/events). For
example, to create a policy that grants access to static secret (KVv1 and KVv2)
events, you need permission to subscribe to the `events` endpoint, as well as
the `list` and `subscribe` permissions on KV secrets you want to get secrets
from:
 ```hcl
  path "sys/events/subscribe/kv*" {
    capabilities = ["read"]
  }

  path "*" {
    capabilities = ["list", "subscribe"]
    subscribe_event_types = ["kv*"]
  }
   ```

Subscribing to KV events means that Proxy receives updates as soon as a secret
changes, which reduces staleness in the cache. Vault Proxy only checks for a
secret update if an event notification indicates that the related secret was
updated.

## Step 2: Ensure tokens have `capabilities-self` access

Tokens require `update` access to the
[`sys/capabilies-self`](/vault/api-docs/system/capabilities-self) endpoint to
request cached secrets. Vault tokens receive `update` permissions
[by default](/vault/docs/concepts/policies#default-policy). If you have modified
or removed the default policy, you must explicitly create a policy with the
appropriate permissions. For example:
```hcl
  path "sys/capabilities-self" {
    capabilities = ["update"]
  }
```

## Step 3: Configure an appropriate refresh interval
By default, Vault Proxy refreshes tokens every five minutes. You can change the
default behavior and configure Proxy to verify and update cached token
capabilities with the `static_secret_token_capability_refresh_interval`
parameter in the `cache` configuration stanza. For example, to set a refresh
interval of one minute:
```hcl
cache {
  cache_static_secrets = true
  static_secret_token_capability_refresh_interval = "1m"
}
```

## Functionality

With static secret caching, Vault Proxy caches `GET` requests for KVv1 and KVv2
endpoints.

When a client sends a `GET` request for a new KV secret, Proxy forwards the
request to Vault but caches the response before forwarding it to the client. If
that client makes subsequent `GET` requests for the same secret, Vault Proxy
serves the cached response rather than forwarding the request to Vault.

<Tip title="'Offline' Secret Access and CLI KV Get">

  Vault Proxy does not cache any non-KV API responses. While KV secrets can be retrieved even if
  Vault is unavailable, other requests cannot be served. As a result, using the `vault kv`
  CLI command, which sends a request to `/sys/internal/ui/mounts` before the KV `GET` request,
  will require a real request to Vault and cannot be served entirely from the cache or
  when Vault is unavailable (you can use `vault read` instead).

</Tip>

Similarly, when a token requests access to a KV secret, it must complete a
success `GET` request. If the request is successful, Proxy caches the fact that
the token was successful in addition to the result. Subsequent requests by the
same token can then access this secret from the cache instead of Vault.

Vault Proxy uses the [event notification system](/vault/docs/concepts/events) to keep the
cache up to date. It monitors the KV event feed for events related to any secret
currently stored in the cache, including modification events like updates and
deletes. When Proxy detects a change in a cached secret, it will update or
evict the cache entry as appropriate.

Vault Proxy also checks and refreshes the access permissions of known tokens
according to the window set with `static_secret_token_capability_refresh_interval`.
By default, the refresh interval is five minutes.

Every interval, Proxy calls [`sys/capabilies-self`](/vault/api-docs/system/capabilities-self) on
behalf of every token in the cache to confirm the token still has permission to
access the cached secret. If the result from Vault indicates that permission (or
the token itself) was revoked, Proxy updates the cache entry so that the affected
token can no longer access the relevant paths from the cache. The refresh interval
is essentially the maximum period after which permission to read a KV secret is
fully revoked for the relevant token.

If the capabilities have been removed, or Proxy receives a `403` response, the
capability is removed from the token, and that token cannot be used to access the
cache. For other kinds of errors, such as Vault being unreachable or sealed,
the `static_secret_token_capability_refresh_behavior` config is consulted.
If set to `optimistic` (the default), the capability will not be removed unless we
receive a `403` or valid response without the capability. If set to `pessimistic`,
the capability will be removed for any error, such as would occur if Vault is sealed.

For token refresh to work, any token that will access the cache also needs
`update` permission for [`sys/capabilies-self`](/vault/api-docs/system/capabilities-self).
Having `update` permission for the token lets Proxy test capabilities for the
token against multiple paths with a single request instead of testing for a `403`
response for each path explicitly.

<Tip title="Refresh is per token, not per secret">

  If Proxy's API proxy is configured to use auto-authentication for tokens, and **all**
  requests that pass through Vault Proxy use the same token, Proxy only
  makes a single request to Vault every refresh interval, no matter how many
  secrets are currently cached.

</Tip>

When static secret caching is enabled, Proxy returns `HIT` or `MISS` in the `X-Cache`
response header for requests so client can tell if the response was served from
the cache or forwarded from Vault. In the event of a hit, Proxy also sets the
`Age` header to indicate, in seconds, how old the cache entry is.

<Tip title="Old does not mean stale">

  The fact that a cache entry is old, does not necessarily mean that the
  information is out of date. Vault Proxy continually monitors KV events for
  updates. A large value for `Age` may simply mean that the secret has not been
  rotated recently.

</Tip>

## Configuration

The top level `cache` block has the following configuration entries relating to static secret caching:

- `cache_static_secrets` `(bool: false)` - Enables static secret caching when
set to `true`. When `cache_static_secrets` and `auto_auth` are both enabled,
Vault Proxy serves KV secrets directly from the cache to clients with
sufficient permission.

- `static_secret_token_capability_refresh_interval` `(duration: "5m", optional)` -
Sets the interval as a [duration format string](/vault/docs/concepts/duration-format)
at which Vault Proxy rechecks the permissions of tokens used to access cached
secrets. The refresh interval is the maximum period after which permission to
read a cached KV secret is fully revoked. Ignored when `cache_static_secrets`
is `false`.

- `static_secret_token_capability_refresh_behavior` `(string: "optimistic", optional)` -
Sets the capability refresh behavior in the case of an error when attempting to
refresh capabilities. In the case of a `403`, capabilities will be removed for the token
with either option. In case of other errors, such as Vault being sealed or Vault being
unavailable, this setting controls the behavior. If set to `optimistic` (the default),
capabilities will be removed for only `403` errors. If set to `pessimistic`, capabilities
will be removed for any error. This essentially allows configuring a preference between
favoring availability (`optimistic`) or access fidelity (`pessimistic`) of cached
static secrets. Ignored when `cache_static_secrets` is `false`.

### Example configuration

The following example Vault Proxy configuration:
- Defines a TCP listener (`listener`) with TLS disabled.
- Forces clients using API proxy (`api_proxy`) to identify with an auto-auth token.
- Configures auto-authentication (`auto-auth`) for `approle`.
- Enables static secret caching with `cache_static_secrets`.
- Sets an explicit token capability refresh window of 1 hour with `static_secret_token_capability_refresh_interval`.

```hcl
# Other Vault Proxy configuration blocks
# ...

cache {
  cache_static_secrets = true
  static_secret_token_capability_refresh_interval = "1h"
}

api_proxy {
  use_auto_auth_token = "force"
}

listener "tcp" {
    address = "127.0.0.1:8100"
    tls_disable = true
}

auto_auth {
  method {
    type = "approle"
    config = {
      role_id_file_path = "roleid"
      secret_id_file_path = "secretid"
      remove_secret_id_file_after_reading = false
    }
  }
```
[event-system]: /vault/docs/concepts/events

layout  docs page title  Improve Vault traffic resiliency description       Use static secret caching with Vault Proxy to cache key value data in Vault    handle updates  and reduce direct requests to Vault from clients         Improve Vault traffic resiliency with Vault Proxy   include  alerts enterprise only mdx   Use static secret caching with Vault Proxy to cache KVv1 and KVv2 secrets to minimize requests made to Vault and provide resilient connections for clients   Vault Proxy utilizes the Enterprise only  Vault event notification system   vault docs concepts events  feature for cache freshness  As a result  static secret caching can only be used with Vault Enterprise installations   When using a Vault cluster with performance standbys  Proxy may receive secret update events before the secret update has been fully replicated  To make sure that Proxy can get updated secret values after receiving an event notification  Proxy must be configured to point to the address of the active node in its  Vault stanza   vault docs agent and proxy proxy vault stanza   or  allow forwarding via header must be set to true   vault docs configuration replication allow forwarding via header  on the cluster  When  allow forwarding via header  is configured  Proxy will only forward requests to update a secret in its cache after receiving an event indicating that secret got updated  This approach would be recommended if access to Vault was behind  for example  a load balancer      Step 1  Subscribe Vault Proxy to KV events  Vault Proxy uses Vault events and auto auth to monitor secret status and make appropriate cache updates  1  Enable  auto auth   vault docs agent and proxy autoauth   1  Create an auto auth token with permission to subscribe to KV event updates with the  Vault event notification system   vault docs concepts events   For example  to create a policy that grants access to static secret  KVv1 and KVv2  events  you need permission to subscribe to the  events  endpoint  as well as the  list  and  subscribe  permissions on KV secrets you want to get secrets from      hcl   path  sys events subscribe kv         capabilities     read          path           capabilities     list    subscribe       subscribe event types     kv                Subscribing to KV events means that Proxy receives updates as soon as a secret changes  which reduces staleness in the cache  Vault Proxy only checks for a secret update if an event notification indicates that the related secret was updated      Step 2  Ensure tokens have  capabilities self  access  Tokens require  update  access to the   sys capabilies self    vault api docs system capabilities self  endpoint to request cached secrets  Vault tokens receive  update  permissions  by default   vault docs concepts policies default policy   If you have modified or removed the default policy  you must explicitly create a policy with the appropriate permissions  For example     hcl   path  sys capabilities self        capabilities     update               Step 3  Configure an appropriate refresh interval By default  Vault Proxy refreshes tokens every five minutes  You can change the default behavior and configure Proxy to verify and update cached token capabilities with the  static secret token capability refresh interval  parameter in the  cache  configuration stanza  For example  to set a refresh interval of one minute     hcl cache     cache static secrets   true   static secret token capability refresh interval    1m            Functionality  With static secret caching  Vault Proxy caches  GET  requests for KVv1 and KVv2 endpoints   When a client sends a  GET  request for a new KV secret  Proxy forwards the request to Vault but caches the response before forwarding it to the client  If that client makes subsequent  GET  requests for the same secret  Vault Proxy serves the cached response rather than forwarding the request to Vault    Tip title   Offline  Secret Access and CLI KV Get      Vault Proxy does not cache any non KV API responses  While KV secrets can be retrieved even if   Vault is unavailable  other requests cannot be served  As a result  using the  vault kv    CLI command  which sends a request to   sys internal ui mounts  before the KV  GET  request    will require a real request to Vault and cannot be served entirely from the cache or   when Vault is unavailable  you can use  vault read  instead      Tip   Similarly  when a token requests access to a KV secret  it must complete a success  GET  request  If the request is successful  Proxy caches the fact that the token was successful in addition to the result  Subsequent requests by the same token can then access this secret from the cache instead of Vault   Vault Proxy uses the  event notification system   vault docs concepts events  to keep the cache up to date  It monitors the KV event feed for events related to any secret currently stored in the cache  including modification events like updates and deletes  When Proxy detects a change in a cached secret  it will update or evict the cache entry as appropriate   Vault Proxy also checks and refreshes the access permissions of known tokens according to the window set with  static secret token capability refresh interval   By default  the refresh interval is five minutes   Every interval  Proxy calls   sys capabilies self    vault api docs system capabilities self  on behalf of every token in the cache to confirm the token still has permission to access the cached secret  If the result from Vault indicates that permission  or the token itself  was revoked  Proxy updates the cache entry so that the affected token can no longer access the relevant paths from the cache  The refresh interval is essentially the maximum period after which permission to read a KV secret is fully revoked for the relevant token   If the capabilities have been removed  or Proxy receives a  403  response  the capability is removed from the token  and that token cannot be used to access the cache  For other kinds of errors  such as Vault being unreachable or sealed  the  static secret token capability refresh behavior  config is consulted  If set to  optimistic   the default   the capability will not be removed unless we receive a  403  or valid response without the capability  If set to  pessimistic   the capability will be removed for any error  such as would occur if Vault is sealed   For token refresh to work  any token that will access the cache also needs  update  permission for   sys capabilies self    vault api docs system capabilities self   Having  update  permission for the token lets Proxy test capabilities for the token against multiple paths with a single request instead of testing for a  403  response for each path explicitly    Tip title  Refresh is per token  not per secret      If Proxy s API proxy is configured to use auto authentication for tokens  and   all     requests that pass through Vault Proxy use the same token  Proxy only   makes a single request to Vault every refresh interval  no matter how many   secrets are currently cached     Tip   When static secret caching is enabled  Proxy returns  HIT  or  MISS  in the  X Cache  response header for requests so client can tell if the response was served from the cache or forwarded from Vault  In the event of a hit  Proxy also sets the  Age  header to indicate  in seconds  how old the cache entry is    Tip title  Old does not mean stale      The fact that a cache entry is old  does not necessarily mean that the   information is out of date  Vault Proxy continually monitors KV events for   updates  A large value for  Age  may simply mean that the secret has not been   rotated recently     Tip      Configuration  The top level  cache  block has the following configuration entries relating to static secret caching      cache static secrets    bool  false     Enables static secret caching when set to  true   When  cache static secrets  and  auto auth  are both enabled  Vault Proxy serves KV secrets directly from the cache to clients with sufficient permission      static secret token capability refresh interval    duration   5m   optional     Sets the interval as a  duration format string   vault docs concepts duration format  at which Vault Proxy rechecks the permissions of tokens used to access cached secrets  The refresh interval is the maximum period after which permission to read a cached KV secret is fully revoked  Ignored when  cache static secrets  is  false       static secret token capability refresh behavior    string   optimistic   optional     Sets the capability refresh behavior in the case of an error when attempting to refresh capabilities  In the case of a  403   capabilities will be removed for the token with either option  In case of other errors  such as Vault being sealed or Vault being unavailable  this setting controls the behavior  If set to  optimistic   the default   capabilities will be removed for only  403  errors  If set to  pessimistic   capabilities will be removed for any error  This essentially allows configuring a preference between favoring availability   optimistic   or access fidelity   pessimistic   of cached static secrets  Ignored when  cache static secrets  is  false        Example configuration  The following example Vault Proxy configuration    Defines a TCP listener   listener   with TLS disabled    Forces clients using API proxy   api proxy   to identify with an auto auth token    Configures auto authentication   auto auth   for  approle     Enables static secret caching with  cache static secrets     Sets an explicit token capability refresh window of 1 hour with  static secret token capability refresh interval       hcl   Other Vault Proxy configuration blocks        cache     cache static secrets   true   static secret token capability refresh interval    1h     api proxy     use auto auth token    force     listener  tcp        address    127 0 0 1 8100      tls disable   true    auto auth     method       type    approle      config           role id file path    roleid        secret id file path    secretid        remove secret id file after reading   false                event system    vault docs concepts events


vault Vault Agent can be run as a Windows service In order to do this you need to register Vault Agent with the Windows page title Run Vault Agent as a Windows service Register Vault Agent with sc exe and run Agent as a Windows service layout docs Run Vault Agent as a Windows service

Answer:
---
layout: docs
page_title: Run Vault Agent as a Windows service
description: >-
  Register Vault Agent with sc.exe and run Agent as a Windows service.
---

# Run Vault Agent as a Windows service

Vault Agent can be run as a Windows service. In order to do this, you need to register Vault Agent with the Windows
Service Control Manager. After Vault Agent is registered, it can be started like any other Windows
service.

While this guide focuses on an example for Vault Agent, this example can be easily adapted to work for
[Vault Proxy](/vault/docs/agent-and-proxy/proxy) by changing the config and subcommand
given to `vault.exe` as appropriate.

~> Note: The commands on this page should be run in a PowerShell session with Administrator capabilities.

~> Note: When specifying Windows file paths in config files, they should be formatted like this: `C:/foo/bar/file.txt`
instead of using backslashes.

## Register Vault Agent as a Windows service

There are multiple ways to register Vault Agent as a Windows service. One way is to use
[`sc.exe`](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/sc-create). `sc.exe` works
best if the path to your Vault binary and its associated agent config file do not contain spaces. `sc.exe` can be
pretty tricky to get working correctly if your path contains spaces, as paths containing spaces must be quoted,
and escaping quotes correctly in a way that makes `sc.exe` happy is non-trivial. If your path contains spaces, or you prefer not to use `sc.exe`, another
alternative is to use the
[`New-Service`](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/new-service?view=powershell-5.1)
cmdlet. `New-Service` is less picky about the method used to escape quotes, and can sometimes be easier. Examples of
both will be shown below.

### Using sc.exe

~> **Important Note:** Ensure the executable path of the service is quoted, especially when it contains spaces, to avoid
potential privilege escalation risks.

If you use `sc.exe`, make sure you specify `sc.exe` explicitly, and not just `sc`. The command below shows the creation
of Vault Agent as a service, using "Vault Agent" as the display name, and starting automatically when Windows starts.
The `binPath` argument should include the fully qualified path to the Vault executable, as well as any arguments required.

```shell-session
PS C:\Windows\system32> sc.exe create VaultAgent binPath="C:\vault\vault.exe agent -config=C:\vault\agent-config.hcl" displayName="Vault Agent" start=auto
[SC] CreateService SUCCESS
```

Note that the spacing after the `=` in all of the arguments is intentional and required.

If you receive a success message, your service is registered with the service manager.

If you get an error, please verify the path to the binary and check the arguments, by running the contents of
`binPath=` directly in a PowerShell session and observing the results.

### Using New-Service

The syntax is slightly different for `New-Service`, but the gist is the same. The invocation below is equivalent to the
`sc.exe` one above.

```shell-session
PS C:\Windows\system32> New-Service -Name "VaultAgent" -BinaryPathName "C:\vault\vault.exe agent -config=C:\vault\agent-config.hcl" -DisplayName "Vault Agent" -StartupType "Automatic"

Status   Name               DisplayName
------   ----               -----------
Stopped  VaultAgent         Vault Agent
```

As mentioned previously, `New-Service` is easier to use if the path to your Vault executable and/or agent config contains spaces.
Below is an example of how to configure Vault Agent as a service using a path with spaces.

```shell-session
PS C:\Windows\system32> New-Service -Name "VaultAgent" -BinaryPathName '"C:\my dir\vault.exe" agent -config="C:\my dir\agent-config.hcl"' -DisplayName "Vault Agent" -StartupType "Automatic"

Status   Name               DisplayName
------   ----               -----------
Stopped  VaultAgent         Vault Agent
```

Note that only the paths themselves are double quoted, and the entire `BinaryPathName` is wrapped in single quotes, in order
to escape the double quotes used for the paths.

If anything goes wrong during this process, and you need to manually edit the path later, use the Registry Editor to find
the following key: `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\VaultAgent`. You can edit the `ImagePath` value
at that key to the correct path.

## Start the Vault Agent service

There are multiple ways to start the service.

- Using the `sc.exe` command.
- Using the `Start-Service` cmdlet.
- Go to the Windows Service Manager, and look for **VaultAgent** in the service name column. Click the
`Start` button to start the service.

### Example starting Vault Agent using `sc.exe`

```shell-session
PS C:\Windows\system32> sc.exe start VaultAgent

SERVICE_NAME: VaultAgent
     TYPE               : 10  WIN32_OWN_PROCESS
     STATE              : 4  RUNNING
                             (STOPPABLE, NOT_PAUSABLE, ACCEPTS_SHUTDOWN)
     WIN32_EXIT_CODE    : 0  (0x0)
     SERVICE_EXIT_CODE  : 0  (0x0)
     CHECKPOINT         : 0x0
     WAIT_HINT          : 0x0
     PID                : 6548
     FLAGS              :
```

### Example starting Vault Agent using `Start-Service`

```shell-session
PS C:\Windows\system32> Start-Service -Name "VaultAgent"
```

Note that in the case where the service was started successfully, `New-Service` does not return any output.

layout  docs page title  Run Vault Agent as a Windows service description       Register Vault Agent with sc exe and run Agent as a Windows service         Run Vault Agent as a Windows service  Vault Agent can be run as a Windows service  In order to do this  you need to register Vault Agent with the Windows Service Control Manager  After Vault Agent is registered  it can be started like any other Windows service   While this guide focuses on an example for Vault Agent  this example can be easily adapted to work for  Vault Proxy   vault docs agent and proxy proxy  by changing the config and subcommand given to  vault exe  as appropriate      Note  The commands on this page should be run in a PowerShell session with Administrator capabilities      Note  When specifying Windows file paths in config files  they should be formatted like this   C  foo bar file txt  instead of using backslashes      Register Vault Agent as a Windows service  There are multiple ways to register Vault Agent as a Windows service  One way is to use   sc exe   https   docs microsoft com en us windows server administration windows commands sc create    sc exe  works best if the path to your Vault binary and its associated agent config file do not contain spaces   sc exe  can be pretty tricky to get working correctly if your path contains spaces  as paths containing spaces must be quoted  and escaping quotes correctly in a way that makes  sc exe  happy is non trivial  If your path contains spaces  or you prefer not to use  sc exe   another alternative is to use the   New Service   https   docs microsoft com en us powershell module microsoft powershell management new service view powershell 5 1  cmdlet   New Service  is less picky about the method used to escape quotes  and can sometimes be easier  Examples of both will be shown below       Using sc exe       Important Note    Ensure the executable path of the service is quoted  especially when it contains spaces  to avoid potential privilege escalation risks   If you use  sc exe   make sure you specify  sc exe  explicitly  and not just  sc   The command below shows the creation of Vault Agent as a service  using  Vault Agent  as the display name  and starting automatically when Windows starts  The  binPath  argument should include the fully qualified path to the Vault executable  as well as any arguments required      shell session PS C  Windows system32  sc exe create VaultAgent binPath  C  vault vault exe agent  config C  vault agent config hcl  displayName  Vault Agent  start auto  SC  CreateService SUCCESS      Note that the spacing after the     in all of the arguments is intentional and required   If you receive a success message  your service is registered with the service manager   If you get an error  please verify the path to the binary and check the arguments  by running the contents of  binPath   directly in a PowerShell session and observing the results       Using New Service  The syntax is slightly different for  New Service   but the gist is the same  The invocation below is equivalent to the  sc exe  one above      shell session PS C  Windows system32  New Service  Name  VaultAgent   BinaryPathName  C  vault vault exe agent  config C  vault agent config hcl   DisplayName  Vault Agent   StartupType  Automatic   Status   Name               DisplayName                                         Stopped  VaultAgent         Vault Agent      As mentioned previously   New Service  is easier to use if the path to your Vault executable and or agent config contains spaces  Below is an example of how to configure Vault Agent as a service using a path with spaces      shell session PS C  Windows system32  New Service  Name  VaultAgent   BinaryPathName   C  my dir vault exe  agent  config  C  my dir agent config hcl    DisplayName  Vault Agent   StartupType  Automatic   Status   Name               DisplayName                                         Stopped  VaultAgent         Vault Agent      Note that only the paths themselves are double quoted  and the entire  BinaryPathName  is wrapped in single quotes  in order to escape the double quotes used for the paths   If anything goes wrong during this process  and you need to manually edit the path later  use the Registry Editor to find the following key   HKEY LOCAL MACHINE SYSTEM CurrentControlSet Services VaultAgent   You can edit the  ImagePath  value at that key to the correct path      Start the Vault Agent service  There are multiple ways to start the service     Using the  sc exe  command    Using the  Start Service  cmdlet    Go to the Windows Service Manager  and look for   VaultAgent   in the service name column  Click the  Start  button to start the service       Example starting Vault Agent using  sc exe      shell session PS C  Windows system32  sc exe start VaultAgent  SERVICE NAME  VaultAgent      TYPE                 10  WIN32 OWN PROCESS      STATE                4  RUNNING                               STOPPABLE  NOT PAUSABLE  ACCEPTS SHUTDOWN       WIN32 EXIT CODE      0   0x0       SERVICE EXIT CODE    0   0x0       CHECKPOINT           0x0      WAIT HINT            0x0      PID                  6548      FLAGS                         Example starting Vault Agent using  Start Service      shell session PS C  Windows system32  Start Service  Name  VaultAgent       Note that in the case where the service was started successfully   New Service  does not return any output


vault Vault Agent is a client side daemon that securely extracts secrets from Vault page title What is Vault Agent for clients without the complexity of API calls layout docs What is Vault Agent

Answer:
---
layout: docs
page_title: What is Vault Agent?
description: >-
  Vault Agent is a client-side daemon that securely extracts secrets from Vault
  for clients without the complexity of API calls.
---

# What is Vault Agent?

Vault Agent aims to remove the initial hurdle to adopt Vault by providing a
more scalable and simpler way for applications to integrate with Vault, by
providing the ability to render [templates][template] containing the secrets
required by your application, without requiring changes to your application.

![Vault Agent workflow](/img/vault-agent-workflow.png)

Vault Agent is a client daemon that provides the following features:

- [Auto-Auth][autoauth] - Automatically authenticate to Vault and manage the
  token renewal process for locally-retrieved dynamic secrets.
- [API Proxy][apiproxy] - Allows Vault Agent to act as a proxy for Vault's API,
  optionally using (or forcing the use of) the Auto-Auth token.
- [Caching][caching] - Allows client-side caching of responses containing newly
  created tokens and responses containing leased secrets generated off of these
  newly created tokens. The agent also manages the renewals of the cached tokens and leases.
- [Windows Service][winsvc] - Allows running the Vault Agent as a Windows
  service.
- [Templating][template] - Allows rendering of user-supplied templates by Vault
  Agent, using the token generated by the Auto-Auth step.
- [Process Supervisor Mode][process-supervisor] - Runs a child process with Vault
  secrets injected as environment variables.

## Auto-Auth

Vault Agent allows easy authentication to Vault in a wide variety of
environments. Please see the [Auto-Auth docs][autoauth]
for information.

Auto-Auth functionality takes place within an `auto_auth` configuration stanza.

## API proxy

Vault Agent can act as an API proxy for Vault, allowing you to talk to Vault's
API via a listener defined for Agent. It can be configured to optionally allow or force the automatic use of
the Auto-Auth token for these requests. Please see the [API Proxy docs][apiproxy]
for more information.

API Proxy functionality takes place within a defined `listener`, and its behaviour can be configured with an
[`api_proxy` stanza](/vault/docs/agent-and-proxy/agent/apiproxy#configuration-api_proxy).

## Caching

Vault Agent allows client-side caching of responses containing newly created tokens
and responses containing leased secrets generated off of these newly created tokens.
Please see the [Caching docs][caching] for information.

## API

### Quit

This endpoint triggers shutdown of the agent. By default, it is disabled, and can
be enabled per listener using the [`agent_api`][agent-api] stanza. It is recommended
to only enable this on trusted interfaces, as it does not require any authorization to use.

| Method | Path             |
| :----- | :--------------- |
| `POST` | `/agent/v1/quit` |

### Cache

See the [caching](/vault/docs/agent-and-proxy/agent/caching#api) page for details on the cache API.

## Configuration

### Command options

- `-log-level` ((#\_log_level)) `(string: "info")` - Log verbosity level. Supported values (in
  order of descending detail) are `trace`, `debug`, `info`, `warn`, and `error`. This can
  also be specified via the `VAULT_LOG_LEVEL` environment variable.

- `-log-format` ((#\_log_format)) `(string: "standard")` - Log format. Supported values
  are `standard` and `json`. This can also be specified via the
  `VAULT_LOG_FORMAT` environment variable.

- `-log-file` ((#\_log_file)) - the absolute path where Vault Agent should save
  log messages. Paths that end with a path separator use the default file name,
  `agent.log`. Paths that do not end with a file extension use the default
  `.log` extension. If the log file rotates, Vault Agent appends the current
  timestamp to the file name at the time of rotation. For example:

  `log-file` | Full log file | Rotated log file
  ---------- | ------------- | ----------------
  `/var/log` | `/var/log/agent.log` | `/var/log/agent-{timestamp}.log`
  `/var/log/my-diary` | `/var/log/my-diary.log` | `/var/log/my-diary-{timestamp}.log`
  `/var/log/my-diary.txt` | `/var/log/my-diary.txt` | `/var/log/my-diary-{timestamp}.txt`

- `-log-rotate-bytes` ((#\_log_rotate_bytes)) - to specify the number of
  bytes that should be written to a log before it needs to be rotated. Unless specified,
  there is no limit to the number of bytes that can be written to a log file.

- `-log-rotate-duration` ((#\_log_rotate_duration)) - to specify the maximum
  duration a log should be written to before it needs to be rotated. Must be a duration
  value such as 30s. Defaults to 24h.

- `-log-rotate-max-files` ((#\_log_rotate_max_files)) - to specify the maximum
  number of older log file archives to keep. Defaults to `0` (no files are ever deleted).
  Set to `-1` to discard old log files when a new one is created.

### Configuration file options

These are the currently-available general configuration options:

- `vault` ([vault][vault]: <optional\>) - Specifies the remote Vault server the Agent connects to.

- `auto_auth` ([auto_auth][autoauth]: <optional\>) - Specifies the method and other options used for Auto-Auth functionality.

- `api_proxy` ([api_proxy][apiproxy]: <optional\>) - Specifies options used for API Proxy functionality.

- `cache` ([cache][caching]: <optional\>) - Specifies options used for Caching functionality.

- `listener` ([listener][listener]: <optional\>) - Specifies the addresses and ports on which the Agent will respond to requests.

  ~> **Note:** On `SIGHUP` (`kill -SIGHUP $(pidof vault)`), Vault Agent will attempt to reload listener TLS configuration.
  This method can be used to refresh certificates used by Vault Agent without having to restart its process.

- `pid_file` `(string: "")` - Path to the file in which the agent's Process ID
  (PID) should be stored

- `exit_after_auth` `(bool: false)` - If set to `true`, the agent will exit
  with code `0` after a single successful auth, where success means that a
  token was retrieved and all sinks successfully wrote it. If you have
  `template` stanzas defined in your agent configuration, the agent
  waits for the configured templates to render successfully before
  exiting. If you use environment templates (`env_template` ) and set
  `exit_after_auth` to true, Vault agent will not run the child processes
  defined in your `exec` stanza.

- `disable_idle_connections` `(string array: [])` - A list of strings that disables idle connections for various features in Vault Agent.
  Valid values include: `auto-auth`, `caching`, `proxying`, and `templating`. `proxying` configures this for the API proxy, which is
  identical in function to `caching` for historical reasons. Can also be configured by setting the `VAULT_AGENT_DISABLE_IDLE_CONNECTIONS`
  environment variable as a comma separated string. This environment variable will override any values found in a configuration file.

- `disable_keep_alives` `(string array: [])` - A list of strings that disables keep alives for various features in Vault Agent.
  Valid values include: `auto-auth`, `caching`, `proxying`, and `templating`. `proxying` configures this for the API proxy, which is
  identical in function to `caching` for historical reasons. Can also be configured by setting the `VAULT_AGENT_DISABLE_KEEP_ALIVES`
  environment variable as a comma separated string. This environment variable will override any values found in a configuration file.

- `template` ([template][template]: <optional\>) - Specifies options used for templating Vault secrets to files.

- `template_config` ([template_config][template-config]: <optional\>) - Specifies templating engine behavior.

- `exec` ([exec][process-supervisor]: <optional\>) - Specifies options for vault agent to run a child process
  that injects secrets (via `env_template` stanzas) as environment variables.

- `env_template` ([env_template][template]: <optional\>) - Multiple blocks accepted. Each block contains
  the options used for templating Vault secrets as environment variables via the
  [process supervisor mode](/vault/docs/agent-and-proxy/agent/process-supervisor).

- `telemetry` ([telemetry][telemetry]: <optional\>) – Specifies the telemetry
  reporting system. See the [telemetry Stanza](/vault/docs/agent-and-proxy/agent#telemetry-stanza) section below
  for a list of metrics specific to Agent.

- `log_level` - Equivalent to the [`-log-level` command-line flag](#_log_level).

  ~> **Note:** On `SIGHUP` (`kill -SIGHUP $(pidof vault)`), Vault Agent will update the log level to the value
  specified by configuration file (including overriding values set using CLI or environment variable parameters).

- `log_format` - Equivalent to the [`-log-format` command-line flag](#_log_format).

- `log_file` - Equivalent to the [`-log-file` command-line flag](#_log_file).

- `log_rotate_duration` - Equivalent to the [`-log-rotate-duration` command-line flag](#_log_rotate_duration).

- `log_rotate_bytes` - Equivalent to the [`-log-rotate-bytes` command-line flag](#_log_rotate_bytes).

- `log_rotate_max_files` - Equivalent to the [`-log-rotate-max-files` command-line flag](#_log_rotate_max_files).

### vault stanza

There can at most be one top level `vault` block, and it has the following
configuration entries:

- `address` `(string: <optional>)` - The address of the Vault server to
  connect to. This should be a Fully Qualified Domain Name (FQDN) or IP
  such as `https://vault-fqdn:8200` or `https://172.16.9.8:8200`.
  This value can be overridden by setting the `VAULT_ADDR` environment variable.

- `ca_cert` `(string: <optional>)` - Path on the local disk to a single PEM-encoded
  CA certificate to verify the Vault server's SSL certificate. This value can
  be overridden by setting the `VAULT_CACERT` environment variable.

- `ca_path` `(string: <optional>)` - Path on the local disk to a directory of
  PEM-encoded CA certificates to verify the Vault server's SSL certificate.
  This value can be overridden by setting the `VAULT_CAPATH` environment
  variable.

- `client_cert` `(string: <optional>)` - Path on the local disk to a single
  PEM-encoded CA certificate to use for TLS authentication to the Vault server.
  This value can be overridden by setting the `VAULT_CLIENT_CERT` environment
  variable.

- `client_key` `(string: <optional>)` - Path on the local disk to a single
  PEM-encoded private key matching the client certificate from `client_cert`.
  This value can be overridden by setting the `VAULT_CLIENT_KEY` environment
  variable.

- `tls_skip_verify` `(string: <optional>)` - Disable verification of TLS
  certificates. Using this option is highly discouraged as it decreases the
  security of data transmissions to and from the Vault server. This value can
  be overridden by setting the `VAULT_SKIP_VERIFY` environment variable.

- `tls_server_name` `(string: <optional>)` - Name to use as the SNI host when
  connecting via TLS. This value can be overridden by setting the
  `VAULT_TLS_SERVER_NAME` environment variable.

- `namespace` `(string: <optional>)` - Namespace to use for all of Vault Agent's
  requests to Vault. This can also be specified by command line or environment variable.
  The order of precedence is: this setting lowest, followed by the environment variable
  `VAULT_NAMESPACE`, and then the highest precedence command-line option `-namespace`.
  If none of these are specified, defaults to the root namespace.

#### retry stanza

The `vault` stanza may contain a `retry` stanza that controls how failing Vault
requests are handled, whether these requests are issued in order to render
templates, or are proxied requests coming from the api proxy subsystem.
Auto-auth, however, has its own notion of retrying and is not affected by this
section.

For requests from the templating engine, Vaul Agent will reset its retry counter and
perform retries again once all retries are exhausted. This means that templating
will retry on failures indefinitely unless `exit_on_retry_failure` from the
[`template_config`][template-config] stanza is set to `true`.

Here are the options for the `retry` stanza:

- `num_retries` `(int: 12)` - Specify how many times a failing request will
  be retried. A value of `0` translates to the default, i.e. 12 retries.
  A value of `-1` disables retries. The environment variable `VAULT_MAX_RETRIES`
  overrides this setting.

There are a few subtleties to be aware of here. First, requests originating
from the proxy cache will only be retried if they resulted in specific HTTP
result codes: any 50x code except 501 ("not implemented"), as well as 412
("precondition failed"); 412 is used in Vault Enterprise 1.7+ to indicate a
stale read due to eventual consistency. Requests coming from the template
subsystem are retried regardless of the failure.

Second, templating retries may be performed by both the templating engine _and_
the cache proxy if Vault Agent [persistent
cache][persistent-cache] is enabled. This is due to the
fact that templating requests go through the cache proxy when persistence is
enabled.

Third, the backoff algorithm used to set the time between retries differs for
the template and cache subsystems. This is a technical limitation we hope
to address in the future.

### listener stanza

Vault Agent supports one or more [listener][listener_main] stanzas. Listeners
can be configured with or without [caching][caching], but will use the cache if it
has been configured, and will enable the [API proxy][apiproxy]. In addition to the standard
listener configuration, an Agent's listener configuration also supports the following:

- `require_request_header` `(bool: false)` - Require that all incoming HTTP
  requests on this listener must have an `X-Vault-Request: true` header entry.
  Using this option offers an additional layer of protection from Server Side
  Request Forgery attacks. Requests on the listener that do not have the proper
  `X-Vault-Request` header will fail, with a HTTP response status code of `412: Precondition Failed`.

- `role` `(string: default)` - `role` determines which APIs the listener serves.
  It can be configured to `metrics_only` to serve only metrics, or the default role, `default`,
  which serves everything (including metrics). The `require_request_header` does not apply
  to `metrics_only` listeners.

- `agent_api` ([agent_api][agent-api]: <optional\>) - Manages optional Agent API endpoints.

#### agent_api stanza

- `enable_quit` `(bool: false)` - If set to `true`, the agent will enable the [quit](/vault/docs/agent-and-proxy/agent#quit) API.

### telemetry stanza

Vault Agent supports the [telemetry][telemetry] stanza and collects various
runtime metrics about its performance, the auto-auth and the cache status:

| Metric                           | Description                                          | Type    |
| -------------------------------- | ---------------------------------------------------- | ------- |
| `vault.agent.authenticated`      | Current authentication status (1 - has valid token,  | gauge   |
|                                  | 0 - no valid token)                                  |         |
| `vault.agent.auth.failure`       | Number of authentication failures                    | counter |
| `vault.agent.auth.success`       | Number of authentication successes                   | counter |
| `vault.agent.proxy.success`      | Number of requests successfully proxied              | counter |
| `vault.agent.proxy.client_error` | Number of requests for which Vault returned an error | counter |
| `vault.agent.proxy.error`        | Number of requests the agent failed to proxy         | counter |
| `vault.agent.cache.hit`          | Number of cache hits                                 | counter |
| `vault.agent.cache.miss`         | Number of cache misses                               | counter |

### IMPORTANT: `VAULT_ADDR` usage

If you export the `VAULT_ADDR` environment variable on the Vault Agent instance, that value takes precedence over the value in the configuration file. The Vault Agent uses that to connect to Vault and this can create an infinite loop where the value of `VAULT_ADDR` is used to make a connection, and the Vault Agent ends up trying to connect to itself instead of the server.

When the connection fails, the Vault Agent increments the port and tries again. The agent repeats these attempts, which leads to port exhaustion.

This problem is a result of the precedence order of the 3 different ways to configure the Vault address. They are, in increasing order of priority:

1. Configuration files
1. Environment variables
1. CLI flags

## Start Vault Agent

To run Vault Agent:

1. [Download](/vault/downloads) the Vault binary where the client application runs
   (virtual machine, Kubernetes pod, etc.)

1. Create a Vault Agent configuration file. (See the [Example
   Configuration](#example-configuration) section for an example configuration.)

1. Start a Vault Agent with the configuration file.

   **Example:**

   ```shell-session
   $ vault agent -config=/etc/vault/agent-config.hcl
   ```

   To get help, run:

   ```shell-session
   $ vault agent -h
   ```

As with Vault, the `-config` flag can be used in three different ways:

- Use the flag once to name the path to a single specific configuration file.
- Use the flag multiple times to name multiple configuration files, which will be composed at runtime.
- Use the flag to name a directory of configuration files, the contents of which will be composed at runtime.

## Example configuration

An example configuration, with very contrived values, follows:

```hcl
pid_file = "./pidfile"

vault {
  address = "https://vault-fqdn:8200"
  retry {
    num_retries = 5
  }
}

auto_auth {
  method "aws" {
    mount_path = "auth/aws-subaccount"
    config = {
      type = "iam"
      role = "foobar"
    }
  }

  sink "file" {
    config = {
      path = "/tmp/file-foo"
    }
  }

  sink "file" {
    wrap_ttl = "5m"
    aad_env_var = "TEST_AAD_ENV"
    dh_type = "curve25519"
    dh_path = "/tmp/file-foo-dhpath2"
    config = {
      path = "/tmp/file-bar"
    }
  }
}

cache {
  // An empty cache stanza still enables caching
}

api_proxy {
  use_auto_auth_token = true
}

listener "unix" {
  address = "/path/to/socket"
  tls_disable = true

  agent_api {
    enable_quit = true
  }
}

listener "tcp" {
  address = "127.0.0.1:8100"
  tls_disable = true
}

template {
  source = "/etc/vault/server.key.ctmpl"
  destination = "/etc/vault/server.key"
}

template {
  source = "/etc/vault/server.crt.ctmpl"
  destination = "/etc/vault/server.crt"
}
```

[vault]: /vault/docs/agent-and-proxy/agent#vault-stanza
[autoauth]: /vault/docs/agent-and-proxy/autoauth
[caching]: /vault/docs/agent-and-proxy/agent/caching
[apiproxy]: /vault/docs/agent-and-proxy/agent/apiproxy
[persistent-cache]: /vault/docs/agent-and-proxy/agent/caching/persistent-caches
[template]: /vault/docs/agent-and-proxy/agent/template
[process-supervisor]: /vault/docs/agent-and-proxy/agent/process-supervisor
[template-config]: /vault/docs/agent-and-proxy/agent/template#template-configurations
[agent-api]: /vault/docs/agent-and-proxy/agent/#agent_api-stanza
[listener]: /vault/docs/agent-and-proxy/agent#listener-stanza
[listener_main]: /vault/docs/configuration/listener/tcp
[winsvc]: /vault/docs/agent-and-proxy/agent/winsvc
[telemetry]: /vault/docs/configuration/telemetry

layout  docs page title  What is Vault Agent  description       Vault Agent is a client side daemon that securely extracts secrets from Vault   for clients without the complexity of API calls         What is Vault Agent   Vault Agent aims to remove the initial hurdle to adopt Vault by providing a more scalable and simpler way for applications to integrate with Vault  by providing the ability to render  templates  template  containing the secrets required by your application  without requiring changes to your application     Vault Agent workflow   img vault agent workflow png   Vault Agent is a client daemon that provides the following features      Auto Auth  autoauth    Automatically authenticate to Vault and manage the   token renewal process for locally retrieved dynamic secrets     API Proxy  apiproxy    Allows Vault Agent to act as a proxy for Vault s API    optionally using  or forcing the use of  the Auto Auth token     Caching  caching    Allows client side caching of responses containing newly   created tokens and responses containing leased secrets generated off of these   newly created tokens  The agent also manages the renewals of the cached tokens and leases     Windows Service  winsvc    Allows running the Vault Agent as a Windows   service     Templating  template    Allows rendering of user supplied templates by Vault   Agent  using the token generated by the Auto Auth step     Process Supervisor Mode  process supervisor    Runs a child process with Vault   secrets injected as environment variables      Auto Auth  Vault Agent allows easy authentication to Vault in a wide variety of environments  Please see the  Auto Auth docs  autoauth  for information   Auto Auth functionality takes place within an  auto auth  configuration stanza      API proxy  Vault Agent can act as an API proxy for Vault  allowing you to talk to Vault s API via a listener defined for Agent  It can be configured to optionally allow or force the automatic use of the Auto Auth token for these requests  Please see the  API Proxy docs  apiproxy  for more information   API Proxy functionality takes place within a defined  listener   and its behaviour can be configured with an   api proxy  stanza   vault docs agent and proxy agent apiproxy configuration api proxy       Caching  Vault Agent allows client side caching of responses containing newly created tokens and responses containing leased secrets generated off of these newly created tokens  Please see the  Caching docs  caching  for information      API      Quit  This endpoint triggers shutdown of the agent  By default  it is disabled  and can be enabled per listener using the   agent api   agent api  stanza  It is recommended to only enable this on trusted interfaces  as it does not require any authorization to use     Method   Path                                                POST      agent v1 quit         Cache  See the  caching   vault docs agent and proxy agent caching api  page for details on the cache API      Configuration      Command options      log level       log level     string   info      Log verbosity level  Supported values  in   order of descending detail  are  trace    debug    info    warn   and  error   This can   also be specified via the  VAULT LOG LEVEL  environment variable       log format       log format     string   standard      Log format  Supported values   are  standard  and  json   This can also be specified via the    VAULT LOG FORMAT  environment variable       log file       log file     the absolute path where Vault Agent should save   log messages  Paths that end with a path separator use the default file name     agent log   Paths that do not end with a file extension use the default     log  extension  If the log file rotates  Vault Agent appends the current   timestamp to the file name at the time of rotation  For example      log file    Full log file   Rotated log file                                                     var log      var log agent log      var log agent  timestamp  log      var log my diary      var log my diary log      var log my diary  timestamp  log      var log my diary txt      var log my diary txt      var log my diary  timestamp  txt       log rotate bytes       log rotate bytes     to specify the number of   bytes that should be written to a log before it needs to be rotated  Unless specified    there is no limit to the number of bytes that can be written to a log file       log rotate duration       log rotate duration     to specify the maximum   duration a log should be written to before it needs to be rotated  Must be a duration   value such as 30s  Defaults to 24h       log rotate max files       log rotate max files     to specify the maximum   number of older log file archives to keep  Defaults to  0   no files are ever deleted     Set to   1  to discard old log files when a new one is created       Configuration file options  These are the currently available general configuration options      vault   code   vault  vault    optional     code    Specifies the remote Vault server the Agent connects to      auto auth   code   auto auth  autoauth    optional     code    Specifies the method and other options used for Auto Auth functionality      api proxy   code   api proxy  apiproxy    optional     code    Specifies options used for API Proxy functionality      cache   code   cache  caching    optional     code    Specifies options used for Caching functionality      listener   code   listener  listener    optional     code    Specifies the addresses and ports on which the Agent will respond to requests          Note    On  SIGHUP    kill  SIGHUP   pidof vault     Vault Agent will attempt to reload listener TLS configuration    This method can be used to refresh certificates used by Vault Agent without having to restart its process      pid file    string         Path to the file in which the agent s Process ID    PID  should be stored     exit after auth    bool  false     If set to  true   the agent will exit   with code  0  after a single successful auth  where success means that a   token was retrieved and all sinks successfully wrote it  If you have    template  stanzas defined in your agent configuration  the agent   waits for the configured templates to render successfully before   exiting  If you use environment templates   env template    and set    exit after auth  to true  Vault agent will not run the child processes   defined in your  exec  stanza      disable idle connections    string array         A list of strings that disables idle connections for various features in Vault Agent    Valid values include   auto auth    caching    proxying   and  templating    proxying  configures this for the API proxy  which is   identical in function to  caching  for historical reasons  Can also be configured by setting the  VAULT AGENT DISABLE IDLE CONNECTIONS    environment variable as a comma separated string  This environment variable will override any values found in a configuration file      disable keep alives    string array         A list of strings that disables keep alives for various features in Vault Agent    Valid values include   auto auth    caching    proxying   and  templating    proxying  configures this for the API proxy  which is   identical in function to  caching  for historical reasons  Can also be configured by setting the  VAULT AGENT DISABLE KEEP ALIVES    environment variable as a comma separated string  This environment variable will override any values found in a configuration file      template   code   template  template    optional     code    Specifies options used for templating Vault secrets to files      template config   code   template config  template config    optional     code    Specifies templating engine behavior      exec   code   exec  process supervisor    optional     code    Specifies options for vault agent to run a child process   that injects secrets  via  env template  stanzas  as environment variables      env template   code   env template  template    optional     code    Multiple blocks accepted  Each block contains   the options used for templating Vault secrets as environment variables via the    process supervisor mode   vault docs agent and proxy agent process supervisor       telemetry   code   telemetry  telemetry    optional     code    Specifies the telemetry   reporting system  See the  telemetry Stanza   vault docs agent and proxy agent telemetry stanza  section below   for a list of metrics specific to Agent      log level    Equivalent to the    log level  command line flag    log level           Note    On  SIGHUP    kill  SIGHUP   pidof vault     Vault Agent will update the log level to the value   specified by configuration file  including overriding values set using CLI or environment variable parameters       log format    Equivalent to the    log format  command line flag    log format       log file    Equivalent to the    log file  command line flag    log file       log rotate duration    Equivalent to the    log rotate duration  command line flag    log rotate duration       log rotate bytes    Equivalent to the    log rotate bytes  command line flag    log rotate bytes       log rotate max files    Equivalent to the    log rotate max files  command line flag    log rotate max files        vault stanza  There can at most be one top level  vault  block  and it has the following configuration entries      address    string   optional      The address of the Vault server to   connect to  This should be a Fully Qualified Domain Name  FQDN  or IP   such as  https   vault fqdn 8200  or  https   172 16 9 8 8200     This value can be overridden by setting the  VAULT ADDR  environment variable      ca cert    string   optional      Path on the local disk to a single PEM encoded   CA certificate to verify the Vault server s SSL certificate  This value can   be overridden by setting the  VAULT CACERT  environment variable      ca path    string   optional      Path on the local disk to a directory of   PEM encoded CA certificates to verify the Vault server s SSL certificate    This value can be overridden by setting the  VAULT CAPATH  environment   variable      client cert    string   optional      Path on the local disk to a single   PEM encoded CA certificate to use for TLS authentication to the Vault server    This value can be overridden by setting the  VAULT CLIENT CERT  environment   variable      client key    string   optional      Path on the local disk to a single   PEM encoded private key matching the client certificate from  client cert     This value can be overridden by setting the  VAULT CLIENT KEY  environment   variable      tls skip verify    string   optional      Disable verification of TLS   certificates  Using this option is highly discouraged as it decreases the   security of data transmissions to and from the Vault server  This value can   be overridden by setting the  VAULT SKIP VERIFY  environment variable      tls server name    string   optional      Name to use as the SNI host when   connecting via TLS  This value can be overridden by setting the    VAULT TLS SERVER NAME  environment variable      namespace    string   optional      Namespace to use for all of Vault Agent s   requests to Vault  This can also be specified by command line or environment variable    The order of precedence is  this setting lowest  followed by the environment variable    VAULT NAMESPACE   and then the highest precedence command line option   namespace     If none of these are specified  defaults to the root namespace        retry stanza  The  vault  stanza may contain a  retry  stanza that controls how failing Vault requests are handled  whether these requests are issued in order to render templates  or are proxied requests coming from the api proxy subsystem  Auto auth  however  has its own notion of retrying and is not affected by this section   For requests from the templating engine  Vaul Agent will reset its retry counter and perform retries again once all retries are exhausted  This means that templating will retry on failures indefinitely unless  exit on retry failure  from the   template config   template config  stanza is set to  true    Here are the options for the  retry  stanza      num retries    int  12     Specify how many times a failing request will   be retried  A value of  0  translates to the default  i e  12 retries    A value of   1  disables retries  The environment variable  VAULT MAX RETRIES    overrides this setting   There are a few subtleties to be aware of here  First  requests originating from the proxy cache will only be retried if they resulted in specific HTTP result codes  any 50x code except 501   not implemented    as well as 412   precondition failed    412 is used in Vault Enterprise 1 7  to indicate a stale read due to eventual consistency  Requests coming from the template subsystem are retried regardless of the failure   Second  templating retries may be performed by both the templating engine  and  the cache proxy if Vault Agent  persistent cache  persistent cache  is enabled  This is due to the fact that templating requests go through the cache proxy when persistence is enabled   Third  the backoff algorithm used to set the time between retries differs for the template and cache subsystems  This is a technical limitation we hope to address in the future       listener stanza  Vault Agent supports one or more  listener  listener main  stanzas  Listeners can be configured with or without  caching  caching   but will use the cache if it has been configured  and will enable the  API proxy  apiproxy   In addition to the standard listener configuration  an Agent s listener configuration also supports the following      require request header    bool  false     Require that all incoming HTTP   requests on this listener must have an  X Vault Request  true  header entry    Using this option offers an additional layer of protection from Server Side   Request Forgery attacks  Requests on the listener that do not have the proper    X Vault Request  header will fail  with a HTTP response status code of  412  Precondition Failed       role    string  default      role  determines which APIs the listener serves    It can be configured to  metrics only  to serve only metrics  or the default role   default     which serves everything  including metrics   The  require request header  does not apply   to  metrics only  listeners      agent api   code   agent api  agent api    optional     code    Manages optional Agent API endpoints        agent api stanza     enable quit    bool  false     If set to  true   the agent will enable the  quit   vault docs agent and proxy agent quit  API       telemetry stanza  Vault Agent supports the  telemetry  telemetry  stanza and collects various runtime metrics about its performance  the auto auth and the cache status     Metric                             Description                                            Type                                                                                vault agent authenticated         Current authentication status  1   has valid token     gauge                                          0   no valid token                                                  vault agent auth failure          Number of authentication failures                      counter      vault agent auth success          Number of authentication successes                     counter      vault agent proxy success         Number of requests successfully proxied                counter      vault agent proxy client error    Number of requests for which Vault returned an error   counter      vault agent proxy error           Number of requests the agent failed to proxy           counter      vault agent cache hit             Number of cache hits                                   counter      vault agent cache miss            Number of cache misses                                 counter        IMPORTANT   VAULT ADDR  usage  If you export the  VAULT ADDR  environment variable on the Vault Agent instance  that value takes precedence over the value in the configuration file  The Vault Agent uses that to connect to Vault and this can create an infinite loop where the value of  VAULT ADDR  is used to make a connection  and the Vault Agent ends up trying to connect to itself instead of the server   When the connection fails  the Vault Agent increments the port and tries again  The agent repeats these attempts  which leads to port exhaustion   This problem is a result of the precedence order of the 3 different ways to configure the Vault address  They are  in increasing order of priority   1  Configuration files 1  Environment variables 1  CLI flags     Start Vault Agent  To run Vault Agent   1   Download   vault downloads  the Vault binary where the client application runs     virtual machine  Kubernetes pod  etc    1  Create a Vault Agent configuration file   See the  Example    Configuration   example configuration  section for an example configuration    1  Start a Vault Agent with the configuration file        Example           shell session      vault agent  config  etc vault agent config hcl            To get help  run         shell session      vault agent  h         As with Vault  the   config  flag can be used in three different ways     Use the flag once to name the path to a single specific configuration file    Use the flag multiple times to name multiple configuration files  which will be composed at runtime    Use the flag to name a directory of configuration files  the contents of which will be composed at runtime      Example configuration  An example configuration  with very contrived values  follows      hcl pid file      pidfile   vault     address    https   vault fqdn 8200    retry       num retries   5        auto auth     method  aws        mount path    auth aws subaccount      config           type    iam        role    foobar               sink  file        config           path     tmp file foo               sink  file        wrap ttl    5m      aad env var    TEST AAD ENV      dh type    curve25519      dh path     tmp file foo dhpath2      config           path     tmp file bar               cache        An empty cache stanza still enables caching    api proxy     use auto auth token   true    listener  unix      address     path to socket    tls disable   true    agent api       enable quit   true        listener  tcp      address    127 0 0 1 8100    tls disable   true    template     source     etc vault server key ctmpl    destination     etc vault server key     template     source     etc vault server crt ctmpl    destination     etc vault server crt          vault    vault docs agent and proxy agent vault stanza  autoauth    vault docs agent and proxy autoauth  caching    vault docs agent and proxy agent caching  apiproxy    vault docs agent and proxy agent apiproxy  persistent cache    vault docs agent and proxy agent caching persistent caches  template    vault docs agent and proxy agent template  process supervisor    vault docs agent and proxy agent process supervisor  template config    vault docs agent and proxy agent template template configurations  agent api    vault docs agent and proxy agent  agent api stanza  listener    vault docs agent and proxy agent listener stanza  listener main    vault docs configuration listener tcp  winsvc    vault docs agent and proxy agent winsvc  telemetry    vault docs configuration telemetry


vault page title Run Vault Agent in process supervisor mode environment variables for use in external processes Run Vault Agent in process supervisor mode Run Vault Agent in process supervisor mode to write Vault secrets to layout docs

Answer:
---
layout: docs
page_title: Run Vault Agent in process supervisor mode
description: >-
  Run Vault Agent in process supervisor mode to write Vault secrets to
  environment variables for use in external processes.

---

# Run Vault Agent in process supervisor mode

Vault Agent's Process Supervisor Mode allows Vault secrets to be injected into
a process via environment variables using
[Consul Template markup][consul-templating-language].

-> If you are running your applications in a Kubernetes cluster, we recommend
  evaluating the [Vault Secrets Operator](/vault/docs/platform/k8s/vso) and
  the [Vault Agent Sidecar Injector](/vault/docs/platform/k8s/injector)
  instead.

## Functionality

Vault Agent will inject secrets referenced in the `env_template` configuration
blocks as environment variables into the child process specified in the `exec` block.

When you start Vault Agent in process supervisor mode, it will wait until each
environment variable template has rendered at least once before starting the
process. If `restart_on_secret_changes` is set to `always` (default), Agent
will restart the process whenever an update to an injected secret is detected.
This could be either a static secret update (done on
[`static_secret_render_interval`](/vault/docs/agent-and-proxy/agent/template#static_secret_render_interval))
or dynamic secret being close to its expiration.

In many ways, Vault Agent will mirror the child process. Standard intput and
output streams (`stdin` / `stdout` / `stderr`) are all forwarded to the child
process. Additionally, Vault Agent will exit when the child process exits on
its own with the same exit code.

## Configuration

-> Agent's [generate-config](/vault/docs/agent-and-proxy/agent/generate-config)
   tool will help you get started by generating a valid agent configuration
   file from the given inputs.

The process supervisor mode requires at least one `env_template` block and
exactly one top level `exec` block. It is incompatible with regular file
`template` entries.

### `env_template`

`env_template` stanza maps the template specified in the `contents` field or
referenced in the `source` field to the environment variable name in the title
of the stanza. It uses the same
[templating language](/vault/docs/agent-and-proxy/agent/template#templating-language)
as file templates but permits only a subset of
[its configuration parameters](/vault/docs/agent-and-proxy/agent/template#template_configurations):

- environment variable name `(string: <required>)` - the name of the
  environment variable to which the contents of the template should map.

- `contents` `(string: "")` - This option allows embedding the contents of
  a template in the configuration file rather then supplying the `source` path to
  the template file. This is useful for short templates. This option is mutually
  exclusive with the `source` option.

- `source` `(string: "")` - Path on disk to use as the input template. This
  option is required if not using the `contents` option.

- `error_on_missing_key` `(bool: false)` - Exit with an error when accessing
  a struct or map field/key that does notexist. The default behavior will print `<no value>`
  when accessing a field that does not exist. It is highly recommended you set this
  to "true". Also see
  [`exit_on_retry_failure` in global Vault Agent Template Config](/vault/docs/agent-and-proxy/agent/template#interaction-between-exit_on_retry_failure-and-error_on_missing_key).

- `left_delimiter` `(string: "")` - Delimiter to use in the template. The
  default is "}}" but for some templates, it may be easier to use a different
  delimiter that does not conflict with the output file itself.

### `exec`

The top level `exec` block has the following configuration entries.

- `command` `(string array: required)` - Specify the command for the child
  process with optional arguments. The executable's path must be either
  absolute or relative to the current working directory.

- `restart_on_secret_changes` `(string: "always")` - Controls whether agent
  will restart the child process on secret changes. There are two types of
  secret changes relevant to this configuration: a static secret update (on
  [static_secret_render_interval`](/vault/docs/agent-and-proxy/agent/template#static_secret_render_interval))
  and dynamic secret being close to its expiration. The configuration supports
  two options: `always` and `never`.

- `restart_stop_signal` `(string: "SIGTERM")` - Signal to send to the child
  process when a secret has been updated and the process needs to be restarted.
  The process has 30 seconds after this signal is sent until `SIGKILL` is sent
  to force the child process to stop.

## Configuration example

The following example was generated using
[`vault agent generate-config`](/vault/docs/agent-and-proxy/agent/generate-config),
a configuration helper tool. Given this configuration, Vault Agent will run
the child process (`./my-app arg1 arg2`) with two additional environment
variables (`FOO_USER` and `FOO_PASSWORD`) populated with secrets from Vault.

```hcl
auto_auth {

  method {
    type = "token_file"

    config {
      token_file_path = "/Users/avean/.vault-token"
    }
  }
}

template_config {
  static_secret_render_interval = "5m"
  exit_on_retry_failure         = true
  max_connections_per_host      = 10
}

vault {
  address = "http://localhost:8200"
}

env_template "FOO_PASSWORD" {
  contents             = ""
  error_on_missing_key = true
}
env_template "FOO_USER" {
  contents             = ""
  error_on_missing_key = true
}

exec {
  command                   = ["./my-app", "arg1", "arg2"]
  restart_on_secret_changes = "always"
  restart_stop_signal       = "SIGTERM"
}
```

[consul-templating-language]: https://github.com/hashicorp/consul-template/blob/v0.28.1/docs/templating-language.md
[template-config]: /vault/docs/agent-and-proxy/agent/template#template-configurations

## Tutorial

Refer to the [Vault Agent - secrets as environment
variables](/vault/tutorials/vault-agent/agent-env-vars) tutorial for an
end-to-end example.

layout  docs page title  Run Vault Agent in process supervisor mode description       Run Vault Agent in process supervisor mode to write Vault secrets to   environment variables for use in external processes          Run Vault Agent in process supervisor mode  Vault Agent s Process Supervisor Mode allows Vault secrets to be injected into a process via environment variables using  Consul Template markup  consul templating language       If you are running your applications in a Kubernetes cluster  we recommend   evaluating the  Vault Secrets Operator   vault docs platform k8s vso  and   the  Vault Agent Sidecar Injector   vault docs platform k8s injector    instead      Functionality  Vault Agent will inject secrets referenced in the  env template  configuration blocks as environment variables into the child process specified in the  exec  block   When you start Vault Agent in process supervisor mode  it will wait until each environment variable template has rendered at least once before starting the process  If  restart on secret changes  is set to  always   default   Agent will restart the process whenever an update to an injected secret is detected  This could be either a static secret update  done on   static secret render interval    vault docs agent and proxy agent template static secret render interval   or dynamic secret being close to its expiration   In many ways  Vault Agent will mirror the child process  Standard intput and output streams   stdin     stdout     stderr   are all forwarded to the child process  Additionally  Vault Agent will exit when the child process exits on its own with the same exit code      Configuration     Agent s  generate config   vault docs agent and proxy agent generate config     tool will help you get started by generating a valid agent configuration    file from the given inputs   The process supervisor mode requires at least one  env template  block and exactly one top level  exec  block  It is incompatible with regular file  template  entries        env template    env template  stanza maps the template specified in the  contents  field or referenced in the  source  field to the environment variable name in the title of the stanza  It uses the same  templating language   vault docs agent and proxy agent template templating language  as file templates but permits only a subset of  its configuration parameters   vault docs agent and proxy agent template template configurations      environment variable name   string   required      the name of the   environment variable to which the contents of the template should map      contents    string         This option allows embedding the contents of   a template in the configuration file rather then supplying the  source  path to   the template file  This is useful for short templates  This option is mutually   exclusive with the  source  option      source    string         Path on disk to use as the input template  This   option is required if not using the  contents  option      error on missing key    bool  false     Exit with an error when accessing   a struct or map field key that does notexist  The default behavior will print   no value     when accessing a field that does not exist  It is highly recommended you set this   to  true   Also see     exit on retry failure  in global Vault Agent Template Config   vault docs agent and proxy agent template interaction between exit on retry failure and error on missing key       left delimiter    string         Delimiter to use in the template  The   default is      but for some templates  it may be easier to use a different   delimiter that does not conflict with the output file itself        exec   The top level  exec  block has the following configuration entries      command    string array  required     Specify the command for the child   process with optional arguments  The executable s path must be either   absolute or relative to the current working directory      restart on secret changes    string   always      Controls whether agent   will restart the child process on secret changes  There are two types of   secret changes relevant to this configuration  a static secret update  on    static secret render interval    vault docs agent and proxy agent template static secret render interval     and dynamic secret being close to its expiration  The configuration supports   two options   always  and  never       restart stop signal    string   SIGTERM      Signal to send to the child   process when a secret has been updated and the process needs to be restarted    The process has 30 seconds after this signal is sent until  SIGKILL  is sent   to force the child process to stop       Configuration example  The following example was generated using   vault agent generate config    vault docs agent and proxy agent generate config   a configuration helper tool  Given this configuration  Vault Agent will run the child process     my app arg1 arg2   with two additional environment variables   FOO USER  and  FOO PASSWORD   populated with secrets from Vault      hcl auto auth      method       type    token file       config         token file path     Users avean  vault token               template config     static secret render interval    5m    exit on retry failure           true   max connections per host        10    vault     address    http   localhost 8200     env template  FOO PASSWORD      contents                    error on missing key   true   env template  FOO USER      contents                    error on missing key   true    exec     command                         my app    arg1    arg2     restart on secret changes    always    restart stop signal          SIGTERM          consul templating language   https   github com hashicorp consul template blob v0 28 1 docs templating language md  template config    vault docs agent and proxy agent template template configurations      Tutorial  Refer to the  Vault Agent   secrets as environment variables   vault tutorials vault agent agent env vars  tutorial for an end to end example