vault Step by step instructions for managing Vault resources programmatically with page title Manage Vault resources programmatically layout docs Terraform Manage Vault resources programmatically with Terraform

Answer:
---
layout: docs
page_title: Manage Vault resources programmatically
description: >-
  Step-by-step instructions for managing Vault resources programmatically with
  Terraform
---

# Manage Vault resources programmatically with Terraform

Use Terraform to manage policies, namespaces, and plugins in Vault.

## Before you start

- **You must have [Terraform installed](/terraform/install)**.
- **You must have the [Terraform Vault provider](https://registry.terraform.io/providers/hashicorp/vault/latest) configured**.
- **You must have sufficient access to run Terraform**.
- **You must have a [Vault server running](/vault/tutorials/getting-started/getting-started-dev-server)**.

## Step 1: Create a resource file for namespaces

Terraform Vault provider supports a `vault_namespace` resource type for
managing Vault namespaces:

```hcl
resource "vault_namespace" "<TERRAFORM_RESOURCE_NAME>" {
  path = "<VAULT_NAMESPACE>"
}
```

To manage your Vault namespaces in Terraform:

1. Use the `vault namespace list` command to identify any unmanaged namespaces
   that you need to migrate. For example:

    ```shell-session
    $ vault namespace list

    Keys
    ----
    admin/
    ```

1. Create a new Terraform Vault Provider resource file called
   `vault_namespaces.tf` that defines `vault_namespace` resources for each of
   the new or existing namespaces resources you want to manage.

   For example, to migrate the `admin` namespace in the example and create a new
   `dev` namespace:

    ```hcl
    resource "vault_namespace" "admin_ns" {
      path = "admin"
    }

    resource "vault_namespace" "dev_ns" {
      path = "dev"
    }
    ```

## Step 2: Create a resource file for secret engines

Terraform Vault provider supports discrete types for the different
[auth](https://registry.terraform.io/providers/hashicorp/vault/latest/docs#vault-authentication-configuration-options),
[secret](https://registry.terraform.io/providers/hashicorp/vault/latest/docs/resources/mount),
and [database](https://registry.terraform.io/providers/hashicorp/vault/latest/docs/resources/database_secrets_mount)
plugin types in Vault.

To migrate a secret engine, use the `vault_mount` resource type:

```hcl
resource "vault_mount" "<TERRAFORM_RESOURCE_NAME>" {
  path = "<VAULT_NAMESPACE>"
  type = "<VAULT_PLUGIN_TYPE>"
}
```

To manage your Vault secret engines in Terraform:

1. Use the `vault secret list` command to identify any unmanaged secret engines
   that you need to migrate. For example:

    ```shell-session
    $ vault secrets list | grep -vEw '(cubbyhole|identity|sys)'

    Path          Type         Accessor              Description
    ----          ----         --------              -----------
    transit/      transit      transit_8291b949      n/a
    ```

1. Use the `-namespace` flag to check for unmanaged secret engines under any
   namespaces you identified in the previous step. For example, to check for
   secret engines under the `admin` namespace:

    ```shell-session
    $ vault secrets list -namespace=admin | grep -vEw '(cubbyhole|identity|sys)'

    Path           Type            Accessor                 Description
    ----           ----            --------                 -----------
    admin_keys/    kv              kv_87edfc65              n/a
    ```

1. Create a new Terraform Vault Provider resource file called `vault_secrets.tf`
   that defines `vault_mount` resources for each of the new or existing secret
   engines you want to manage.

   For example, to  migrate the `transit` and `admin_keys` secret engines in the
   example and enable a new `kv` engine under the new `dev` namespace called
   `dev_keys`:

    ```hcl
    resource "vault_mount" "transit_plugin" {
      path = "transit"
      type = "transit"
    }

    resource "vault_mount" "admin_keys_plugin" {
      namespace = vault_namespace.admin_ns.path
      path = "admin_keys"
      type = "kv"
      options = {
        version = "2"
      }
    }

    resource "vault_mount" "dev_keys_plugin" {
      namespace = vault_namespace.dev_ns.path
      path = "dev_keys"
      type = "kv"
      options = {
        version = "2"
      }
    }
    ```

## Step 3: Create a resource file for policies

Terraform Vault provider supports a `vault_policy` resource type for
managing Vault policies:

```hcl
resource "vault_policy" "<TERRAFORM_RESOURCE_NAME>" {
  name = "<VAULT_POLICY_NAME>"
  policy = <<EOT
    <VAULT_POLICY_DEFINITION>
  EOT
}
```

To manage your Vault policies in Terraform:

1. Use the `vault policy list` command to identify any unmanaged policies that
   you need to migrate. For example:

    ```shell-session
    $ vault policy list | grep -vEw 'root'

    default
    ```

1. Create a Terraform Vault Provider resource file called `vault_policies.tf`
   that defines `vault_mount` resources for each policy resource you want to
   manage in Terraform. You can use the following `bash` code to write all
   your existing, non-root policies to the file:

  ```shell-session
  for vpolicy in $(vault policy list | grep -vw root) ; do
    echo "resource \"vault_policy\" \"vault_$vpolicy\" {"
    echo "  name = \"$vpolicy\""
    echo "  policy = <<EOT"
    vault policy read $vpolicy
    echo "EOT"
    echo "}"
    echo ""
  done > vault_policies.tf
  ```

1. Update the `vault_policies.tf` file with any new policies you want to add.
   For example, to create a policy for the example `dev_keys` secret engine:

   ```hcl
   resource "vault_policy" "dev_team_policy" {
   name = "dev_team"

   policy = <<EOT
    path vault_mount.dev_keys_plugin.path {
      capabilities = ["create", "update"]
    }
    EOT
   }
   ```

## Step 4: Update your Terraform configuration

1. Create a `vault` directory wherever you keep your deployment configuration
   files for Terraform.

1. Save your new resource files to your new Vault configuration directory.

1. Use `terraform fmt` to adjust the formatting (if needed) of your new
   configuration files:
  ```shell-session
  $ terraform fmt

  vault_namespaces.tf
  vault_secrets.tf
  vault_policies.tf
  ```

1. Use `terraform validate` to confirm the new configuration is valid:
  ```shell-session
  $ terraform validate

  Success! The configuration is valid.
  ```

## Step 5: Import preexisting root-level resources

Use the `terraform import` command to import the preexisting root-level resources.

For example, import the `admin` namespace, `default` policy, and `transit`
plugin from the previous steps:

```shell-session
$ terraform import vault_namespace.admin_ns admin

vault_namespace.admin_ns: Importing from ID "admin"...
vault_namespace.admin_ns: Import prepared!
  Prepared vault_namespace for import
vault_namespace.admin_ns: Refreshing state... [id=admin]

Import successful!

The resources that were imported are shown above. These resources are now in
your Terraform state and will henceforth be managed by Terraform.
```

```shell-session
$ terraform import vault_policy.default_policy default

vault_policy.default_policy: Importing from ID "default"...
vault_policy.default_policy: Import prepared!
  Prepared vault_policy for import
vault_policy.default_policy: Refreshing state... [id=default]

Import successful!

The resources that were imported are shown above. These resources are now in
your Terraform state and will henceforth be managed by Terraform.
```

```shell-session
$ terraform import vault_mount.transit_plugin transit

vault_mount.transit_plugin: Importing from ID "transit"...
vault_mount.transit_plugin: Import prepared!
  Prepared vault_mount for import
vault_mount.transit_plugin: Refreshing state... [id=transit]

Import successful!

The resources that were imported are shown above. These resources are now in
your Terraform state and will henceforth be managed by Terraform.
```

## Step 6: Import preexisting nested resources

To import resources that belong to a previously unmanaged namespace, you must
set the `TERRAFORM_VAULT_NAMESPACE_IMPORT` environment variable before importing.

For example, to import the `admin_keys` secret engine from the `admin` namespace:

1. Set `TERRAFORM_VAULT_NAMESPACE_IMPORT` to the `admin` Vault namespace:

  ```shell-session
  $ export TERRAFORM_VAULT_NAMESPACE_IMPORT="admin"
  ```

1. Import the `vault_mount` resource `admin_keys`:

  ```shell-session
  $ terraform import vault_mount.admin_keys_plugin admin_keys

  vault_mount.admin_keys_plugin: Importing from ID "admin_keys"...
  vault_mount.admin_keys_plugin: Import prepared!
    Prepared vault_mount for import
  vault_mount.admin_keys_plugin: Refreshing state... [id=admin_keys]

  Import successful!

  The resources that were imported are shown above. These resources are now in
  your Terraform state and will henceforth be managed by Terraform.
  ```

1. Unset the `TERRAFORM_VAULT_NAMESPACE_IMPORT` variable when you finish
   importing child resources:

  ```shell-session
  $ unset TERRAFORM_VAULT_NAMESPACE_IMPORT
  ```

## Step 6: Verify the import

1. Use the `terraform state show` command to check your Terraform state file and
   verify the resources imported successfully. For example, to check the
   `admin_keys` resource:

  ```shell-session
  $ terraform state show vault_mount.admin_keys_plugin

  # vault_mount.admin_keys_plugin:
  resource "vault_mount" "admin_keys" {
      accessor                     = "kv_87edfc65"
      allowed_managed_keys         = []
      audit_non_hmac_request_keys  = []
      audit_non_hmac_response_keys = []
      default_lease_ttl_seconds    = 0
      description                  = null
      external_entropy_access      = false
      id                           = "admin_keys"
      local                        = false
      max_lease_ttl_seconds        = 0
      namespace                    = "admin"
      options                      = {
          "version" = "2"
      }
      path                         = "admin_keys"
      seal_wrap                    = false
      type                         = "kv"
  ```

1. For each of the migrated resources, compare the `accessor` value from your
   Terraform state to the accessor value in Vault. For example, to confirm the
   accessor for `admin_keys`:

  ```shell-session
  $ vault secrets list -namespace="admin" | grep -vEw '(cubbyhole|identity|sys)'

  Path           Type            Accessor                 Description
  ----           ----            --------                 -----------
  admin_keys/    kv              kv_87edfc65              n/a
  ```

## Step 7: Add new Vault resources

1. Run `terraform plan` to confirm the new resources that Terraform will manage:

    ```shell-session
    $ terraform plan

    vault_policy.default_policy: Refreshing state... [id=default]
    vault_namespace.admin_ns: Refreshing state... [id=admin/]
    vault_mount.transit_plugin: Refreshing state... [id=transit]
    vault_mount.admin_keys_plugin: Refreshing state... [id=admin_keys]

    Terraform used the selected providers to generate the following execution plan.
    Resource actions are indicated with the following symbols:
      + create

    Terraform will perform the following actions:

      # vault_mount.dev_keys_plugin will be created
      + resource "vault_mount" "dev_keys" {
          + accessor                     = (known after apply)
          + audit_non_hmac_request_keys  = (known after apply)
          + audit_non_hmac_response_keys = (known after apply)
          + default_lease_ttl_seconds    = (known after apply)
          + external_entropy_access      = false
          + id                           = (known after apply)
          + max_lease_ttl_seconds        = (known after apply)
          + namespace                    = "dev"
          + options                      = {
              + "version" = "2"
            }
          + path                         = "dev_keys"
          + seal_wrap                    = (known after apply)
          + type                         = "kv"
        }

      # vault_namespace.dev_ns will be created
      + resource "vault_namespace" "dev" {
          + custom_metadata = (known after apply)
          + id              = (known after apply)
          + namespace_id    = (known after apply)
          + path            = "dev"
          + path_fq         = (known after apply)
        }

      # vault_policy.dev_team will be created
      + resource "vault_policy" "dev_team" {
          + id     = (known after apply)
          + name   = "dev_team"
          + policy = <<-EOT
                path vault_mount.dev_keys_plugin.path {
                      capabilities = ["create", "update"]
                    }
            EOT
        }

    Plan: 3 to add, 0 to change, 0 to destroy.
    ```

1. Run `terraform apply` to create the new resources:

  ```shell-session
  $ terraform apply

  vault_namespace.dev_ns: Creating...
  vault_namespace.dev_ns: Creation complete after 0s [id=dev/]
  vault_mount.dev_keys_plugin: Creating...
  vault_mount.dev_keys_plugin: Creation complete after 0s [id=dev_keys]
  vault_policy.dev_team: Creating...
  vault_policy.dev_team: Creation complete after 0s [id=dev_team]

  Apply complete! Resources: 3 added, 0 changed, 0 destroyed.
  ```

1. Use the `terraform state show` command to check your Terraform state file and
   verify the new resources created successfully. For example, to check the
   `dev_keys` resource:

  ```shell-session
  $ terraform state show vault_mount.dev_keys_plugin

  # vault_mount.dev_keys_plugin:
  resource "vault_mount" "dev_keys" {
      accessor                     = "kv_b3d2dd6f"
      allowed_managed_keys         = []
      audit_non_hmac_request_keys  = []
      audit_non_hmac_response_keys = []
      default_lease_ttl_seconds    = 0
      description                  = null
      external_entropy_access      = false
      id                           = "dev_keys"
      local                        = false
      max_lease_ttl_seconds        = 0
      namespace                    = "dev"
      options                      = {
          "version" = "2"
      }
      path                         = "dev_keys"
      seal_wrap                    = false
      type                         = "kv"
  }
  ```

1. Confirm that your Vault instance can use the new resources. For example, to
   confirm the `dev_keys` resources:

  ```shell-session
  $ vault secrets list -namespace="dev" | grep -vEw '(cubbyhole|identity|sys)'

  Path          Type            Accessor                 Description
  ----          ----            --------                 -----------
  dev_keys/     kv              kv_b3d2dd6f              n/a
  ```

## Next steps

1. Review the [best practices for programmatic Vault management](/vault/docs/configuration/programmatic-best-practices).

layout  docs page title  Manage Vault resources programmatically description       Step by step instructions for managing Vault resources programmatically with   Terraform        Manage Vault resources programmatically with Terraform  Use Terraform to manage policies  namespaces  and plugins in Vault      Before you start      You must have  Terraform installed   terraform install         You must have the  Terraform Vault provider  https   registry terraform io providers hashicorp vault latest  configured        You must have sufficient access to run Terraform         You must have a  Vault server running   vault tutorials getting started getting started dev server         Step 1  Create a resource file for namespaces  Terraform Vault provider supports a  vault namespace  resource type for managing Vault namespaces      hcl resource  vault namespace    TERRAFORM RESOURCE NAME       path     VAULT NAMESPACE          To manage your Vault namespaces in Terraform   1  Use the  vault namespace list  command to identify any unmanaged namespaces    that you need to migrate  For example          shell session       vault namespace list      Keys              admin           1  Create a new Terraform Vault Provider resource file called     vault namespaces tf  that defines  vault namespace  resources for each of    the new or existing namespaces resources you want to manage         For example  to migrate the  admin  namespace in the example and create a new     dev  namespace          hcl     resource  vault namespace   admin ns          path    admin             resource  vault namespace   dev ns          path    dev                    Step 2  Create a resource file for secret engines  Terraform Vault provider supports discrete types for the different   auth  https   registry terraform io providers hashicorp vault latest docs vault authentication configuration options    secret  https   registry terraform io providers hashicorp vault latest docs resources mount   and  database  https   registry terraform io providers hashicorp vault latest docs resources database secrets mount  plugin types in Vault   To migrate a secret engine  use the  vault mount  resource type      hcl resource  vault mount    TERRAFORM RESOURCE NAME       path     VAULT NAMESPACE     type     VAULT PLUGIN TYPE          To manage your Vault secret engines in Terraform   1  Use the  vault secret list  command to identify any unmanaged secret engines    that you need to migrate  For example          shell session       vault secrets list   grep  vEw   cubbyhole identity sys        Path          Type         Accessor              Description                                                                      transit       transit      transit 8291b949      n a          1  Use the   namespace  flag to check for unmanaged secret engines under any    namespaces you identified in the previous step  For example  to check for    secret engines under the  admin  namespace          shell session       vault secrets list  namespace admin   grep  vEw   cubbyhole identity sys        Path           Type            Accessor                 Description                                                                             admin keys     kv              kv 87edfc65              n a          1  Create a new Terraform Vault Provider resource file called  vault secrets tf     that defines  vault mount  resources for each of the new or existing secret    engines you want to manage         For example  to  migrate the  transit  and  admin keys  secret engines in the    example and enable a new  kv  engine under the new  dev  namespace called     dev keys           hcl     resource  vault mount   transit plugin          path    transit        type    transit             resource  vault mount   admin keys plugin          namespace   vault namespace admin ns path       path    admin keys        type    kv        options             version    2                     resource  vault mount   dev keys plugin          namespace   vault namespace dev ns path       path    dev keys        type    kv        options             version    2                            Step 3  Create a resource file for policies  Terraform Vault provider supports a  vault policy  resource type for managing Vault policies      hcl resource  vault policy    TERRAFORM RESOURCE NAME       name     VAULT POLICY NAME     policy     EOT      VAULT POLICY DEFINITION    EOT        To manage your Vault policies in Terraform   1  Use the  vault policy list  command to identify any unmanaged policies that    you need to migrate  For example          shell session       vault policy list   grep  vEw  root       default          1  Create a Terraform Vault Provider resource file called  vault policies tf     that defines  vault mount  resources for each policy resource you want to    manage in Terraform  You can use the following  bash  code to write all    your existing  non root policies to the file        shell session   for vpolicy in   vault policy list   grep  vw root    do     echo  resource   vault policy     vault  vpolicy          echo    name      vpolicy        echo    policy     EOT      vault policy read  vpolicy     echo  EOT      echo         echo      done   vault policies tf        1  Update the  vault policies tf  file with any new policies you want to add     For example  to create a policy for the example  dev keys  secret engine         hcl    resource  vault policy   dev team policy       name    dev team      policy     EOT     path vault mount dev keys plugin path         capabilities     create    update             EOT                  Step 4  Update your Terraform configuration  1  Create a  vault  directory wherever you keep your deployment configuration    files for Terraform   1  Save your new resource files to your new Vault configuration directory   1  Use  terraform fmt  to adjust the formatting  if needed  of your new    configuration files       shell session     terraform fmt    vault namespaces tf   vault secrets tf   vault policies tf        1  Use  terraform validate  to confirm the new configuration is valid       shell session     terraform validate       Success  The configuration is valid            Step 5  Import preexisting root level resources  Use the  terraform import  command to import the preexisting root level resources   For example  import the  admin  namespace   default  policy  and  transit  plugin from the previous steps      shell session   terraform import vault namespace admin ns admin  vault namespace admin ns  Importing from ID  admin     vault namespace admin ns  Import prepared    Prepared vault namespace for import vault namespace admin ns  Refreshing state     id admin   Import successful   The resources that were imported are shown above  These resources are now in your Terraform state and will henceforth be managed by Terraform          shell session   terraform import vault policy default policy default  vault policy default policy  Importing from ID  default     vault policy default policy  Import prepared    Prepared vault policy for import vault policy default policy  Refreshing state     id default   Import successful   The resources that were imported are shown above  These resources are now in your Terraform state and will henceforth be managed by Terraform          shell session   terraform import vault mount transit plugin transit  vault mount transit plugin  Importing from ID  transit     vault mount transit plugin  Import prepared    Prepared vault mount for import vault mount transit plugin  Refreshing state     id transit   Import successful   The resources that were imported are shown above  These resources are now in your Terraform state and will henceforth be managed by Terraform          Step 6  Import preexisting nested resources  To import resources that belong to a previously unmanaged namespace  you must set the  TERRAFORM VAULT NAMESPACE IMPORT  environment variable before importing   For example  to import the  admin keys  secret engine from the  admin  namespace   1  Set  TERRAFORM VAULT NAMESPACE IMPORT  to the  admin  Vault namespace        shell session     export TERRAFORM VAULT NAMESPACE IMPORT  admin         1  Import the  vault mount  resource  admin keys         shell session     terraform import vault mount admin keys plugin admin keys    vault mount admin keys plugin  Importing from ID  admin keys       vault mount admin keys plugin  Import prepared      Prepared vault mount for import   vault mount admin keys plugin  Refreshing state     id admin keys     Import successful     The resources that were imported are shown above  These resources are now in   your Terraform state and will henceforth be managed by Terraform         1  Unset the  TERRAFORM VAULT NAMESPACE IMPORT  variable when you finish    importing child resources        shell session     unset TERRAFORM VAULT NAMESPACE IMPORT           Step 6  Verify the import  1  Use the  terraform state show  command to check your Terraform state file and    verify the resources imported successfully  For example  to check the     admin keys  resource        shell session     terraform state show vault mount admin keys plugin      vault mount admin keys plugin    resource  vault mount   admin keys          accessor                        kv 87edfc65        allowed managed keys                    audit non hmac request keys             audit non hmac response keys            default lease ttl seconds      0       description                    null       external entropy access        false       id                              admin keys        local                          false       max lease ttl seconds          0       namespace                       admin        options                                     version     2                path                            admin keys        seal wrap                      false       type                            kv         1  For each of the migrated resources  compare the  accessor  value from your    Terraform state to the accessor value in Vault  For example  to confirm the    accessor for  admin keys         shell session     vault secrets list  namespace  admin    grep  vEw   cubbyhole identity sys      Path           Type            Accessor                 Description                                                                         admin keys     kv              kv 87edfc65              n a            Step 7  Add new Vault resources  1  Run  terraform plan  to confirm the new resources that Terraform will manage          shell session       terraform plan      vault policy default policy  Refreshing state     id default      vault namespace admin ns  Refreshing state     id admin       vault mount transit plugin  Refreshing state     id transit      vault mount admin keys plugin  Refreshing state     id admin keys       Terraform used the selected providers to generate the following execution plan      Resource actions are indicated with the following symbols          create      Terraform will perform the following actions           vault mount dev keys plugin will be created         resource  vault mount   dev keys                accessor                        known after apply              audit non hmac request keys     known after apply              audit non hmac response keys    known after apply              default lease ttl seconds       known after apply              external entropy access        false             id                              known after apply              max lease ttl seconds           known after apply              namespace                       dev              options                                           version     2                            path                            dev keys              seal wrap                       known after apply              type                            kv                     vault namespace dev ns will be created         resource  vault namespace   dev                custom metadata    known after apply              id                 known after apply              namespace id       known after apply              path               dev              path fq            known after apply                     vault policy dev team will be created         resource  vault policy   dev team                id        known after apply              name      dev team              policy      EOT                 path vault mount dev keys plugin path                         capabilities     create    update                                     EOT                Plan  3 to add  0 to change  0 to destroy           1  Run  terraform apply  to create the new resources        shell session     terraform apply    vault namespace dev ns  Creating      vault namespace dev ns  Creation complete after 0s  id dev     vault mount dev keys plugin  Creating      vault mount dev keys plugin  Creation complete after 0s  id dev keys    vault policy dev team  Creating      vault policy dev team  Creation complete after 0s  id dev team     Apply complete  Resources  3 added  0 changed  0 destroyed         1  Use the  terraform state show  command to check your Terraform state file and    verify the new resources created successfully  For example  to check the     dev keys  resource        shell session     terraform state show vault mount dev keys plugin      vault mount dev keys plugin    resource  vault mount   dev keys          accessor                        kv b3d2dd6f        allowed managed keys                    audit non hmac request keys             audit non hmac response keys            default lease ttl seconds      0       description                    null       external entropy access        false       id                              dev keys        local                          false       max lease ttl seconds          0       namespace                       dev        options                                     version     2                path                            dev keys        seal wrap                      false       type                            kv             1  Confirm that your Vault instance can use the new resources  For example  to    confirm the  dev keys  resources        shell session     vault secrets list  namespace  dev    grep  vEw   cubbyhole identity sys      Path          Type            Accessor                 Description                                                                        dev keys      kv              kv b3d2dd6f              n a            Next steps  1  Review the  best practices for programmatic Vault management   vault docs configuration programmatic best practices


vault metrics to upstream systems telemetry stanza layout docs page title Telemetry Configuration The telemetry stanza specifies various configurations for Vault to publish

Answer:
---
layout: docs
page_title: Telemetry - Configuration
description: |-
  The telemetry stanza specifies various configurations for Vault to publish
  metrics to upstream systems.
---

# `telemetry` stanza

The `telemetry` stanza specifies various configurations for Vault to publish
metrics to upstream systems. Available Vault metrics can be found in the
[Telemetry internals documentation](/vault/docs/internals/telemetry).

```hcl
telemetry {
  statsite_address = "statsite.company.local:8125"
}
```

## `telemetry` parameters

Due to the number of configurable parameters to the `telemetry` stanza,
parameters on this page are grouped by the telemetry provider.

### Common

The following options are available on all telemetry configurations.

- `usage_gauge_period` `(string: "10m")` - Specifies the interval at which high-cardinality
  usage data is collected, such as token counts, entity counts, and secret counts.
   A value of "none" disables the collection.  Uses [duration format strings](/vault/docs/concepts/duration-format).
- `maximum_gauge_cardinality` `(int: 500)` - The maximum cardinality of gauge labels.
- `disable_hostname` `(bool: false)` - Specifies if gauge values should be
  prefixed with the local hostname.
- `enable_hostname_label` `(bool: false)` - Specifies if all metric values should
  contain the `host` label with the local hostname. It is recommended to enable
  `disable_hostname` if this option is used.
- `metrics_prefix` `(string: "vault")` - Specifies the prefix used for metric vaules. By default, metrics are prefixed with "vault".
- `lease_metrics_epsilon` `(string: "1h")` - Specifies the size of the bucket used to measure future
  lease expiration. For example, for the default value of 1 hour, the `vault.expire.leases.by_expiration`
  metric will aggregate the total number of expiring leases for 1 hour buckets, starting from the current time.
  Note that leases are put into buckets by rounding. For example, if `lease_metrics_epsilon` is set to 1h and
  lease A expires 25 minutes from now, and lease B expires 35 minutes from now, then lease A will be in the first
  bucket, which corresponds to 0-30 minutes, and lease B will be in the second bucket, which corresponds to 31-90
  minutes. Uses [duration format strings](/vault/docs/concepts/duration-format).
- `num_lease_metrics_buckets` `(int: 168)` - The number of expiry buckets for leases. For the default value, for
  example, 168 value labels for the `vault.expire.leases.by_expiration` metric will be reported, where each value
  each bucket is separated in time by the `lease_metrics_epsilon` parameter. For the default 1 hour value of
  `lease_metrics_epsilon` and the default value of `num_lease_metrics_buckets`, `vault.expire.leases.by_expiration`
  will report the total number of leases expiring within each hour from the current time to one week from the current time.
- `add_lease_metrics_namespace_labels` `(bool: false)` - If this value is set to true, then `vault.expire.leases.by_expiration`
  will break down expiring leases by both time and namespace. This parameter is disabled by default because enabling it can lead
  to a large-cardinality metric.
- `add_mount_point_rollback_metrics` `(bool: false)` - If this value is set to true, then `vault.rollback.attempt.{MOUNT_POINT}`
  and `vault.route.rollback.{MOUNT_POINT}` metrics will be reported for every mount point. If this parameter is false, then
  `vault.rollback.attempt` and `vault.route.rollback` metrics (which do not have the mount point in the metric name)
  will be reported instead. This parameter is disabled by default starting in Vault 1.15 due to the high cardinality of
  these metrics.
- `filter_default` `(bool: true)` - This controls whether to allow metrics that have not been specified by the filter.
  Defaults to `true`, which will allow all metrics when no filters are provided.
  When set to `false` with no filters, no metrics will be sent.
- `prefix_filter` `(string array: [])` - This is a list of filter rules to apply for allowing/blocking metrics by
  prefix in the following format:
  ```json
  ["+vault.token", "-vault.expire", "+vault.expire.num_leases"]
  ```
  A leading "**+**" will enable any metrics with the given prefix, and a leading "**-**" will block them.
  If there is overlap between two rules, the more specific rule will take precedence. Blocking will take priority if the same prefix is listed multiple times.

### `statsite`

These `telemetry` parameters apply to
[statsite](https://github.com/armon/statsite).

- `statsite_address` `(string: "")` - Specifies the address of a statsite server
  to forward metrics data to.

```hcl
telemetry {
  statsite_address = "statsite.company.local:8125"
}
```

### `statsd`

These `telemetry` parameters apply to
[statsd](https://github.com/etsy/statsd).

- `statsd_address` `(string: "")` - Specifies the address of a statsd server to
  forward metrics to.

```hcl
telemetry {
  statsd_address = "statsd.company.local:8125"
}
```

### `circonus`

These `telemetry` parameters apply to [Circonus](http://circonus.com/).

- `circonus_api_token` `(string: "")` - Specifies a valid Circonus API Token
  used to create/manage check. If provided, metric management is enabled.

- `circonus_api_app` `(string: "nomad")` - Specifies a valid app name associated
  with the API token.

- `circonus_api_url` `(string: "https://api.circonus.com/v2")` - Specifies the
  base URL to use for contacting the Circonus API.

- `circonus_submission_interval` `(string: "10s")` - Specifies the interval at
  which metrics are submitted to Circonus.

- `circonus_submission_url` `(string: "")` - Specifies the
  `check.config.submission_url` field, of a Check API object, from a previously
  created HTTPTRAP check.

- `circonus_check_id` `(string: "")` - Specifies the Check ID (**not check
  bundle**) from a previously created HTTPTRAP check. The numeric portion of the
  `check._cid` field in the Check API object.

- `circonus_check_force_metric_activation` `(bool: false)` - Specifies if force
  activation of metrics which already exist and are not currently active. If
  check management is enabled, the default behavior is to add new metrics as
  they are encountered. If the metric already exists in the check, it will
  not be activated. This setting overrides that behavior.

- `circonus_check_instance_id` `(string: "<hostname>:<application>")` - Serves
  to uniquely identify the metrics coming from this _instance_. It can be used
  to maintain metric continuity with transient or ephemeral instances as they
  move around within an infrastructure. By default, this is set to
  hostname:application name (e.g. "host123:nomad").

- `circonus_check_search_tag` `(string: <service>:<application>)` - Specifies a
  special tag which, when coupled with the instance id, helps to narrow down the
  search results when neither a Submission URL or Check ID is provided. By
  default, this is set to service:app (e.g. "service:nomad").

- `circonus_check_display_name` `(string: "")` - Specifies a name to give a
  check when it is created. This name is displayed in the Circonus UI Checks
  list.

- `circonus_check_tags` `(string: "")` - Comma separated list of additional
  tags to add to a check when it is created.

- `circonus_broker_id` `(string: "")` - Specifies the ID of a specific Circonus
  Broker to use when creating a new check. The numeric portion of `broker._cid`
  field in a Broker API object. If metric management is enabled and neither a
  Submission URL nor Check ID is provided, an attempt will be made to search for
  an existing check using Instance ID and Search Tag. If one is not found, a new
  HTTPTRAP check will be created. By default, this is a random
  Enterprise Broker is selected, or, the default Circonus Public Broker.

- `circonus_broker_select_tag` `(string: "")` - Specifies a special tag which
  will be used to select a Circonus Broker when a Broker ID is not provided. The
  best use of this is to as a hint for which broker should be used based on
  _where_ this particular instance is running (e.g. a specific geo location or
  datacenter, dc:sfo).

### `dogstatsd`

These `telemetry` parameters apply to
[DogStatsD](http://docs.datadoghq.com/guides/dogstatsd/).

- `dogstatsd_addr` `(string: "")` - This provides the address of a DogStatsD
  instance. DogStatsD is a protocol-compatible flavor of statsd, with the added
  ability to decorate metrics with tags and event information. If provided,
  Vault will send various telemetry information to that instance for
  aggregation. This can be used to capture runtime information.

* `dogstatsd_tags` `(string array: [])` - This provides a list of global tags
  that will be added to all telemetry packets sent to DogStatsD. It is a list
  of strings, where each string looks like "my_tag_name:my_tag_value".

### `prometheus`

These `telemetry` parameters apply to
[prometheus](https://prometheus.io).

- `prometheus_retention_time` `(string: "24h")` - Specifies the amount of time that
  Prometheus metrics are retained in memory. Setting this to 0 will disable Prometheus telemetry.
- `disable_hostname` `(bool: false)` - It is recommended to also enable the option
  `disable_hostname` to avoid having prefixed metrics with hostname.

The `/v1/sys/metrics` endpoint is only accessible on active nodes
and automatically disabled on standby nodes. You can enable the `/v1/sys/metrics`
endpoint on standby nodes by [enabling unauthenticated metrics access][telemetry-tcp].
Standby nodes will never forward a request to `/v1/sys/metrics` to the active
node. If unauthenticated metrics access is enabled, the standby node will
respond with its own metrics. If unauthenticated metrics access is not enabled,
then a standby node will attempt to service the request but fail and then
redirect the request to the active node.

Querying `/v1/sys/metrics` with one of the following headers:

 - `Accept: prometheus/telemetry`
 - `Accept: application/openmetrics-text`

will return Prometheus formatted results. Most Prometheus servers automatically
query scrape targets with these headers by default.

A Vault token is required with `capabilities = ["read", "list"]` to
/v1/sys/metrics. The Prometheus `bearer_token` or `bearer_token_file` options
must be added to the scrape job.

Vault does not use the default Prometheus path, so Prometheus must be configured
to scrape `v1/sys/metrics` instead of the default scrape path.

An example job_name stanza required in the [Prometheus config](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config) is provided below.

```
# prometheus.yml
scrape_configs:
  - job_name: 'vault'
    metrics_path: "/v1/sys/metrics"
    scheme: https
    tls_config:
      ca_file: your_ca_here.pem
    bearer_token: "your_vault_token_here"
    static_configs:
    - targets: ['your_vault_server_here:8200']
```

An example telemetry configuration to be added to Vault's configuration file is shown below:

```hcl
telemetry {
  prometheus_retention_time = "30s"
  disable_hostname = true
}
```

### `stackdriver`

These `telemetry` parameters apply to [Stackdriver Monitoring](https://cloud.google.com/monitoring/).

The Stackdriver telemetry provider uses the official Google Cloud Golang SDK. This means
it supports the common ways of
[providing credentials to Google Cloud](https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application).

To use this telemetry provider, the service account must have the following
minimum scope(s):

```text
https://www.googleapis.com/auth/cloud-platform
https://www.googleapis.com/auth/monitoring
https://www.googleapis.com/auth/monitoring.write
```

And the following IAM role(s):

```text
roles/monitoring.metricWriter
```

- `stackdriver_project_id` `(string: "")` - The Google Cloud ProjectID to send telemetry data to.
- `stackdriver_location` `(string: "")` - The GCP or AWS region of the monitored resource.
- `stackdriver_namespace` `(string: "")` - A namespace identifier for the telemetry data.
- `stackdriver_debug_logs` `(bool: "false")` - Specifies if Vault writes additional stackdriver
related debug logs to standard error output (stderr).

It is recommended to also enable the option `disable_hostname` to avoid having prefixed
metrics with hostname and enable instead `enable_hostname_label`.

```hcl
telemetry {
  stackdriver_project_id = "my-test-project"
  stackdriver_location = "us-east1-a"
  stackdriver_namespace = "vault-cluster-a"
  disable_hostname = true
  enable_hostname_label = true
}
```

Metrics from Vault can be found in [Metrics Explorer](https://cloud.google.com/monitoring/charts/metrics-explorer).
All those metrics are shown with a resource type of `generic_task`, and the metric name
is prefixed with `custom.googleapis.com/go-metrics/`.

[telemetry-tcp]: /vault/docs/configuration/listener/tcp#telemetry-parameters

layout  docs page title  Telemetry   Configuration description       The telemetry stanza specifies various configurations for Vault to publish   metrics to upstream systems          telemetry  stanza  The  telemetry  stanza specifies various configurations for Vault to publish metrics to upstream systems  Available Vault metrics can be found in the  Telemetry internals documentation   vault docs internals telemetry       hcl telemetry     statsite address    statsite company local 8125             telemetry  parameters  Due to the number of configurable parameters to the  telemetry  stanza  parameters on this page are grouped by the telemetry provider       Common  The following options are available on all telemetry configurations      usage gauge period    string   10m      Specifies the interval at which high cardinality   usage data is collected  such as token counts  entity counts  and secret counts     A value of  none  disables the collection   Uses  duration format strings   vault docs concepts duration format      maximum gauge cardinality    int  500     The maximum cardinality of gauge labels     disable hostname    bool  false     Specifies if gauge values should be   prefixed with the local hostname     enable hostname label    bool  false     Specifies if all metric values should   contain the  host  label with the local hostname  It is recommended to enable    disable hostname  if this option is used     metrics prefix    string   vault      Specifies the prefix used for metric vaules  By default  metrics are prefixed with  vault      lease metrics epsilon    string   1h      Specifies the size of the bucket used to measure future   lease expiration  For example  for the default value of 1 hour  the  vault expire leases by expiration    metric will aggregate the total number of expiring leases for 1 hour buckets  starting from the current time    Note that leases are put into buckets by rounding  For example  if  lease metrics epsilon  is set to 1h and   lease A expires 25 minutes from now  and lease B expires 35 minutes from now  then lease A will be in the first   bucket  which corresponds to 0 30 minutes  and lease B will be in the second bucket  which corresponds to 31 90   minutes  Uses  duration format strings   vault docs concepts duration format      num lease metrics buckets    int  168     The number of expiry buckets for leases  For the default value  for   example  168 value labels for the  vault expire leases by expiration  metric will be reported  where each value   each bucket is separated in time by the  lease metrics epsilon  parameter  For the default 1 hour value of    lease metrics epsilon  and the default value of  num lease metrics buckets    vault expire leases by expiration    will report the total number of leases expiring within each hour from the current time to one week from the current time     add lease metrics namespace labels    bool  false     If this value is set to true  then  vault expire leases by expiration    will break down expiring leases by both time and namespace  This parameter is disabled by default because enabling it can lead   to a large cardinality metric     add mount point rollback metrics    bool  false     If this value is set to true  then  vault rollback attempt  MOUNT POINT     and  vault route rollback  MOUNT POINT   metrics will be reported for every mount point  If this parameter is false  then    vault rollback attempt  and  vault route rollback  metrics  which do not have the mount point in the metric name    will be reported instead  This parameter is disabled by default starting in Vault 1 15 due to the high cardinality of   these metrics     filter default    bool  true     This controls whether to allow metrics that have not been specified by the filter    Defaults to  true   which will allow all metrics when no filters are provided    When set to  false  with no filters  no metrics will be sent     prefix filter    string array         This is a list of filter rules to apply for allowing blocking metrics by   prefix in the following format       json      vault token     vault expire     vault expire num leases           A leading         will enable any metrics with the given prefix  and a leading         will block them    If there is overlap between two rules  the more specific rule will take precedence  Blocking will take priority if the same prefix is listed multiple times         statsite   These  telemetry  parameters apply to  statsite  https   github com armon statsite       statsite address    string         Specifies the address of a statsite server   to forward metrics data to      hcl telemetry     statsite address    statsite company local 8125              statsd   These  telemetry  parameters apply to  statsd  https   github com etsy statsd       statsd address    string         Specifies the address of a statsd server to   forward metrics to      hcl telemetry     statsd address    statsd company local 8125              circonus   These  telemetry  parameters apply to  Circonus  http   circonus com        circonus api token    string         Specifies a valid Circonus API Token   used to create manage check  If provided  metric management is enabled      circonus api app    string   nomad      Specifies a valid app name associated   with the API token      circonus api url    string   https   api circonus com v2      Specifies the   base URL to use for contacting the Circonus API      circonus submission interval    string   10s      Specifies the interval at   which metrics are submitted to Circonus      circonus submission url    string         Specifies the    check config submission url  field  of a Check API object  from a previously   created HTTPTRAP check      circonus check id    string         Specifies the Check ID    not check   bundle    from a previously created HTTPTRAP check  The numeric portion of the    check  cid  field in the Check API object      circonus check force metric activation    bool  false     Specifies if force   activation of metrics which already exist and are not currently active  If   check management is enabled  the default behavior is to add new metrics as   they are encountered  If the metric already exists in the check  it will   not be activated  This setting overrides that behavior      circonus check instance id    string    hostname   application       Serves   to uniquely identify the metrics coming from this  instance   It can be used   to maintain metric continuity with transient or ephemeral instances as they   move around within an infrastructure  By default  this is set to   hostname application name  e g   host123 nomad        circonus check search tag    string   service   application      Specifies a   special tag which  when coupled with the instance id  helps to narrow down the   search results when neither a Submission URL or Check ID is provided  By   default  this is set to service app  e g   service nomad        circonus check display name    string         Specifies a name to give a   check when it is created  This name is displayed in the Circonus UI Checks   list      circonus check tags    string         Comma separated list of additional   tags to add to a check when it is created      circonus broker id    string         Specifies the ID of a specific Circonus   Broker to use when creating a new check  The numeric portion of  broker  cid    field in a Broker API object  If metric management is enabled and neither a   Submission URL nor Check ID is provided  an attempt will be made to search for   an existing check using Instance ID and Search Tag  If one is not found  a new   HTTPTRAP check will be created  By default  this is a random   Enterprise Broker is selected  or  the default Circonus Public Broker      circonus broker select tag    string         Specifies a special tag which   will be used to select a Circonus Broker when a Broker ID is not provided  The   best use of this is to as a hint for which broker should be used based on    where  this particular instance is running  e g  a specific geo location or   datacenter  dc sfo         dogstatsd   These  telemetry  parameters apply to  DogStatsD  http   docs datadoghq com guides dogstatsd        dogstatsd addr    string         This provides the address of a DogStatsD   instance  DogStatsD is a protocol compatible flavor of statsd  with the added   ability to decorate metrics with tags and event information  If provided    Vault will send various telemetry information to that instance for   aggregation  This can be used to capture runtime information      dogstatsd tags    string array         This provides a list of global tags   that will be added to all telemetry packets sent to DogStatsD  It is a list   of strings  where each string looks like  my tag name my tag value         prometheus   These  telemetry  parameters apply to  prometheus  https   prometheus io       prometheus retention time    string   24h      Specifies the amount of time that   Prometheus metrics are retained in memory  Setting this to 0 will disable Prometheus telemetry     disable hostname    bool  false     It is recommended to also enable the option    disable hostname  to avoid having prefixed metrics with hostname   The   v1 sys metrics  endpoint is only accessible on active nodes and automatically disabled on standby nodes  You can enable the   v1 sys metrics  endpoint on standby nodes by  enabling unauthenticated metrics access  telemetry tcp   Standby nodes will never forward a request to   v1 sys metrics  to the active node  If unauthenticated metrics access is enabled  the standby node will respond with its own metrics  If unauthenticated metrics access is not enabled  then a standby node will attempt to service the request but fail and then redirect the request to the active node   Querying   v1 sys metrics  with one of the following headers       Accept  prometheus telemetry      Accept  application openmetrics text   will return Prometheus formatted results  Most Prometheus servers automatically query scrape targets with these headers by default   A Vault token is required with  capabilities     read    list    to  v1 sys metrics  The Prometheus  bearer token  or  bearer token file  options must be added to the scrape job   Vault does not use the default Prometheus path  so Prometheus must be configured to scrape  v1 sys metrics  instead of the default scrape path   An example job name stanza required in the  Prometheus config  https   prometheus io docs prometheus latest configuration configuration  scrape config  is provided below         prometheus yml scrape configs      job name   vault      metrics path    v1 sys metrics      scheme  https     tls config        ca file  your ca here pem     bearer token   your vault token here      static configs        targets    your vault server here 8200        An example telemetry configuration to be added to Vault s configuration file is shown below      hcl telemetry     prometheus retention time    30s    disable hostname   true             stackdriver   These  telemetry  parameters apply to  Stackdriver Monitoring  https   cloud google com monitoring     The Stackdriver telemetry provider uses the official Google Cloud Golang SDK  This means it supports the common ways of  providing credentials to Google Cloud  https   cloud google com docs authentication production providing credentials to your application    To use this telemetry provider  the service account must have the following minimum scope s       text https   www googleapis com auth cloud platform https   www googleapis com auth monitoring https   www googleapis com auth monitoring write      And the following IAM role s       text roles monitoring metricWriter         stackdriver project id    string         The Google Cloud ProjectID to send telemetry data to     stackdriver location    string         The GCP or AWS region of the monitored resource     stackdriver namespace    string         A namespace identifier for the telemetry data     stackdriver debug logs    bool   false      Specifies if Vault writes additional stackdriver related debug logs to standard error output  stderr    It is recommended to also enable the option  disable hostname  to avoid having prefixed metrics with hostname and enable instead  enable hostname label       hcl telemetry     stackdriver project id    my test project    stackdriver location    us east1 a    stackdriver namespace    vault cluster a    disable hostname   true   enable hostname label   true        Metrics from Vault can be found in  Metrics Explorer  https   cloud google com monitoring charts metrics explorer   All those metrics are shown with a resource type of  generic task   and the metric name is prefixed with  custom googleapis com go metrics      telemetry tcp    vault docs configuration listener tcp telemetry parameters


vault Kubernetes service registration Kubernetes Service Registration labels Vault pods with their current status layout docs for use with selectors page title Kubernetes Service Registration Configuration

Answer:
---
layout: docs
page_title: Kubernetes - Service Registration - Configuration
description: >-
  Kubernetes Service Registration labels Vault pods with their current status
  for use with selectors.
---

# Kubernetes service registration

Kubernetes Service Registration tags Vault pods with their current status for
use with selectors. Service registration is only available when Vault is running in
[High Availability mode](/vault/docs/concepts/ha).

- **HashiCorp Supported** – Kubernetes Service Registration is officially supported
  by HashiCorp.

## Configuration

```hcl
service_registration "kubernetes" {
  namespace      = "my-namespace"
  pod_name       = "my-pod-name"
}
```

Alternatively, the namespace and pod name can be set through the following
environment variables:

- `VAULT_K8S_NAMESPACE`
- `VAULT_K8S_POD_NAME`

This allows you to set these parameters using
[the Downward API](https://kubernetes.io/docs/tasks/inject-data-application/downward-api-volume-expose-pod-information/).

If using only environment variables, the service registration stanza declaring
you're using Kubernetes must still exist to indicate your intentions:

```
service_registration "kubernetes" {}
```

For service registration to succeed, Vault must be able to apply labels to pods
in Kubernetes. The following RBAC rules are required to allow the service account
associated with the Vault pods to update its own pod specification:

```
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  namespace: mynamespace
  name: vault-service-account
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "update", "patch"]
```

## Examples

Once properly configured, enabling service registration will cause Kubernetes pods
to come up with the following labels:

```
apiVersion: v1
kind: Pod
metadata:
  name: vault
  labels:
    vault-active: "false"
    vault-initialized: "true"
    vault-perf-standby: "false"
    vault-sealed: "false"
    vault-version: 1.18.1
```

After shutdowns, Vault pods will bear the following labels:

```
apiVersion: v1
kind: Pod
metadata:
  name: vault
  labels:
    vault-active: "false"
    vault-initialized: "false"
    vault-perf-standby: "false"
    vault-sealed: "true"
    vault-version: 1.18.1
```

## Label definitions

- `vault-active` `(string: "true"/"false")` – Vault active is updated dynamically each time Vault's active status changes.
  True indicates that this Vault pod is currently the leader. False indicates that this Vault pod is currently a standby.
- `vault-initialized` `(string: "true"/"false")` – Vault initialized is updated dynamically each time Vault's initialization
  status changes. True indicates that Vault is currently initialized. False indicates the Vault is currently uninitialized.
- `vault-perf-standby` `(string: "true"/"false")` – Vault performance standby is updated dynamically each
  time Vault's leader/standby status changes. **This field is only valuable if the pod is a member of a performance standby cluster**,
  it will simply be set to "false" when it's not applicable. True indicates that this Vault pod is currently a performance standby. False indicates
  that this Vault pod is currently a performance leader.
- `vault-sealed` `(string: "true"/"false")` – Vault sealed is updated dynamically each
  time Vault's sealed/unsealed status changes. True indicates that Vault is currently sealed. False indicates that Vault
  is currently unsealed.
- `vault-version` `(string: "1.18.1")` – Vault version is a string that will not change during a pod's lifecycle.

## Working with vault's service discovery labels

### Example service

With labels applied to the pod, services can be created using selectors to filter pods with specific Vault HA roles,
effectively allowing direct communication with subsets of Vault pods. Note the `vault-active: "true"` line below.

```
apiVersion: v1
kind: Service
metadata:
  labels:
    app.kubernetes.io/instance: vault
    app.kubernetes.io/name: vault
    helm.sh/chart: vault-0.29.1
  name: vault-active-us-east
  namespace: default
spec:
  clusterIP: 10.7.254.51
  ports:
  - name: http
    port: 8200
    protocol: TCP
    targetPort: 8200
  - name: internal
    port: 8201
    protocol: TCP
    targetPort: 8201
  publishNotReadyAddresses: false
  selector:
    app.kubernetes.io/instance: vault
    app.kubernetes.io/name: vault
    component: server
    vault-active: "true"
  type: ClusterIP
```

Also, by setting `publishNotReadyAddresses: false` above, pods that have failed will be removed from the service pool.

With this active service in place, we now have a dedicated endpoint that will always reach the active node. When
setting up Vault replication, it can be used as the primary address:

```shell-session
$ vault write -f sys/replication/performance/primary/enable \
    primary_cluster_addr='https://vault-active-us-east:8201'
```

### Example upgrades

In conjunction with the pod labels and the `OnDelete` upgrade strategy, upgrades are much easier to orchestrate:

```shell-session
$ helm upgrade vault --set='server.image.tag=1.18.1'

$ kubectl delete pod --selector=vault-active=false \
    --selector=vault-version=1.2.3

$ kubectl delete pod --selector=vault-active=true \
    --selector=vault-version=1.2.3
```

When deleting an instance of a pod, the `StatefulSet` defining the desired state of the cluster will reschedule the
deleted pods with the newest image.

layout  docs page title  Kubernetes   Service Registration   Configuration description       Kubernetes Service Registration labels Vault pods with their current status   for use with selectors         Kubernetes service registration  Kubernetes Service Registration tags Vault pods with their current status for use with selectors  Service registration is only available when Vault is running in  High Availability mode   vault docs concepts ha        HashiCorp Supported     Kubernetes Service Registration is officially supported   by HashiCorp      Configuration     hcl service registration  kubernetes      namespace         my namespace    pod name          my pod name         Alternatively  the namespace and pod name can be set through the following environment variables      VAULT K8S NAMESPACE     VAULT K8S POD NAME   This allows you to set these parameters using  the Downward API  https   kubernetes io docs tasks inject data application downward api volume expose pod information     If using only environment variables  the service registration stanza declaring you re using Kubernetes must still exist to indicate your intentions       service registration  kubernetes          For service registration to succeed  Vault must be able to apply labels to pods in Kubernetes  The following RBAC rules are required to allow the service account associated with the Vault pods to update its own pod specification       kind  Role apiVersion  rbac authorization k8s io v1 metadata    namespace  mynamespace   name  vault service account rules    apiGroups         resources    pods     verbs    get    update    patch           Examples  Once properly configured  enabling service registration will cause Kubernetes pods to come up with the following labels       apiVersion  v1 kind  Pod metadata    name  vault   labels      vault active   false      vault initialized   true      vault perf standby   false      vault sealed   false      vault version  1 18 1      After shutdowns  Vault pods will bear the following labels       apiVersion  v1 kind  Pod metadata    name  vault   labels      vault active   false      vault initialized   false      vault perf standby   false      vault sealed   true      vault version  1 18 1         Label definitions     vault active    string   true   false      Vault active is updated dynamically each time Vault s active status changes    True indicates that this Vault pod is currently the leader  False indicates that this Vault pod is currently a standby     vault initialized    string   true   false      Vault initialized is updated dynamically each time Vault s initialization   status changes  True indicates that Vault is currently initialized  False indicates the Vault is currently uninitialized     vault perf standby    string   true   false      Vault performance standby is updated dynamically each   time Vault s leader standby status changes    This field is only valuable if the pod is a member of a performance standby cluster      it will simply be set to  false  when it s not applicable  True indicates that this Vault pod is currently a performance standby  False indicates   that this Vault pod is currently a performance leader     vault sealed    string   true   false      Vault sealed is updated dynamically each   time Vault s sealed unsealed status changes  True indicates that Vault is currently sealed  False indicates that Vault   is currently unsealed     vault version    string   1 18 1      Vault version is a string that will not change during a pod s lifecycle      Working with vault s service discovery labels      Example service  With labels applied to the pod  services can be created using selectors to filter pods with specific Vault HA roles  effectively allowing direct communication with subsets of Vault pods  Note the  vault active   true   line below       apiVersion  v1 kind  Service metadata    labels      app kubernetes io instance  vault     app kubernetes io name  vault     helm sh chart  vault 0 29 1   name  vault active us east   namespace  default spec    clusterIP  10 7 254 51   ports      name  http     port  8200     protocol  TCP     targetPort  8200     name  internal     port  8201     protocol  TCP     targetPort  8201   publishNotReadyAddresses  false   selector      app kubernetes io instance  vault     app kubernetes io name  vault     component  server     vault active   true    type  ClusterIP      Also  by setting  publishNotReadyAddresses  false  above  pods that have failed will be removed from the service pool   With this active service in place  we now have a dedicated endpoint that will always reach the active node  When setting up Vault replication  it can be used as the primary address      shell session   vault write  f sys replication performance primary enable       primary cluster addr  https   vault active us east 8201           Example upgrades  In conjunction with the pod labels and the  OnDelete  upgrade strategy  upgrades are much easier to orchestrate      shell session   helm upgrade vault   set  server image tag 1 18 1     kubectl delete pod   selector vault active false         selector vault version 1 2 3    kubectl delete pod   selector vault active true         selector vault version 1 2 3      When deleting an instance of a pod  the  StatefulSet  defining the desired state of the cluster will reschedule the deleted pods with the newest image


vault default health check page title Consul Service Registration Configuration layout docs Consul Service Registration registers Vault as a service in Consul with a

Answer:
---
layout: docs
page_title: Consul - Service Registration - Configuration
description: >-
  Consul Service Registration registers Vault as a service in Consul with a
  default

  health check.
---

# Consul service registration

Consul Service Registration registers Vault as a service in [Consul][consul] with
a default health check. When Consul is configured as the storage backend, the stanza
`service_registration` is not needed as it will automatically register Vault as a service.

~> **Version information:** The `service_registration` configuration option was introduced in Vault 1.4.0.

@include 'consul-dataplane-compat.mdx'

- **HashiCorp Supported** – Consul Service Registration is officially supported
  by HashiCorp.

## Configuration

```hcl
service_registration "consul" {
  address      = "127.0.0.1:8500"
}
```

If Vault is running in HA mode, include the transfer protocol (`http://` or
`https://`) in the address:

```hcl
service_registration "consul" {
  address      = "http://127.0.0.1:8500"
}
```

Once properly configured, an unsealed Vault installation should be available and
accessible at:

```text
active.vault.service.consul
```

Unsealed Vault instances in standby mode are available at:

```text
standby.vault.service.consul
```

All unsealed Vault instances are available as healthy at:

```text
vault.service.consul
```

Sealed Vault instances will mark themselves as unhealthy to avoid being returned
at Consul's service discovery layer.

## `consul` parameters

- `address` `(string: "127.0.0.1:8500")` – Specifies the address of the Consul
  agent to communicate with. This can be an IP address, DNS record, or unix
  socket. It is recommended that you communicate with a local Consul agent; do
  not communicate directly with a server.

- `check_timeout` `(string: "5s")` – Specifies the check interval used to send
  health check information back to Consul. This is specified using a label
  suffix like `"30s"` or `"1h"`.

- `disable_registration` `(string: "false")` – Specifies whether Vault should
  register itself with Consul.

- `scheme` `(string: "http")` – Specifies the scheme to use when communicating
  with Consul. This can be set to "http" or "https". It is highly recommended
  you communicate with Consul over https over non-local connections. When
  communicating over a unix socket, this option is ignored.

- `service` `(string: "vault")` – Specifies the name of the service to register
  in Consul.

- `service_tags` `(string: "")` – Specifies a comma-separated list of case-sensitive
  tags to attach to the service registration in Consul.

- `service_meta` `(map[string]string: {})` – Specifies a key-value list of meta tags to
  attach to the service registration in Consul. See [ServiceMeta](/consul/api-docs/catalog#servicemeta) in the Consul docs for more information.

- `service_address` `(string: nil)` – Specifies a service-specific address to
  set on the service registration in Consul. If unset, Vault will use what it
  knows to be the HA redirect address - which is usually desirable. Setting
  this parameter to `""` will tell Consul to leverage the configuration of the
  node the service is registered on dynamically. This could be beneficial if
  you intend to leverage Consul's
  [`translate_wan_addrs`][consul-translate-wan-addrs] parameter.

- `token` `(string: "")` – Specifies the [Consul ACL token][consul-acl] with
  permission to register the Vault service into Consul's service catalog.
  This is **not** a Vault token. See the ACL section below for help.

The following settings apply when communicating with Consul via an encrypted
connection. You can read more about encrypting Consul connections on the
[Consul encryption page][consul-encryption].

- `tls_ca_file` `(string: "")` – Specifies the path to the CA certificate used
  for Consul communication. This defaults to system bundle if not specified.
  This should be set according to the
  [`ca_file`](/consul/docs/agent/config/config-files#ca_file) setting in
  Consul.

- `tls_cert_file` `(string: "")` (optional) – Specifies the path to the
  certificate for Consul communication. This should be set according to the
  [`cert_file`](/consul/docs/agent/config/config-files#cert_file) setting
  in Consul.

- `tls_key_file` `(string: "")` – Specifies the path to the private key for
  Consul communication. This should be set according to the
  [`key_file`](/consul/docs/agent/config/config-files#key_file) setting
  in Consul.

- `tls_min_version` `(string: "tls12")` – Specifies the minimum TLS version to
  use. Accepted values are `"tls10"`, `"tls11"`, `"tls12"` or `"tls13"`.

- `tls_skip_verify` `(string: "false")` – Disable verification of TLS certificates.
  Using this option is highly discouraged.

## ACLs

If using ACLs in Consul, you'll need appropriate permissions to register the
Vault service. The following ACL policy will work for most use-cases, assuming
that your service name is `vault`:

```json
{
  "service": {
    "vault": {
      "policy": "write"
    }
  }
}
```

## `consul` examples

### Local agent

This example shows a sample configuration which communicates with a local
Consul agent running on `127.0.0.1:8500`.

```hcl
service_registration "consul" {}
```

### Detailed customization

This example shows communicating with Consul on a custom address with an ACL
token.

```hcl
service_registration "consul" {
  address = "10.5.7.92:8194"
  token   = "abcd1234"
}
```

### Consul via unix socket

This example shows communicating with Consul over a local unix socket.

```hcl
service_registration "consul" {
  address = "unix:///tmp/.consul.http.sock"
}
```

### Custom TLS

This example shows using a custom CA, certificate, and key file to securely
communicate with Consul over TLS.

```hcl
service_registration "consul" {
  scheme        = "https"
  tls_ca_file   = "/etc/pem/vault.ca"
  tls_cert_file = "/etc/pem/vault.cert"
  tls_key_file  = "/etc/pem/vault.key"
}
```

[consul]: https://www.consul.io/ 'Consul by HashiCorp'
[consul-acl]: /consul/docs/guides/acl 'Consul ACLs'
[consul-encryption]: /consul/docs/agent/encryption 'Consul Encryption'
[consul-translate-wan-addrs]: /consul/docs/agent/options#translate_wan_addrs 'Consul Configuration'

layout  docs page title  Consul   Service Registration   Configuration description       Consul Service Registration registers Vault as a service in Consul with a   default    health check         Consul service registration  Consul Service Registration registers Vault as a service in  Consul  consul  with a default health check  When Consul is configured as the storage backend  the stanza  service registration  is not needed as it will automatically register Vault as a service        Version information    The  service registration  configuration option was introduced in Vault 1 4 0    include  consul dataplane compat mdx       HashiCorp Supported     Consul Service Registration is officially supported   by HashiCorp      Configuration     hcl service registration  consul      address         127 0 0 1 8500         If Vault is running in HA mode  include the transfer protocol   http     or  https      in the address      hcl service registration  consul      address         http   127 0 0 1 8500         Once properly configured  an unsealed Vault installation should be available and accessible at      text active vault service consul      Unsealed Vault instances in standby mode are available at      text standby vault service consul      All unsealed Vault instances are available as healthy at      text vault service consul      Sealed Vault instances will mark themselves as unhealthy to avoid being returned at Consul s service discovery layer       consul  parameters     address    string   127 0 0 1 8500      Specifies the address of the Consul   agent to communicate with  This can be an IP address  DNS record  or unix   socket  It is recommended that you communicate with a local Consul agent  do   not communicate directly with a server      check timeout    string   5s      Specifies the check interval used to send   health check information back to Consul  This is specified using a label   suffix like   30s   or   1h        disable registration    string   false      Specifies whether Vault should   register itself with Consul      scheme    string   http      Specifies the scheme to use when communicating   with Consul  This can be set to  http  or  https   It is highly recommended   you communicate with Consul over https over non local connections  When   communicating over a unix socket  this option is ignored      service    string   vault      Specifies the name of the service to register   in Consul      service tags    string         Specifies a comma separated list of case sensitive   tags to attach to the service registration in Consul      service meta    map string string         Specifies a key value list of meta tags to   attach to the service registration in Consul  See  ServiceMeta   consul api docs catalog servicemeta  in the Consul docs for more information      service address    string  nil     Specifies a service specific address to   set on the service registration in Consul  If unset  Vault will use what it   knows to be the HA redirect address   which is usually desirable  Setting   this parameter to      will tell Consul to leverage the configuration of the   node the service is registered on dynamically  This could be beneficial if   you intend to leverage Consul s     translate wan addrs   consul translate wan addrs  parameter      token    string         Specifies the  Consul ACL token  consul acl  with   permission to register the Vault service into Consul s service catalog    This is   not   a Vault token  See the ACL section below for help   The following settings apply when communicating with Consul via an encrypted connection  You can read more about encrypting Consul connections on the  Consul encryption page  consul encryption       tls ca file    string         Specifies the path to the CA certificate used   for Consul communication  This defaults to system bundle if not specified    This should be set according to the     ca file    consul docs agent config config files ca file  setting in   Consul      tls cert file    string        optional    Specifies the path to the   certificate for Consul communication  This should be set according to the     cert file    consul docs agent config config files cert file  setting   in Consul      tls key file    string         Specifies the path to the private key for   Consul communication  This should be set according to the     key file    consul docs agent config config files key file  setting   in Consul      tls min version    string   tls12      Specifies the minimum TLS version to   use  Accepted values are   tls10      tls11      tls12   or   tls13        tls skip verify    string   false      Disable verification of TLS certificates    Using this option is highly discouraged      ACLs  If using ACLs in Consul  you ll need appropriate permissions to register the Vault service  The following ACL policy will work for most use cases  assuming that your service name is  vault       json      service          vault            policy    write                       consul  examples      Local agent  This example shows a sample configuration which communicates with a local Consul agent running on  127 0 0 1 8500       hcl service registration  consul              Detailed customization  This example shows communicating with Consul on a custom address with an ACL token      hcl service registration  consul      address    10 5 7 92 8194    token      abcd1234             Consul via unix socket  This example shows communicating with Consul over a local unix socket      hcl service registration  consul      address    unix    tmp  consul http sock             Custom TLS  This example shows using a custom CA  certificate  and key file to securely communicate with Consul over TLS      hcl service registration  consul      scheme           https    tls ca file       etc pem vault ca    tls cert file     etc pem vault cert    tls key file      etc pem vault key          consul   https   www consul io   Consul by HashiCorp   consul acl    consul docs guides acl  Consul ACLs   consul encryption    consul docs agent encryption  Consul Encryption   consul translate wan addrs    consul docs agent options translate wan addrs  Consul Configuration