vault Migrate Consul to Raft storage page title Migrate Consul to Raft storage This procedure assumes you have a Vault cluster deployed in a Kubernetes environment configured with Consul storage The storage migration can occur while leaving the Consul cluster intact A single change to the Consul cluster is a lock file written by Vault during the migration Guide to migration of Consul storage to Raft layout docs

Answer:
---
layout: docs
page_title: Migrate Consul to Raft storage
description: >-
  Guide to migration of Consul storage to Raft.
---

# Migrate Consul to Raft storage

This procedure assumes you have a Vault cluster deployed in a Kubernetes environment configured with Consul storage.  The storage migration can occur while leaving the Consul cluster intact.  A single change to the Consul cluster is a lock file written by Vault during the migration.

This guide uses basic examples and default Vault configurations.  It is for illustrative purposes, and adaption to specific configurations relevant to your environment is still required.

<Warning title="Back up data">

Always back up your data before attempting migration! Although this is an offline operation and the risk is low, it is advisable to take a recent snapshot from your Consul cluster before proceeding.

</Warning>

## Overview

This guide uses an intermediate Helm configuration to introduce an init container that will perform the storage migration, and then start a single Vault server using the Raft storage backend to verify the results.  Then update the Helm configuration to remove the init container and start Vault replicas.

### Vault and Kubernetes setup

Consider the following `vault status` output and Helm Chart values for Vault:

<CodeBlockConfig hideClipboard>

```plaintext
Key             Value
---             -----
Seal Type       shamir
Initialized     true
Sealed          false
Total Shares    1
Threshold       1
Version         1.14.8+ent
Build Date      2023-12-05T01:49:39Z
Storage Type    consul
Cluster Name    vault-cluster-68870bf8
Cluster ID      cd18c692-f2e3-77a5-fba3-28f06f41f375
HA Enabled      true
HA Cluster      https://vault-0.vault-internal:8201
HA Mode         active
Active Since    2024-04-10T02:45:33.367042122Z
Last WAL        52
```

</CodeBlockConfig>

Helm chart values:

<CodeBlockConfig hideClipboard>

```plaintext
global:
  enabled: false

server:
  enabled: true
  image:
    repository: hashicorp/vault-enterprise
    tag: 1.14.8-ent
  enterpriseLicense:
    secretName: vault-license
    secretKey: vault.hclic
  ha:
    enabled: true
    replicas: 3
    config: |
      ui = true
      service_registration "kubernetes" {}

      listener "tcp" {
        address = ":8200"
        cluster_address = ":8201"
        tls_disable = 1
      }

      storage "consul" {
        path = "vault"
        address = "http://HOST_IP:8500"
      }
```

</CodeBlockConfig>

### Migration procedure

1. Uninstall Vault via Helm.

  ```shell-session
  $ helm uninstall vault
  ```

  Deployed `StatefulSets` cannot have certain attributes modified after their initial deployment.  Therefore, the `StatefulSet` deployment must be entirely replaced.

 Vault servers using Consul storage are by default stateless. Unless explicitly configured, the Vault server `StatefulSet` does not create any Persistent Volume Claims (PVC) or other artifacts.  Vault's index holds its state, which is entirely stored in the Consul server `StatefulSet`'s persistent volumes.

  <Warning title='Caution'>

  It is strongly advised to review your Vault deployment configurations and take appropriate backups for any stateful information managed via Helm or other orchestration platforms.

  </Warning>

1. Create a `ConfigMap` containing the Storage Migration configuration.

  ```shell-session
  $ cat > vault-storage-migration-configmap.yml <<EOF
  apiVersion: v1
  kind: ConfigMap
  metadata:
    labels:
      app.kubernetes.io/instance: vault
      app.kubernetes.io/name: vault
    name: storage-migration
    namespace: default
  data:
    migrate.hcl: |-
      storage_source "consul" {
        address = "http://consul-server.default.svc.cluster.local:8500"
        path = "vault/"
      }

      storage_destination "raft" {
        path = "/vault/data"
      }

      cluster_addr = "https://vault-0.vault-internal:8201"
  EOF
  ```

  Often your Vault server should communicate to Consul via a Consul client agent.  This example uses the service endpoint for a Consul server deployed in Kubernetes, although it can work for a Consul server cluster deployed outside of Kubernetes as well.

1. Apply the `ConfigMap`.

  ```shell-session
  $ kubectl create -f vault-storage-migration-configmap.yml
  ```

1. Install Vault via Helm deployment with Raft Migration storage configuration.

  ```shell-session
  $ cat > vault-migration-values.yml <<EOF
  global:
    enabled: false

  server:
    enabled: true
    image:
      repository: hashicorp/vault-enterprise
      tag: 1.14.8-ent
    enterpriseLicense:
      secretName: vault-license
      secretKey: vault.hclic
    extraInitContainers:
      - name: vault-storage-migration
        image: hashicorp/vault-enterprise:1.14.8-ent
        command:
          - "/bin/sh"
          - "-ec"
        args:
          - "/bin/vault operator migrate -config /vault/storage-migration/migrate.hcl"
        volumeMounts:
          - name: storage-migration
            mountPath: "/vault/storage-migration"
          - name: data
            mountPath: "/vault/data"
    volumeMounts:
      - name: storage-migration
        mountPath: "/vault/storage-migration"
    volumes:
      - name: storage-migration
        configMap:
          name: storage-migration
    dataStorage:
      enabled: true
      size: "1Gi"
    ha:
      enabled: true
      replicas: 1
      raft:
        enabled: true
        config: |
          ui = true
          service_registration "kubernetes" {}

          listener "tcp" {
            address = ":8200"
            cluster_address = ":8201"
            tls_disable = 1
          }

          storage "raft" {
            path = "/vault/data"
            retry_join {
              auto_join_scheme = "http"
              auto_join = "provider=k8s"
            }
          }
  EOF
  ```

  **Configuration notes**
    - `storage “raft”` configuration to specify the path for the Raft DB (`/vault/data` by default), and any `retry_join` parameters in your original configuration.
      - This example uses `auto_join` to automatically find Raft peers via the Kubernetes API.  See the [`retry_join`](/vault/docs/configuration/storage/raft#retry_join-stanza) for more information.
    - `dataStorage` configuration in the Helm override values, to specify the parameters of the PVCs the Vault `StatefulSet` will create.
    - `extraInitContainers` will start an init container mounting the storage migration ConfigMap and `data` volume, which it will then use to execute the storage migration.
    - `replicas: 1`
      - This setting is temporary for the purposes of the migration.  A new Vault `StatefulSet` with one replica to confirm the init container completed the migration and unseal Vault using the new storage backend.

1. Apply this configuration.

  ```shell-session
  $ helm install vault hashicorp/vault -f vault-migration-values.yml
  ```

1. Review the migration logs.

  ```shell-session
  $ kubectl logs vault-0 -c vault-server-migration
  ```

1. Unseal Vault.

  ```shell-session
  $ kubectl exec -it vault-0 -- vault operator unseal
  Key                     Value
  ---                     -----
  Seal Type               shamir
  Initialized             true
  Sealed                  false
  Total Shares            1
  Threshold               1
  Version                 1.14.8+ent
  Build Date              2023-12-05T01:49:39Z
  Storage Type            raft
  Cluster Name            vault-cluster-68870bf8
  Cluster ID              cd18c692-f2e3-77a5-fba3-28f06f41f375
  HA Enabled              true
  HA Cluster              https://vault-0.vault-internal:8201
  HA Mode                 active
  Active Since            2024-04-10T04:20:23.707098402Z
  Raft Committed Index    157
  Raft Applied Index      157
  Last WAL                55
  ```

1. Update Vault Helm deployment with Raft storage configuration.

  ```shell-session
  $ cat > vault-raft-values.yml <<EOF
  global:
    enabled: false
  server:
    enabled: true
    image:
      repository: hashicorp/vault-enterprise
      tag: 1.14.8-ent
    enterpriseLicense:
      secretName: vault-license
      secretKey: vault.hclic
    dataStorage:
      enabled: true
      size: "1Gi"
    ha:
      enabled: true
      replicas: 5
      raft:
        enabled: true
        config: |
          ui = true
          service_registration "kubernetes" {}

          listener "tcp" {
            address = ":8200"
            cluster_address = ":8201"
            tls_disable = 1
          }

          storage "raft" {
            path = "/vault/data"
            retry_join {
              auto_join_scheme = "http"
              auto_join = "provider=k8s"
            }
          }
  EOF
  ```
  **Configuration notes**
    - `replicas: 5`
      - Upgrade the Helm deployment in place using the final Raft storage configuration, removing the `extraInitContainer` and storage migration `ConfigMap`, and increasing the number of replicas.  The `retry_join` parameters used by the new Vault server replicas to automatically join the cluster.

1. Apply the configuration.

  ```shell-session
  $ helm upgrade vault hashicorp/vault -f vault-raft-values.yml
  ```

1. Unseal Vault.

  ```shell-session
  $ for i in {1..4} ; do kubectl exec -it vault-0 -- vault operator unseal ; done
  ```

1. Confirm the Raft peers have formed a quorum.

  ```shell-session
  $ kubectl exec -it vault-0 -- vault operator raft list-peers

  Node                                    Address                        State       Voter
  ----                                    -------                        -----       -----
  24c166d8-a8bb-3ac7-f8a0-12bd066a34bb    vault-0.vault-internal:8201    leader      true
  626434d1-170b-575a-2a04-af4f2e90820b    vault-1.vault-internal:8201    follower    true
  1dfbba31-9b5b-2d16-18ce-bfa7b6c0ead6    vault-2.vault-internal:8201    follower    true
  3f333082-1a64-7559-0142-e4f1658a28f3    vault-3.vault-internal:8201    follower    true
  9ca5a15e-3ddc-d132-0b46-5b895f3828dc    vault-4.vault-internal:8201    follower    true
  ```

## Rollback procedure

To revert to the original configuration, you'll just need to delete the Helm deployment, and re-deploy it using the override values specifying your Consul storage configuration.

Note that the Vault Helm Chart's default configuration using Raft storage will retain any PVCs created.  Vault does not use these while configured with Consul storage.  You will need to remove the PVCs before re-attempting the migration.

1. Uninstall Vault via Helm.

  ```shell-session
  $ helm uninstall vault
  ```

1. Install Vault via Helm with old Consul storage configuration.

  ```shell-session
  $ `helm install vault hashicorp/vault -f vault-consul-values.yml
  ```

1. Unseal Vault and confirm the storage has reverted to Consul.

  <CodeBlockConfig highlight="11">

  ```she-session
  $ kubectl exec -it vault-0 -- vault status
  Key             Value
  ---             -----
  Seal Type       shamir
  Initialized     true
  Sealed          false
  Total Shares    1
  Threshold       1
  Version         1.14.8+ent
  Build Date      2023-12-05T01:49:39Z
  Storage Type    consul
  Cluster Name    vault-cluster-68870bf8
  Cluster ID      cd18c692-f2e3-77a5-fba3-28f06f41f375
  HA Enabled      true
  HA Cluster      https://vault-0.vault-internal:8201
  HA Mode         active
  Active Since    2024-04-10T04:44:12.516016652Z
  Last WAL        54
  ```

  </CodeBlockConfig>

## References

- [Vault operator migrate command](/vault/docs/commands/operator/migrate)
- [Helm Chart configuration](/vault/docs/platform/k8s/helm/configuration)
- [Vault on Kubernetes deployment guide](/vault/tutorials/kubernetes/kubernetes-raft-deployment-guide)
- [Vault Helm Chart configuration](https://github.com/hashicorp/vault-helm)
- [kubectl commands](https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands)
- [Kubernetes storage volumes](https://kubernetes.io/docs/concepts/storage/volumes/)
- [Create a Pod that has an Init Container](https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-initialization/#create-a-pod-that-has-an-init-container)
- [Helm docs](https://helm.sh/docs/)

layout  docs page title  Migrate Consul to Raft storage description       Guide to migration of Consul storage to Raft          Migrate Consul to Raft storage  This procedure assumes you have a Vault cluster deployed in a Kubernetes environment configured with Consul storage   The storage migration can occur while leaving the Consul cluster intact   A single change to the Consul cluster is a lock file written by Vault during the migration   This guide uses basic examples and default Vault configurations   It is for illustrative purposes  and adaption to specific configurations relevant to your environment is still required    Warning title  Back up data    Always back up your data before attempting migration  Although this is an offline operation and the risk is low  it is advisable to take a recent snapshot from your Consul cluster before proceeding     Warning      Overview  This guide uses an intermediate Helm configuration to introduce an init container that will perform the storage migration  and then start a single Vault server using the Raft storage backend to verify the results   Then update the Helm configuration to remove the init container and start Vault replicas       Vault and Kubernetes setup  Consider the following  vault status  output and Helm Chart values for Vault    CodeBlockConfig hideClipboard      plaintext Key             Value                       Seal Type       shamir Initialized     true Sealed          false Total Shares    1 Threshold       1 Version         1 14 8 ent Build Date      2023 12 05T01 49 39Z Storage Type    consul Cluster Name    vault cluster 68870bf8 Cluster ID      cd18c692 f2e3 77a5 fba3 28f06f41f375 HA Enabled      true HA Cluster      https   vault 0 vault internal 8201 HA Mode         active Active Since    2024 04 10T02 45 33 367042122Z Last WAL        52        CodeBlockConfig   Helm chart values    CodeBlockConfig hideClipboard      plaintext global    enabled  false  server    enabled  true   image      repository  hashicorp vault enterprise     tag  1 14 8 ent   enterpriseLicense      secretName  vault license     secretKey  vault hclic   ha      enabled  true     replicas  3     config          ui   true       service registration  kubernetes            listener  tcp            address     8200          cluster address     8201          tls disable   1                storage  consul            path    vault          address    http   HOST IP 8500                 CodeBlockConfig       Migration procedure  1  Uninstall Vault via Helm        shell session     helm uninstall vault          Deployed  StatefulSets  cannot have certain attributes modified after their initial deployment   Therefore  the  StatefulSet  deployment must be entirely replaced    Vault servers using Consul storage are by default stateless  Unless explicitly configured  the Vault server  StatefulSet  does not create any Persistent Volume Claims  PVC  or other artifacts   Vault s index holds its state  which is entirely stored in the Consul server  StatefulSet  s persistent volumes      Warning title  Caution      It is strongly advised to review your Vault deployment configurations and take appropriate backups for any stateful information managed via Helm or other orchestration platforms       Warning   1  Create a  ConfigMap  containing the Storage Migration configuration        shell session     cat   vault storage migration configmap yml   EOF   apiVersion  v1   kind  ConfigMap   metadata      labels        app kubernetes io instance  vault       app kubernetes io name  vault     name  storage migration     namespace  default   data      migrate hcl           storage source  consul            address    http   consul server default svc cluster local 8500          path    vault                  storage destination  raft            path     vault data                 cluster addr    https   vault 0 vault internal 8201     EOF            Often your Vault server should communicate to Consul via a Consul client agent   This example uses the service endpoint for a Consul server deployed in Kubernetes  although it can work for a Consul server cluster deployed outside of Kubernetes as well   1  Apply the  ConfigMap         shell session     kubectl create  f vault storage migration configmap yml        1  Install Vault via Helm deployment with Raft Migration storage configuration        shell session     cat   vault migration values yml   EOF   global      enabled  false    server      enabled  true     image        repository  hashicorp vault enterprise       tag  1 14 8 ent     enterpriseLicense        secretName  vault license       secretKey  vault hclic     extraInitContainers          name  vault storage migration         image  hashicorp vault enterprise 1 14 8 ent         command                bin sh                ec          args                bin vault operator migrate  config  vault storage migration migrate hcl          volumeMounts              name  storage migration             mountPath    vault storage migration              name  data             mountPath    vault data      volumeMounts          name  storage migration         mountPath    vault storage migration      volumes          name  storage migration         configMap            name  storage migration     dataStorage        enabled  true       size   1Gi      ha        enabled  true       replicas  1       raft          enabled  true         config              ui   true           service registration  kubernetes                listener  tcp                address     8200              cluster address     8201              tls disable   1                        storage  raft                path     vault data              retry join                 auto join scheme    http                auto join    provider k8s                              EOF            Configuration notes          storage  raft   configuration to specify the path for the Raft DB    vault data  by default   and any  retry join  parameters in your original configuration          This example uses  auto join  to automatically find Raft peers via the Kubernetes API   See the   retry join    vault docs configuration storage raft retry join stanza  for more information         dataStorage  configuration in the Helm override values  to specify the parameters of the PVCs the Vault  StatefulSet  will create         extraInitContainers  will start an init container mounting the storage migration ConfigMap and  data  volume  which it will then use to execute the storage migration           replicas  1          This setting is temporary for the purposes of the migration   A new Vault  StatefulSet  with one replica to confirm the init container completed the migration and unseal Vault using the new storage backend   1  Apply this configuration        shell session     helm install vault hashicorp vault  f vault migration values yml          1  Review the migration logs          shell session     kubectl logs vault 0  c vault server migration          1  Unseal Vault        shell session     kubectl exec  it vault 0    vault operator unseal   Key                     Value                                   Seal Type               shamir   Initialized             true   Sealed                  false   Total Shares            1   Threshold               1   Version                 1 14 8 ent   Build Date              2023 12 05T01 49 39Z   Storage Type            raft   Cluster Name            vault cluster 68870bf8   Cluster ID              cd18c692 f2e3 77a5 fba3 28f06f41f375   HA Enabled              true   HA Cluster              https   vault 0 vault internal 8201   HA Mode                 active   Active Since            2024 04 10T04 20 23 707098402Z   Raft Committed Index    157   Raft Applied Index      157   Last WAL                55        1  Update Vault Helm deployment with Raft storage configuration        shell session     cat   vault raft values yml   EOF   global      enabled  false   server      enabled  true     image        repository  hashicorp vault enterprise       tag  1 14 8 ent     enterpriseLicense        secretName  vault license       secretKey  vault hclic     dataStorage        enabled  true       size   1Gi      ha        enabled  true       replicas  5       raft          enabled  true         config              ui   true           service registration  kubernetes                listener  tcp                address     8200              cluster address     8201              tls disable   1                        storage  raft                path     vault data              retry join                 auto join scheme    http                auto join    provider k8s                              EOF           Configuration notes          replicas  5          Upgrade the Helm deployment in place using the final Raft storage configuration  removing the  extraInitContainer  and storage migration  ConfigMap   and increasing the number of replicas   The  retry join  parameters used by the new Vault server replicas to automatically join the cluster   1  Apply the configuration        shell session     helm upgrade vault hashicorp vault  f vault raft values yml          1  Unseal Vault        shell session     for i in  1  4    do kubectl exec  it vault 0    vault operator unseal   done        1  Confirm the Raft peers have formed a quorum        shell session     kubectl exec  it vault 0    vault operator raft list peers    Node                                    Address                        State       Voter                                                                                24c166d8 a8bb 3ac7 f8a0 12bd066a34bb    vault 0 vault internal 8201    leader      true   626434d1 170b 575a 2a04 af4f2e90820b    vault 1 vault internal 8201    follower    true   1dfbba31 9b5b 2d16 18ce bfa7b6c0ead6    vault 2 vault internal 8201    follower    true   3f333082 1a64 7559 0142 e4f1658a28f3    vault 3 vault internal 8201    follower    true   9ca5a15e 3ddc d132 0b46 5b895f3828dc    vault 4 vault internal 8201    follower    true             Rollback procedure  To revert to the original configuration  you ll just need to delete the Helm deployment  and re deploy it using the override values specifying your Consul storage configuration   Note that the Vault Helm Chart s default configuration using Raft storage will retain any PVCs created   Vault does not use these while configured with Consul storage   You will need to remove the PVCs before re attempting the migration   1  Uninstall Vault via Helm        shell session     helm uninstall vault        1  Install Vault via Helm with old Consul storage configuration        shell session      helm install vault hashicorp vault  f vault consul values yml          1  Unseal Vault and confirm the storage has reverted to Consul      CodeBlockConfig highlight  11         she session     kubectl exec  it vault 0    vault status   Key             Value                           Seal Type       shamir   Initialized     true   Sealed          false   Total Shares    1   Threshold       1   Version         1 14 8 ent   Build Date      2023 12 05T01 49 39Z   Storage Type    consul   Cluster Name    vault cluster 68870bf8   Cluster ID      cd18c692 f2e3 77a5 fba3 28f06f41f375   HA Enabled      true   HA Cluster      https   vault 0 vault internal 8201   HA Mode         active   Active Since    2024 04 10T04 44 12 516016652Z   Last WAL        54            CodeBlockConfig      References     Vault operator migrate command   vault docs commands operator migrate     Helm Chart configuration   vault docs platform k8s helm configuration     Vault on Kubernetes deployment guide   vault tutorials kubernetes kubernetes raft deployment guide     Vault Helm Chart configuration  https   github com hashicorp vault helm     kubectl commands  https   kubernetes io docs reference generated kubectl kubectl commands     Kubernetes storage volumes  https   kubernetes io docs concepts storage volumes      Create a Pod that has an Init Container  https   kubernetes io docs tasks configure pod container configure pod initialization  create a pod that has an init container     Helm docs  https   helm sh docs


vault This document explores two different methods for integrating HashiCorp Vault with Kubernetes The information provided is intended for DevOps practitioners who understand secret management concepts and are familiar with HashiCorp Vault and Kubernetes This document also offers practical guidance to help you understand and choose the best method for your use case Agent injector vs Vault CSI provider This section compares Sidecar Injector and Vault CSI Provider for Kubernetes and Vault integration layout docs page title Agent Injector vs Vault CSI Provider

Answer:
---
layout: docs
page_title: Agent Injector vs. Vault CSI Provider
description: This section compares Sidecar Injector and Vault CSI Provider for Kubernetes and Vault integration.
---

# Agent injector vs. Vault CSI provider

This document explores two different methods for integrating HashiCorp Vault with Kubernetes. The information provided is intended for DevOps practitioners who understand secret management concepts and are familiar with HashiCorp Vault and Kubernetes. This document also offers practical guidance to help you understand and choose the best method for your use case.

Information contained within this document details the contrast between the Agent Injector, also referred as _Vault Sidecar_ or _Sidecar_ in this document, and the Vault Container Storage Interface (CSI) provider used to integrate Vault and Kubernetes.

## Vault sidecar agent injector

The [Vault Sidecar Agent Injector](/vault/docs/platform/k8s/injector) leverages the [sidecar pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/sidecar) to alter pod specifications to include a Vault Agent container that renders Vault secrets to a shared memory volume. By rendering secrets to a shared volume, containers within the pod can consume Vault secrets without being Vault-aware. The injector is a Kubernetes mutating webhook controller. The controller intercepts pod events and applies mutations to the pod if annotations exist within the request. This functionality is provided by the [vault-k8s](https://github.com/hashicorp/vault-k8s) project and can be automatically installed and configured using the Vault Helm chart.

![Vault Sidecar Injection Workflow](/img/vault-sidecar-inject-workflow.png)

## Vault CSI provider

The [Vault CSI provider](/vault/docs/platform/k8s/csi) allows pods to consume Vault secrets by using ephemeral [CSI Secrets Store](https://github.com/kubernetes-sigs/secrets-store-csi-driver) volumes. At a high level, the CSI Secrets Store driver enables users to create `SecretProviderClass` objects. These objects define which secret provider to use and what secrets to retrieve. When pods requesting CSI volumes are made, the CSI Secrets Store driver sends the request to the Vault CSI provider if the provider is `vault`. The Vault CSI provider then uses the specified `SecretProviderClass` and the pod’s service account to retrieve the secrets from Vault and mount them into the pod’s CSI volume. Note that the secret is retrieved from Vault and populated to the CSI secrets store volume during the `ContainerCreation` phase. Therefore, pods are blocked from starting until the secrets are read from Vault and written to the volume.

![Vault Sidecar Injection Workflow](/img/vault-csi-workflow.png)

~> **Note**: Secrets are fetched earlier in the pod lifecycle, therefore, they have fewer compatibility issues with Sidecars, such as Istio.

Before we get into some of the similarities and differences between the two solutions, let's look at several common design considerations.

- **Secret projections:** Every application requires secrets to explicitly presented. Typically, applications expect secrets to be either exported as environment variables or written to a file that the application can read on startup. Keep that in mind as you’re deciding on a suitable method to use.

- **Secret scope:** Some applications are deployed across multiple Kubernetes environments (e.g., dev, qa, prod) across your data centers, the edge, or public clouds. Some services run outside of Kubernetes on VMs, serverless, or other cloud-managed services. You may face scenarios where these applications need to share sets of secrets across these heterogeneous environments. Scoping the secrets correctly to be either local to the Kubernetes environment or global across different environments helps ensure that each application can easily and securely access its own set of secrets within the environment it is deployed in.

- **Secret types:** Secrets can be text files, binary files, tokens, or certs, or they can be statically or dynamically generated. They can also be valid permanently or time-scoped, and can vary in size. You need to consider the secret types your application requires and how they’re projected into the application.

- **Secret definition:** You also need to consider how each secret is defined, created, updated, and removed, as well as the tooling associated with that process.

- **Encryption:** Encrypting secrets both at rest and in transit is a critical requirement for many enterprise organizations.

- **Governance:** Applications and secrets can have a many-to-many relationship that requires careful considerations when granting access for applications to retrieve their respective secrets. As the number of applications and secrets scale, so does the challenge of managing their access policies.

- **Secrets updates and rotation:** Secrets can be leased, time-scoped, or automatically rotated, and each scenario needs to be a programmatic process to ensure the new secret is propagated to the application pods properly.

- **Secret caching:** In certain Kubernetes environments (e.g., edge or retail), there is a potential need for secret caching in the case of communication or network failures between the environment and the secret storage.

- **Auditability:** Keeping a secret access audit log detailing all secret access information is critical to ensure traceability of secret-access events.

Now that you're familiar with some of the design considerations, we'll explore the similarities and differences between the two solutions to help you determine the best solution to use as you design and implement your secrets management strategy in a Kubernetes environment.

## Similarities

Both Agent Injection and Vault CSI solutions have the following similarities:

- They simplify retrieving different types of secrets stored in Vault and expose them to the target pod running on Kubernetes without knowing the not-so-trivial Vault processes. It’s important to note that there is no need to change the application logic or code to use these solutions, therefore, making it easier to migrate brownfield applications into Kubernetes. Developers working on greenfield applications can leverage the Vault SDKs to integrate with Vault directly.

- They support all types of Vault [secrets engines](/vault/docs/secrets). This support allows you to leverage an extensive set of secret types, ranging from static key-value secrets to dynamically generated database credentials and TLS certs with customized TTL.

- They leverage the application’s Kubernetes pod service account token as [Secret Zero](https://www.hashicorp.com/resources/secret-zero-mitigating-the-risk-of-secret-introduction-with-vault) to authenticate with Vault via the Kubernetes auth method. With this method, there is no need to manage yet another separate identity to identify the application pods when authenticating to Vault.

- Secret lifetime is tied to the lifetime of the pod for both methods. While this holds true for file contents inside the pod, this also holds true for Kubernetes secrets that CSI creates. Secrets are automatically created and deleted as the pod is created and deleted.

![Vault's Kubernetes auth workflow](/img/k8s-auth-workflow.png)

- They require the desired secrets to exist within Vault before deploying the application.

- They require the pod’s service account to bind to a Vault role with a policy enabling access to desired secrets (that is, Kubernetes RBAC isn’t used to authorize access to secrets).

- They can both be deployed via Helm.

- They require successfully retrieving secrets from Vault before the pods are started.

- They rely on user-defined pod annotations to retrieve the required secrets from Vault.

## Differences

Now that you understand the similarities, there are differences between these two solutions for considerations:

- The Sidecar Agent Injector solution is composed of two elements:

  - The Sidecar Service Injector, which is deployed as a cluster service and is responsible for intercepting Kubernetes apiserver pod events and mutating pod specs to add required sidecar containers
  - The Vault Sidecar Container, which is deployed alongside each application pod and is responsible for authenticating into Vault, retrieving secrets from Vault, and rendering secrets for the application to consume.

- In contrast, the Vault CSI Driver is deployed as a daemonset on every node in the Kubernetes cluster and uses the Secret Provider Class specified and the pod’s service account to retrieve the secrets from Vault and mount them into the pod’s CSI volume.

- The Sidecar Agent Injector supports [all](/vault/docs/platform/k8s/injector/annotations#vault-hashicorp-com-auth-path) Vault [auto-auth](/vault/docs/agent-and-proxy/autoauth/methods) methods. The Sidecar CSI driver supports only Vault’s [Kubernetes auth method](/vault/docs/platform/k8s/csi/configurations#vaultkubernetesmountpath).

- The Sidecar container launched with every application pod uses [Vault Agent](https://www.hashicorp.com/blog/why-use-the-vault-agent-for-secrets-management), which provides a powerful set of capabilities such as auto-auth, templating, and caching. The CSI driver does not use the Vault Agent and therefore lacks these functionalities.

- The Vault CSI driver supports rendering Vault secrets into Kubernetes secrets and environment variables. Sidecar Injector Service does not support rendering secrets into Kubernetes secrets; however, there are ways to [agent templating](/vault/docs/platform/k8s/injector/examples#environment-variable-example) to render secrets into environment variables.

- The CSI driver uses `hostPath` to mount ephemeral volumes into the pods, which some container platforms (e.g., OpenShift) disable by default. On the other hand, Sidecar Agent Service uses in-memory _tmpfs_ volumes.

- Sidecar Injector Service [automatically](/vault/docs/agent-and-proxy/agent/template#renewals-and-updating-secrets) renews, rotates, and fetches secrets/tokens while the CSI Driver does not support that.

## Comparison chart

The below chart provides a high-level comparison between the two solutions.

~> **Note:** Shared Memory Volume Environment Variable can be achieved through [Agent templating](/vault/docs/platform/k8s/injector/examples#environment-variable-example).

![Comparison Chart](/img/comparison-table.png)

## Going beyond the native kubernetes secrets

On the surface, Kubernetes native secrets might seem similar to the two approaches presented above, but there are significant differences between them:

- Kubernetes is not a secrets management solution. It does have native support for secrets, but that is quite different from an enterprise secrets management solution. Kubernetes secrets are scoped to the cluster only, and many applications will have some services running outside Kubernetes or in other Kubernetes clusters. Having these applications use Kubernetes secrets from outside a Kubernetes environment will be cumbersome and introduce authentication and authorization challenges. Therefore, considering the secret scope as part of the design process is critical.

- Kubernetes secrets are static in nature. You can define secrets by using kubectl or the Kubernetes API, but once they are defined, they are stored in etcd and presented to pods only during pod creation. Defining secrets in this manner may create scenarios where secrets get stale, outdated, or expired, requiring additional workflows to update and rotate the secrets, and then re-deploy the application to use the new version, which can add complexity and become quite time-consuming. Ensure consideration is given to all requirements for secret freshness, updates, and rotation as part of your design process.

- The secret access management security model is tied to the Kubernetes RBAC model. This model can be challenging for users who are not familiar with Kubernetes. Adopting a platform-agnostic security governance model can enable you to adapt workflows for applications regardless of how and where they are running.

## Summary

Designing secrets management in Kubernetes is an intricate task. There are multiple approaches, each with its own set of attributes. We recommend exploring the options presented in this document to increase your understanding of the internals and decide on the best option for your use case.

## Additional resources

- [HashiCorp Vault: Delivering Secrets with Kubernetes](https://medium.com/hashicorp-engineering/hashicorp-vault-delivering-secrets-with-kubernetes-1b358c03b2a3)

- [Retrieve HashiCorp Vault Secrets with Kubernetes CSI](https://www.hashicorp.com/blog/retrieve-hashicorp-vault-secrets-with-kubernetes-csi)

- [Mount Vault Secrets Through Container Storage Interface (CSI) Volume](/vault/tutorials/kubernetes/kubernetes-secret-store-driver)

- [Injecting Secrets into Kubernetes Pods via Vault Agent Containers](/vault/tutorials/kubernetes/kubernetes-sidecar)

- [Vault Sidecar Injector Configurations and Examples](/vault/docs/platform/k8s/injector/annotations)

- [Vault CSI Driver Configurations and Examples](/vault/docs/platform/k8s/csi/configurations)

layout  docs page title  Agent Injector vs  Vault CSI Provider description  This section compares Sidecar Injector and Vault CSI Provider for Kubernetes and Vault integration         Agent injector vs  Vault CSI provider  This document explores two different methods for integrating HashiCorp Vault with Kubernetes  The information provided is intended for DevOps practitioners who understand secret management concepts and are familiar with HashiCorp Vault and Kubernetes  This document also offers practical guidance to help you understand and choose the best method for your use case   Information contained within this document details the contrast between the Agent Injector  also referred as  Vault Sidecar  or  Sidecar  in this document  and the Vault Container Storage Interface  CSI  provider used to integrate Vault and Kubernetes      Vault sidecar agent injector  The  Vault Sidecar Agent Injector   vault docs platform k8s injector  leverages the  sidecar pattern  https   docs microsoft com en us azure architecture patterns sidecar  to alter pod specifications to include a Vault Agent container that renders Vault secrets to a shared memory volume  By rendering secrets to a shared volume  containers within the pod can consume Vault secrets without being Vault aware  The injector is a Kubernetes mutating webhook controller  The controller intercepts pod events and applies mutations to the pod if annotations exist within the request  This functionality is provided by the  vault k8s  https   github com hashicorp vault k8s  project and can be automatically installed and configured using the Vault Helm chart     Vault Sidecar Injection Workflow   img vault sidecar inject workflow png      Vault CSI provider  The  Vault CSI provider   vault docs platform k8s csi  allows pods to consume Vault secrets by using ephemeral  CSI Secrets Store  https   github com kubernetes sigs secrets store csi driver  volumes  At a high level  the CSI Secrets Store driver enables users to create  SecretProviderClass  objects  These objects define which secret provider to use and what secrets to retrieve  When pods requesting CSI volumes are made  the CSI Secrets Store driver sends the request to the Vault CSI provider if the provider is  vault   The Vault CSI provider then uses the specified  SecretProviderClass  and the pod s service account to retrieve the secrets from Vault and mount them into the pod s CSI volume  Note that the secret is retrieved from Vault and populated to the CSI secrets store volume during the  ContainerCreation  phase  Therefore  pods are blocked from starting until the secrets are read from Vault and written to the volume     Vault Sidecar Injection Workflow   img vault csi workflow png        Note    Secrets are fetched earlier in the pod lifecycle  therefore  they have fewer compatibility issues with Sidecars  such as Istio   Before we get into some of the similarities and differences between the two solutions  let s look at several common design considerations       Secret projections    Every application requires secrets to explicitly presented  Typically  applications expect secrets to be either exported as environment variables or written to a file that the application can read on startup  Keep that in mind as you re deciding on a suitable method to use       Secret scope    Some applications are deployed across multiple Kubernetes environments  e g   dev  qa  prod  across your data centers  the edge  or public clouds  Some services run outside of Kubernetes on VMs  serverless  or other cloud managed services  You may face scenarios where these applications need to share sets of secrets across these heterogeneous environments  Scoping the secrets correctly to be either local to the Kubernetes environment or global across different environments helps ensure that each application can easily and securely access its own set of secrets within the environment it is deployed in       Secret types    Secrets can be text files  binary files  tokens  or certs  or they can be statically or dynamically generated  They can also be valid permanently or time scoped  and can vary in size  You need to consider the secret types your application requires and how they re projected into the application       Secret definition    You also need to consider how each secret is defined  created  updated  and removed  as well as the tooling associated with that process       Encryption    Encrypting secrets both at rest and in transit is a critical requirement for many enterprise organizations       Governance    Applications and secrets can have a many to many relationship that requires careful considerations when granting access for applications to retrieve their respective secrets  As the number of applications and secrets scale  so does the challenge of managing their access policies       Secrets updates and rotation    Secrets can be leased  time scoped  or automatically rotated  and each scenario needs to be a programmatic process to ensure the new secret is propagated to the application pods properly       Secret caching    In certain Kubernetes environments  e g   edge or retail   there is a potential need for secret caching in the case of communication or network failures between the environment and the secret storage       Auditability    Keeping a secret access audit log detailing all secret access information is critical to ensure traceability of secret access events   Now that you re familiar with some of the design considerations  we ll explore the similarities and differences between the two solutions to help you determine the best solution to use as you design and implement your secrets management strategy in a Kubernetes environment      Similarities  Both Agent Injection and Vault CSI solutions have the following similarities     They simplify retrieving different types of secrets stored in Vault and expose them to the target pod running on Kubernetes without knowing the not so trivial Vault processes  It s important to note that there is no need to change the application logic or code to use these solutions  therefore  making it easier to migrate brownfield applications into Kubernetes  Developers working on greenfield applications can leverage the Vault SDKs to integrate with Vault directly     They support all types of Vault  secrets engines   vault docs secrets   This support allows you to leverage an extensive set of secret types  ranging from static key value secrets to dynamically generated database credentials and TLS certs with customized TTL     They leverage the application s Kubernetes pod service account token as  Secret Zero  https   www hashicorp com resources secret zero mitigating the risk of secret introduction with vault  to authenticate with Vault via the Kubernetes auth method  With this method  there is no need to manage yet another separate identity to identify the application pods when authenticating to Vault     Secret lifetime is tied to the lifetime of the pod for both methods  While this holds true for file contents inside the pod  this also holds true for Kubernetes secrets that CSI creates  Secrets are automatically created and deleted as the pod is created and deleted     Vault s Kubernetes auth workflow   img k8s auth workflow png     They require the desired secrets to exist within Vault before deploying the application     They require the pod s service account to bind to a Vault role with a policy enabling access to desired secrets  that is  Kubernetes RBAC isn t used to authorize access to secrets      They can both be deployed via Helm     They require successfully retrieving secrets from Vault before the pods are started     They rely on user defined pod annotations to retrieve the required secrets from Vault      Differences  Now that you understand the similarities  there are differences between these two solutions for considerations     The Sidecar Agent Injector solution is composed of two elements       The Sidecar Service Injector  which is deployed as a cluster service and is responsible for intercepting Kubernetes apiserver pod events and mutating pod specs to add required sidecar containers     The Vault Sidecar Container  which is deployed alongside each application pod and is responsible for authenticating into Vault  retrieving secrets from Vault  and rendering secrets for the application to consume     In contrast  the Vault CSI Driver is deployed as a daemonset on every node in the Kubernetes cluster and uses the Secret Provider Class specified and the pod s service account to retrieve the secrets from Vault and mount them into the pod s CSI volume     The Sidecar Agent Injector supports  all   vault docs platform k8s injector annotations vault hashicorp com auth path  Vault  auto auth   vault docs agent and proxy autoauth methods  methods  The Sidecar CSI driver supports only Vault s  Kubernetes auth method   vault docs platform k8s csi configurations vaultkubernetesmountpath      The Sidecar container launched with every application pod uses  Vault Agent  https   www hashicorp com blog why use the vault agent for secrets management   which provides a powerful set of capabilities such as auto auth  templating  and caching  The CSI driver does not use the Vault Agent and therefore lacks these functionalities     The Vault CSI driver supports rendering Vault secrets into Kubernetes secrets and environment variables  Sidecar Injector Service does not support rendering secrets into Kubernetes secrets  however  there are ways to  agent templating   vault docs platform k8s injector examples environment variable example  to render secrets into environment variables     The CSI driver uses  hostPath  to mount ephemeral volumes into the pods  which some container platforms  e g   OpenShift  disable by default  On the other hand  Sidecar Agent Service uses in memory  tmpfs  volumes     Sidecar Injector Service  automatically   vault docs agent and proxy agent template renewals and updating secrets  renews  rotates  and fetches secrets tokens while the CSI Driver does not support that      Comparison chart  The below chart provides a high level comparison between the two solutions        Note    Shared Memory Volume Environment Variable can be achieved through  Agent templating   vault docs platform k8s injector examples environment variable example      Comparison Chart   img comparison table png      Going beyond the native kubernetes secrets  On the surface  Kubernetes native secrets might seem similar to the two approaches presented above  but there are significant differences between them     Kubernetes is not a secrets management solution  It does have native support for secrets  but that is quite different from an enterprise secrets management solution  Kubernetes secrets are scoped to the cluster only  and many applications will have some services running outside Kubernetes or in other Kubernetes clusters  Having these applications use Kubernetes secrets from outside a Kubernetes environment will be cumbersome and introduce authentication and authorization challenges  Therefore  considering the secret scope as part of the design process is critical     Kubernetes secrets are static in nature  You can define secrets by using kubectl or the Kubernetes API  but once they are defined  they are stored in etcd and presented to pods only during pod creation  Defining secrets in this manner may create scenarios where secrets get stale  outdated  or expired  requiring additional workflows to update and rotate the secrets  and then re deploy the application to use the new version  which can add complexity and become quite time consuming  Ensure consideration is given to all requirements for secret freshness  updates  and rotation as part of your design process     The secret access management security model is tied to the Kubernetes RBAC model  This model can be challenging for users who are not familiar with Kubernetes  Adopting a platform agnostic security governance model can enable you to adapt workflows for applications regardless of how and where they are running      Summary  Designing secrets management in Kubernetes is an intricate task  There are multiple approaches  each with its own set of attributes  We recommend exploring the options presented in this document to increase your understanding of the internals and decide on the best option for your use case      Additional resources     HashiCorp Vault  Delivering Secrets with Kubernetes  https   medium com hashicorp engineering hashicorp vault delivering secrets with kubernetes 1b358c03b2a3      Retrieve HashiCorp Vault Secrets with Kubernetes CSI  https   www hashicorp com blog retrieve hashicorp vault secrets with kubernetes csi      Mount Vault Secrets Through Container Storage Interface  CSI  Volume   vault tutorials kubernetes kubernetes secret store driver      Injecting Secrets into Kubernetes Pods via Vault Agent Containers   vault tutorials kubernetes kubernetes sidecar      Vault Sidecar Injector Configurations and Examples   vault docs platform k8s injector annotations      Vault CSI Driver Configurations and Examples   vault docs platform k8s csi configurations


vault The following examples demonstrate how the Vault CSI Provider can be used page title Vault CSI Provider Examples This section documents examples of using the Vault CSI Provider layout docs Vault CSI provider examples

Answer:
---
layout: docs
page_title: Vault CSI Provider Examples
description: This section documents examples of using the Vault CSI Provider.
---

# Vault CSI provider examples

The following examples demonstrate how the Vault CSI Provider can be used.

~> A common mistake is to not install the CSI Secret Store Driver before using the Vault CSI Provider.

## File based dynamic database credentials

The following Secret Provider Class retrieves dynamic database credentials from Vault and
extracts the generated username and password. The secrets are then mounted as files in the
configured mount location.

```yaml
---
apiVersion: secrets-store.csi.x-k8s.io/v1alpha1
kind: SecretProviderClass
metadata:
  name: vault-db-creds
spec:
  provider: vault
  parameters:
    roleName: 'app'
    objects: |
      - objectName: "dbUsername"
        secretPath: "database/creds/db-app"
        secretKey: "username"
      - objectName: "dbPassword"
        secretPath: "database/creds/db-app"
        secretKey: "password"
```

Next, a pod can be created to use this Secret Provider Class to populate the secrets in the pod:

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: app
  labels:
    app: demo
spec:
  selector:
    matchLabels:
      app: demo
  replicas: 1
  template:
    metadata:
      annotations:
      labels:
        app: demo
    spec:
      serviceAccountName: app
      containers:
        - name: app
          image: my-app:1.0.0
          volumeMounts:
            - name: 'vault-db-creds'
              mountPath: '/mnt/secrets-store'
              readOnly: true
      volumes:
        - name: vault-db-creds
          csi:
            driver: 'secrets-store.csi.k8s.io'
            readOnly: true
            volumeAttributes:
              secretProviderClass: 'vault-db-creds'
```

The pod mounts a CSI volume and specifies the Secret Provider Class (`vault-db-creds`) created above.
The secrets created from that provider class are mounted to `/mnt/secrets-store`. When this pod is
created the containers will find two files containing secrets:

- `/mnt/secrets-store/dbUsername`
- `/mnt/secrets-store/dbPassword`

## Environment variable dynamic database credentials

The following Secret Provider Class retrieves dynamic database credentials from Vault and
extracts the generated username and password. The secrets are then synced to Kubernetes secrets
so that they can be mounted as environment variables in the containers.

```yaml
---
apiVersion: secrets-store.csi.x-k8s.io/v1alpha1
kind: SecretProviderClass
metadata:
  name: vault-db-creds
spec:
  provider: vault
  secretObjects:
    - secretName: vault-db-creds-secret
      type: Opaque
      data:
        - objectName: dbUsername # References dbUsername below
          key: username # Key within k8s secret for this value
        - objectName: dbPassword
          key: password
  parameters:
    roleName: 'app'
    objects: |
      - objectName: "dbUsername"
        secretPath: "database/creds/db-app"
        secretKey: "username"
      - objectName: "dbPassword"
        secretPath: "database/creds/db-app"
        secretKey: "password"
```

Next, a pod can be created which uses this Secret Provider Class to populate the secrets in the pod's environment:

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: app
  labels:
    app: demo
spec:
  selector:
    matchLabels:
      app: demo
  replicas: 1
  template:
    metadata:
      annotations:
      labels:
        app: demo
    spec:
      serviceAccountName: app
      containers:
        - name: app
          image: my-app:1.0.0
          env:
            - name: DB_USERNAME
              valueFrom:
                secretKeyRef:
                  name: vault-db-creds-secret
                  key: username
            - name: DB_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: vault-db-creds-secret
                  key: password
          volumeMounts:
            - name: 'vault-db-creds'
              mountPath: '/mnt/secrets-store'
              readOnly: true
      volumes:
        - name: vault-db-creds
          csi:
            driver: 'secrets-store.csi.k8s.io'
            readOnly: true
            volumeAttributes:
              secretProviderClass: 'vault-db-creds'
```

The pod mounts a CSI volume and specifies the Secret Provider Class (`vault-db-creds`) created above.
The secrets created from that provider class are mounted to `/mnt/secrets-store`, additionally a Kubernetes
secret called `vault-db-creds` is created and referenced in two environment variables.

layout  docs page title  Vault CSI Provider Examples description  This section documents examples of using the Vault CSI Provider         Vault CSI provider examples  The following examples demonstrate how the Vault CSI Provider can be used      A common mistake is to not install the CSI Secret Store Driver before using the Vault CSI Provider      File based dynamic database credentials  The following Secret Provider Class retrieves dynamic database credentials from Vault and extracts the generated username and password  The secrets are then mounted as files in the configured mount location      yaml     apiVersion  secrets store csi x k8s io v1alpha1 kind  SecretProviderClass metadata    name  vault db creds spec    provider  vault   parameters      roleName   app      objects            objectName   dbUsername          secretPath   database creds db app          secretKey   username          objectName   dbPassword          secretPath   database creds db app          secretKey   password       Next  a pod can be created to use this Secret Provider Class to populate the secrets in the pod      yaml apiVersion  apps v1 kind  Deployment metadata    name  app   labels      app  demo spec    selector      matchLabels        app  demo   replicas  1   template      metadata        annotations        labels          app  demo     spec        serviceAccountName  app       containers            name  app           image  my app 1 0 0           volumeMounts                name   vault db creds                mountPath    mnt secrets store                readOnly  true       volumes            name  vault db creds           csi              driver   secrets store csi k8s io              readOnly  true             volumeAttributes                secretProviderClass   vault db creds       The pod mounts a CSI volume and specifies the Secret Provider Class   vault db creds   created above  The secrets created from that provider class are mounted to   mnt secrets store   When this pod is created the containers will find two files containing secrets       mnt secrets store dbUsername      mnt secrets store dbPassword      Environment variable dynamic database credentials  The following Secret Provider Class retrieves dynamic database credentials from Vault and extracts the generated username and password  The secrets are then synced to Kubernetes secrets so that they can be mounted as environment variables in the containers      yaml     apiVersion  secrets store csi x k8s io v1alpha1 kind  SecretProviderClass metadata    name  vault db creds spec    provider  vault   secretObjects        secretName  vault db creds secret       type  Opaque       data            objectName  dbUsername   References dbUsername below           key  username   Key within k8s secret for this value           objectName  dbPassword           key  password   parameters      roleName   app      objects            objectName   dbUsername          secretPath   database creds db app          secretKey   username          objectName   dbPassword          secretPath   database creds db app          secretKey   password       Next  a pod can be created which uses this Secret Provider Class to populate the secrets in the pod s environment      yaml apiVersion  apps v1 kind  Deployment metadata    name  app   labels      app  demo spec    selector      matchLabels        app  demo   replicas  1   template      metadata        annotations        labels          app  demo     spec        serviceAccountName  app       containers            name  app           image  my app 1 0 0           env                name  DB USERNAME               valueFrom                  secretKeyRef                    name  vault db creds secret                   key  username               name  DB PASSWORD               valueFrom                  secretKeyRef                    name  vault db creds secret                   key  password           volumeMounts                name   vault db creds                mountPath    mnt secrets store                readOnly  true       volumes            name  vault db creds           csi              driver   secrets store csi k8s io              readOnly  true             volumeAttributes                secretProviderClass   vault db creds       The pod mounts a CSI volume and specifies the Secret Provider Class   vault db creds   created above  The secrets created from that provider class are mounted to   mnt secrets store   additionally a Kubernetes secret called  vault db creds  is created and referenced in two environment variables


vault The Vault CSI Provider allows pods to consume Vault secrets using Vault CSI provider layout docs The Vault CSI Provider allows pods to consume Vault secrets using CSI volumes page title Vault CSI Provider

Answer:
---
layout: docs
page_title: Vault CSI Provider
description: >-
  The Vault CSI Provider allows pods to consume Vault secrets using CSI volumes.
---

# Vault CSI provider

The Vault CSI Provider allows pods to consume Vault secrets using
[CSI Secrets Store](https://github.com/kubernetes-sigs/secrets-store-csi-driver) volumes.

~> The Vault CSI Provider requires the [CSI Secret Store](https://github.com/kubernetes-sigs/secrets-store-csi-driver)
Driver to be installed.

## Overview

At a high level, the CSI Secrets Store driver allows users to create `SecretProviderClass` objects.
This object defines which secret provider to use and what secrets to retrieve. When pods requesting CSI volumes
are created, the CSI Secrets Store driver will send the request to the Vault CSI Provider if the provider
is `vault`. The Vault CSI Provider will then use Secret Provider Class specified and the pod's service account to retrieve
the secrets from Vault, and mount them into the pod's CSI volume.

The secret is retrieved from Vault and populated to the CSI secrets store volume during the `ContainerCreation` phase.
This means that pods will be blocked from starting until the secrets have been read from Vault and written to the volume.

### Features

The following features are supported by the Vault CSI Provider:

- All Vault secret engines supported.
- Authentication using the requesting pod's service account.
- TLS/mTLS communications with Vault.
- Rendering Vault secrets to files.
- Dynamic lease caching and renewal performed by Agent.
- Syncing secrets to Kubernetes secrets to be used as environment variables.
- Installation via [Vault Helm](/vault/docs/platform/k8s/helm)

@include 'kubernetes-supported-versions.mdx'

## Authenticating with Vault

The Vault CSI Provider will authenticate with Vault as the service account of the
pod that mounts the CSI volume. [Kubernetes](/vault/docs/auth/kubernetes) and
[JWT](/vault/docs/auth/jwt) auth methods are supported. The pod's service account
must be bound to a Vault role and a policy granting access to the secrets desired.

It is highly recommended to run pods with dedicated Kubernetes service accounts to
ensure applications cannot access more secrets than they require.

## Secret provider class example

The following is an example of a Secret Provider Class using the `vault` provider:

```yaml
---
apiVersion: secrets-store.csi.x-k8s.io/v1alpha1
kind: SecretProviderClass
metadata:
  name: vault-db-creds
spec:
  # Vault CSI Provider
  provider: vault
  parameters:
    # Vault role name to use during login
    roleName: 'app'
    # Vault address and TLS connection config is normally best configured by the
    # helm chart, but can be overridden per SecretProviderClass:
    # Vault's hostname
    #vaultAddress: 'https://vault:8200'
    # TLS CA certification for validation
    #vaultCACertPath: '/vault/tls/ca.crt'
    objects: |
      - objectName: "dbUsername"
        secretPath: "database/creds/db-app"
        secretKey: "username"
      - objectName: "dbPassword"
        secretPath: "database/creds/db-app"
        secretKey: "password"
    # "objectName" is an alias used within the SecretProviderClass to reference
    # that specific secret. This will also be the filename containing the secret.
    # "secretPath" is the path in Vault where the secret should be retrieved.
    # "secretKey" is the key within the Vault secret response to extract a value from.
```

~> Secret Provider Class is a namespaced object in Kubernetes.

## Using secret provider classes

An application pod uses the example Secret Provider Class above by mounting it as a CSI volume:

```yaml
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: app
  labels:
    app: demo
spec:
  selector:
    matchLabels:
      app: demo
  replicas: 1
  template:
    spec:
      serviceAccountName: app
      containers:
        - name: app
          image: my-app:1.0.0
          volumeMounts:
            - name: 'vault-db-creds'
              mountPath: '/mnt/secrets-store'
              readOnly: true
      volumes:
        - name: vault-db-creds
          csi:
            driver: 'secrets-store.csi.k8s.io'
            readOnly: true
            volumeAttributes:
              secretProviderClass: 'vault-db-creds'
```

In this example `volumes.csi` is created on the application deployment and references
the Secret Provider Class named `vault-db-creds`.

## Tutorial

Refer to the [Vault CSI Provider](/vault/tutorials/kubernetes/kubernetes-secret-store-driver)
tutorial to learn how to set up Vault and its dependencies with a Helm chart.

layout  docs page title  Vault CSI Provider description       The Vault CSI Provider allows pods to consume Vault secrets using CSI volumes         Vault CSI provider  The Vault CSI Provider allows pods to consume Vault secrets using  CSI Secrets Store  https   github com kubernetes sigs secrets store csi driver  volumes      The Vault CSI Provider requires the  CSI Secret Store  https   github com kubernetes sigs secrets store csi driver  Driver to be installed      Overview  At a high level  the CSI Secrets Store driver allows users to create  SecretProviderClass  objects  This object defines which secret provider to use and what secrets to retrieve  When pods requesting CSI volumes are created  the CSI Secrets Store driver will send the request to the Vault CSI Provider if the provider is  vault   The Vault CSI Provider will then use Secret Provider Class specified and the pod s service account to retrieve the secrets from Vault  and mount them into the pod s CSI volume   The secret is retrieved from Vault and populated to the CSI secrets store volume during the  ContainerCreation  phase  This means that pods will be blocked from starting until the secrets have been read from Vault and written to the volume       Features  The following features are supported by the Vault CSI Provider     All Vault secret engines supported    Authentication using the requesting pod s service account    TLS mTLS communications with Vault    Rendering Vault secrets to files    Dynamic lease caching and renewal performed by Agent    Syncing secrets to Kubernetes secrets to be used as environment variables    Installation via  Vault Helm   vault docs platform k8s helm    include  kubernetes supported versions mdx      Authenticating with Vault  The Vault CSI Provider will authenticate with Vault as the service account of the pod that mounts the CSI volume   Kubernetes   vault docs auth kubernetes  and  JWT   vault docs auth jwt  auth methods are supported  The pod s service account must be bound to a Vault role and a policy granting access to the secrets desired   It is highly recommended to run pods with dedicated Kubernetes service accounts to ensure applications cannot access more secrets than they require      Secret provider class example  The following is an example of a Secret Provider Class using the  vault  provider      yaml     apiVersion  secrets store csi x k8s io v1alpha1 kind  SecretProviderClass metadata    name  vault db creds spec      Vault CSI Provider   provider  vault   parameters        Vault role name to use during login     roleName   app        Vault address and TLS connection config is normally best configured by the       helm chart  but can be overridden per SecretProviderClass        Vault s hostname      vaultAddress   https   vault 8200        TLS CA certification for validation      vaultCACertPath    vault tls ca crt      objects            objectName   dbUsername          secretPath   database creds db app          secretKey   username          objectName   dbPassword          secretPath   database creds db app          secretKey   password         objectName  is an alias used within the SecretProviderClass to reference       that specific secret  This will also be the filename containing the secret         secretPath  is the path in Vault where the secret should be retrieved         secretKey  is the key within the Vault secret response to extract a value from          Secret Provider Class is a namespaced object in Kubernetes      Using secret provider classes  An application pod uses the example Secret Provider Class above by mounting it as a CSI volume      yaml     apiVersion  apps v1 kind  Deployment metadata    name  app   labels      app  demo spec    selector      matchLabels        app  demo   replicas  1   template      spec        serviceAccountName  app       containers            name  app           image  my app 1 0 0           volumeMounts                name   vault db creds                mountPath    mnt secrets store                readOnly  true       volumes            name  vault db creds           csi              driver   secrets store csi k8s io              readOnly  true             volumeAttributes                secretProviderClass   vault db creds       In this example  volumes csi  is created on the application deployment and references the Secret Provider Class named  vault db creds       Tutorial  Refer to the  Vault CSI Provider   vault tutorials kubernetes kubernetes secret store driver  tutorial to learn how to set up Vault and its dependencies with a Helm chart


vault This section documents the configurables for the Vault CSI Provider page title Vault CSI Provider Configurations Most settings support being set by in ascending order of precedence The following command line arguments are supported by the Vault CSI provider layout docs Command line arguments

Answer:
---
layout: docs
page_title: Vault CSI Provider Configurations
description: This section documents the configurables for the Vault CSI Provider.
---

# Command line arguments

The following command line arguments are supported by the Vault CSI provider.
Most settings support being set by, in ascending order of precedence:

- Environment variables
- Command line arguments
- Secret Provider Class parameters

If installing via the helm chart, they can be set using e.g.
`--set "csi.extraArgs={-debug=true}"`.

- `-cache-size` `(int: 1000)` - Set the maximum number of Vault tokens that will
  be cached in-memory. One Vault token will be stored for each pod on the same
  node that mounts secrets. Setting to 0 will disable the cache and force each
  volume mount request to reauthenticate to Vault.

- `-debug` `(bool: false)` - Set to true to enable debug level logging.

- `-endpoint` `(string: "/tmp/vault.sock")` - Path to unix socket on which the
  provider will listen for gRPC calls from the driver.

- `-health-addr` `(string: ":8080")` - The address of the HTTP listener
  for reporting health.

- `-hmac-secret-name` `(string: "vault-csi-provider-hmac-key")` - Configure the
  Kubernetes secret name that the provider creates to store an HMAC key for
  generating secret version hashes.

- `-vault-addr` `(string: "https://127.0.0.1:8200")` - Default address
  for connecting to Vault. Can also be specified via the `VAULT_ADDR` environment
  variable. **Note:** It is highly recommended to only set the Vault address when
  installing the helm chart. The helm chart will install Vault Agent as a sidecar
  to the Vault CSI Provider for caching and renewals, but setting `-vault-addr`
  here will cause the Vault CSI Provider to bypass the Agent's cache.

- `-vault-mount` `(string: "kubernetes")` - Default Vault mount path
  for Kubernetes authentication. Can be overridden per Secret Provider Class
  object.

- `-vault-namespace` `(string: "")` - (v1.1.0+) Default Vault namespace for Vault
  requests. Can also be specified via the `VAULT_NAMESPACE` environment variable.

- `-vault-tls-ca-cert` `(string: "")` - (v1.1.0+) Path on disk to a single
  PEM-encoded CA certificate to trust for Vault. Takes precedence over
  `-vault-tls-ca-directory`. Can also be specified via the `VAULT_CACERT`
  environment variable.

- `-vault-tls-ca-directory` `(string: "")` - (v1.1.0+) Path on disk to a
  directory of PEM-encoded CA certificates to trust for Vault. Can also be
  specified via the `VAULT_CAPATH` environment variable.

- `-vault-tls-server-name` `(string: "")` - (v1.1.0+) Name to use as the SNI
  host when connecting to Vault via TLS. Can also be specified via the
  `VAULT_TLS_SERVER_NAME` environment variable.

- `-vault-tls-client-cert` `(string: "")` - (v1.1.0+) Path on disk to a
  PEM-encoded client certificate for mTLS communication with Vault. If set,
  also requires `-vault-tls-client-key`. Can also be specified via the
  `VAULT_CLIENT_CERT` environment variable.

- `-vault-tls-client-key` `(string: "")` - (v1.1.0+) Path on disk to a
  PEM-encoded client key for mTLS communication with Vault. If set, also
  requires `-vault-tls-client-cert`. Can also be specified via the
  `VAULT_CLIENT_KEY` environment variable.

- `-vault-tls-skip-verify` `(bool: false)` - (v1.1.0+) Disable verification of
  TLS certificates. Can also be specified via the `VAULT_SKIP_VERIFY` environment
  variable.

- `-version` `(bool: false)` - print version information and exit.

# Secret provider class parameters

The following parameters are supported by the Vault provider. Each parameter is
an entry under `spec.parameters` in a SecretProviderClass object. The full
structure is illustrated in the [examples](/vault/docs/platform/k8s/csi/examples).

- `roleName` `(string: "")` - Name of the role to be used during login with Vault.

- `vaultAddress` `(string: "")` - The address of the Vault server. **Note:** It is
  highly recommended to only set the Vault address when installing the helm chart.
  The helm chart will install Vault Agent as a sidecar to the Vault CSI Provider
  for caching and renewals, but setting `vaultAddress` here will cause the Vault
  CSI Provider to bypass the Agent's cache.

- `vaultNamespace` `(string: "")` - The Vault [namespace](/vault/docs/enterprise/namespaces) to use.

- `vaultSkipTLSVerify` `(string: "false")` - When set to true, skips verification of the Vault server
  certificate. Setting this to true is not recommended for production.

- `vaultCACertPath` `(string: "")` - The path on disk where the Vault CA certificate can be found
  when verifying the Vault server certificate.

- `vaultCADirectory` `(string: "")` - The directory on disk where the Vault CA certificate can be found
  when verifying the Vault server certificate.

- `vaultTLSClientCertPath` `(string: "")` - The path on disk where the client certificate can be found
  for mTLS communications with Vault.

- `vaultTLSClientKeyPath` `(string: "")` - The path on disk where the client key can be found
  for mTLS communications with Vault.

- `vaultTLSServerName` `(string: "")` - The name to use as the SNI host when connecting via TLS.

- `vaultAuthMountPath` `(string: "kubernetes")` - The name of the auth mount used for login.
  Can be a Kubernetes or JWT auth mount. Mutually exclusive with `vaultKubernetesMountPath`.

- `vaultKubernetesMountPath` `(string: "kubernetes")` - The name of the auth mount used for login.
  Can be a Kubernetes or JWT auth mount. Mutually exclusive with `vaultAuthMountPath`.

- `audience` `(string: "")` - Specifies a custom audience for the requesting pod's service account token,
  generated using the
  [TokenRequest API](https://kubernetes.io/docs/reference/kubernetes-api/authentication-resources/token-request-v1/#TokenRequestSpec).
  The resulting token is used to authenticate to Vault, so if you specify an
  [audience](/vault/api-docs/auth/kubernetes#audience) for your Kubernetes auth
  role, it must match the audience specified here. If not set, the token audiences will default to
  the Kubernetes cluster's default API audiences.

- `objects` `(array)` - An array of secrets to retrieve from Vault.

  - `objectName` `(string: "")` - The alias of the object which can be referenced within the secret provider class and
  the name of the secret file.

  - `method` `(string: "GET")` - The type of HTTP request. Supported values include "GET" and "PUT".

  - `secretPath` `(string: "")` - The path in Vault where the secret is located.
    For secrets that are retrieved via HTTP GET method, the `secretPath` can include optional URI parameters,
    for example, the [version of the KV2 secret](/vault/api-docs/secret/kv/kv-v2#read-secret-version):

    ```yaml
    objects: |
      - objectName: "app-secret"
        secretPath: "secret/data/test?version=1"
        secretKey: "password"
    ```

  - `secretKey` `(string: "")` - The key in the Vault secret to extract. If omitted, the whole response from Vault will be written as JSON.

  - `filePermission` `(integer: 0o644)` - The file permissions to set for this secret's file.

  - `encoding` `(string: "utf-8")` - The encoding of the secret value. Supports decoding `utf-8` (default), `hex`, and `base64` values.

  - `secretArgs` `(map: {})` - Additional arguments to be sent to Vault for a specific secret. Arguments can vary
    for different secret engines. For example:

    ```yaml
    secretArgs:
      common_name: 'test.example.com'
      ttl: '24h'
    ```

    ~> `secretArgs` are sent as part of the HTTP request body. Therefore, they are only effective for HTTP PUT/POST requests, for instance,
        the [request used to generate a new certificate](/vault/api-docs/secret/pki#generate-certificate).
        To supply additional parameters for secrets retrieved via HTTP GET, include optional URI parameters in [`secretPath`](#secretpath).

layout  docs page title  Vault CSI Provider Configurations description  This section documents the configurables for the Vault CSI Provider         Command line arguments  The following command line arguments are supported by the Vault CSI provider  Most settings support being set by  in ascending order of precedence     Environment variables   Command line arguments   Secret Provider Class parameters  If installing via the helm chart  they can be set using e g     set  csi extraArgs   debug true          cache size    int  1000     Set the maximum number of Vault tokens that will   be cached in memory  One Vault token will be stored for each pod on the same   node that mounts secrets  Setting to 0 will disable the cache and force each   volume mount request to reauthenticate to Vault       debug    bool  false     Set to true to enable debug level logging       endpoint    string    tmp vault sock      Path to unix socket on which the   provider will listen for gRPC calls from the driver       health addr    string    8080      The address of the HTTP listener   for reporting health       hmac secret name    string   vault csi provider hmac key      Configure the   Kubernetes secret name that the provider creates to store an HMAC key for   generating secret version hashes       vault addr    string   https   127 0 0 1 8200      Default address   for connecting to Vault  Can also be specified via the  VAULT ADDR  environment   variable    Note    It is highly recommended to only set the Vault address when   installing the helm chart  The helm chart will install Vault Agent as a sidecar   to the Vault CSI Provider for caching and renewals  but setting   vault addr    here will cause the Vault CSI Provider to bypass the Agent s cache       vault mount    string   kubernetes      Default Vault mount path   for Kubernetes authentication  Can be overridden per Secret Provider Class   object       vault namespace    string          v1 1 0   Default Vault namespace for Vault   requests  Can also be specified via the  VAULT NAMESPACE  environment variable       vault tls ca cert    string          v1 1 0   Path on disk to a single   PEM encoded CA certificate to trust for Vault  Takes precedence over     vault tls ca directory   Can also be specified via the  VAULT CACERT    environment variable       vault tls ca directory    string          v1 1 0   Path on disk to a   directory of PEM encoded CA certificates to trust for Vault  Can also be   specified via the  VAULT CAPATH  environment variable       vault tls server name    string          v1 1 0   Name to use as the SNI   host when connecting to Vault via TLS  Can also be specified via the    VAULT TLS SERVER NAME  environment variable       vault tls client cert    string          v1 1 0   Path on disk to a   PEM encoded client certificate for mTLS communication with Vault  If set    also requires   vault tls client key   Can also be specified via the    VAULT CLIENT CERT  environment variable       vault tls client key    string          v1 1 0   Path on disk to a   PEM encoded client key for mTLS communication with Vault  If set  also   requires   vault tls client cert   Can also be specified via the    VAULT CLIENT KEY  environment variable       vault tls skip verify    bool  false      v1 1 0   Disable verification of   TLS certificates  Can also be specified via the  VAULT SKIP VERIFY  environment   variable       version    bool  false     print version information and exit      Secret provider class parameters  The following parameters are supported by the Vault provider  Each parameter is an entry under  spec parameters  in a SecretProviderClass object  The full structure is illustrated in the  examples   vault docs platform k8s csi examples       roleName    string         Name of the role to be used during login with Vault      vaultAddress    string         The address of the Vault server    Note    It is   highly recommended to only set the Vault address when installing the helm chart    The helm chart will install Vault Agent as a sidecar to the Vault CSI Provider   for caching and renewals  but setting  vaultAddress  here will cause the Vault   CSI Provider to bypass the Agent s cache      vaultNamespace    string         The Vault  namespace   vault docs enterprise namespaces  to use      vaultSkipTLSVerify    string   false      When set to true  skips verification of the Vault server   certificate  Setting this to true is not recommended for production      vaultCACertPath    string         The path on disk where the Vault CA certificate can be found   when verifying the Vault server certificate      vaultCADirectory    string         The directory on disk where the Vault CA certificate can be found   when verifying the Vault server certificate      vaultTLSClientCertPath    string         The path on disk where the client certificate can be found   for mTLS communications with Vault      vaultTLSClientKeyPath    string         The path on disk where the client key can be found   for mTLS communications with Vault      vaultTLSServerName    string         The name to use as the SNI host when connecting via TLS      vaultAuthMountPath    string   kubernetes      The name of the auth mount used for login    Can be a Kubernetes or JWT auth mount  Mutually exclusive with  vaultKubernetesMountPath       vaultKubernetesMountPath    string   kubernetes      The name of the auth mount used for login    Can be a Kubernetes or JWT auth mount  Mutually exclusive with  vaultAuthMountPath       audience    string         Specifies a custom audience for the requesting pod s service account token    generated using the    TokenRequest API  https   kubernetes io docs reference kubernetes api authentication resources token request v1  TokenRequestSpec     The resulting token is used to authenticate to Vault  so if you specify an    audience   vault api docs auth kubernetes audience  for your Kubernetes auth   role  it must match the audience specified here  If not set  the token audiences will default to   the Kubernetes cluster s default API audiences      objects    array     An array of secrets to retrieve from Vault        objectName    string         The alias of the object which can be referenced within the secret provider class and   the name of the secret file        method    string   GET      The type of HTTP request  Supported values include  GET  and  PUT         secretPath    string         The path in Vault where the secret is located      For secrets that are retrieved via HTTP GET method  the  secretPath  can include optional URI parameters      for example  the  version of the KV2 secret   vault api docs secret kv kv v2 read secret version           yaml     objects            objectName   app secret          secretPath   secret data test version 1          secretKey   password                secretKey    string         The key in the Vault secret to extract  If omitted  the whole response from Vault will be written as JSON        filePermission    integer  0o644     The file permissions to set for this secret s file        encoding    string   utf 8      The encoding of the secret value  Supports decoding  utf 8   default    hex   and  base64  values        secretArgs    map         Additional arguments to be sent to Vault for a specific secret  Arguments can vary     for different secret engines  For example          yaml     secretArgs        common name   test example com        ttl   24h                   secretArgs  are sent as part of the HTTP request body  Therefore  they are only effective for HTTP PUT POST requests  for instance          the  request used to generate a new certificate   vault api docs secret pki generate certificate           To supply additional parameters for secrets retrieved via HTTP GET  include optional URI parameters in   secretPath    secretpath


vault The Vault CSI Provider can be installed using Vault Helm Installing the Vault CSI provider layout docs Prerequisites page title Vault CSI Provider Installation

Answer:
---
layout: docs
page_title: Vault CSI Provider Installation
description: The Vault CSI Provider can be installed using Vault Helm.
---

# Installing the Vault CSI provider

## Prerequisites

- Kubernetes 1.16+ for both the master and worker nodes (Linux-only)
- [Secrets store CSI driver](https://secrets-store-csi-driver.sigs.k8s.io/getting-started/installation.html) installed
- `TokenRequest` endpoint available, which requires setting the flags
  `--service-account-signing-key-file` and `--service-account-issuer` for
  `kube-apiserver`. Set by default from 1.20+ and earlier in most managed services.

## Installation using helm

The [Vault Helm chart](/vault/docs/platform/k8s/helm) is the recommended way to
install and configure the Vault CSI Provider in Kubernetes.

To install a new instance of Vault and the Vault CSI Provider, first add the
HashiCorp helm repository and ensure you have access to the chart:

~> **Note:** Vault CSI Provider Helm installation requires Vault Helm 0.10.0+.

@include 'helm/repo.mdx'

Then install the chart and enable the CSI feature by setting the
`csi.enabled` value to `true`:

~> **Note:** this will also install the Vault server and Agent Injector.

```shell-session
$ helm install vault hashicorp/vault --set="csi.enabled=true"
```

Upgrades may be performed with `helm upgrade` on an existing installation. Please
always run Helm with `--dry-run` before any install or upgrade to verify
changes.

You can see all the available values settings by running `helm inspect values hashicorp/vault` or by reading the [Vault Helm Configuration
Docs](/vault/docs/platform/k8s/helm/configuration). Commonly used values in the Helm
chart include limiting the namespaces the Vault CSI Provider runs in, TLS options and
more.

## Installation on OpenShift

We recommend using the [Vault agent injector on Openshift](/vault/docs/platform/k8s/helm/openshift)
instead of the Secrets Store CSI driver. OpenShift
[does not recommend](https://docs.openshift.com/container-platform/4.9/storage/persistent_storage/persistent-storage-hostpath.html)
using `hostPath` mounting in production or
[certify Helm charts](https://github.com/redhat-certification/chart-verifier/blob/dbf89bff2d09142e4709d689a9f4037a739c2244/docs/helm-chart-checks.md#table-2-helm-chart-default-checks)
using CSI objects because pods must run as privileged. Pods will have elevated access to
other pods on the same node, which OpenShift does not recommend.

You can run the Secrets Store CSI driver with additional
security configurations on a OpenShift development
or testing cluster.

Deploy the Secrets Store CSI driver and Vault Helm chart
to your OpenShift cluster.

Then, patch the `DaemonSet` for the Vault CSI provider to
run with a privileged security context.

```shell-session
$ kubectl patch daemonset vault-csi-provider \
  --type='json' \
  --patch='[{"op": "add", "path": "/spec/template/spec/containers/0/securityContext", "value": {"privileged": true} }]'
```

The Secrets Store CSI driver and Vault CSI provider need `hostPath` mount access.
Add the service account for the Secrets Store CSI driver to the `privileged`
[security context constraint](https://cloud.redhat.com/blog/managing-sccs-in-openshift).

```shell-session
$ oc adm policy add-scc-to-user privileged system:serviceaccount:${KUBERNETES_VAULT_NAMESPACE}:secrets-store-csi-driver
```

Add the service account for the Vault CSI provider to the `privileged`
security context constraint.

```shell-session
$ oc adm policy add-scc-to-user privileged system:serviceaccount:${KUBERNETES_VAULT_NAMESPACE}:vault-csi-provider
```

You need to give additional access to the application retrieving secrets with the Vault CSI provider.
Create a `SecurityContextConstraint` to `allowHostDirVolumePlugin`, `allowHostDirVolumePlugin`, and
`allowHostPorts` for the application's service account.
You can adjust the other attributes based on your application's runtime configuration.

```shell-session
$ cat > application-scc.yaml << EOF
apiVersion: security.openshift.io/v1
kind: SecurityContextConstraints
metadata:
  name: vault-csi-provider
allowPrivilegedContainer: false
allowHostDirVolumePlugin: true
allowHostNetwork: true
allowHostPorts: true
allowHostIPC: false
allowHostPID: false
readOnlyRootFilesystem: false
defaultAddCapabilities:
- SYS_ADMIN
runAsUser:
  type: RunAsAny
seLinuxContext:
  type: RunAsAny
fsGroup:
  type: RunAsAny
users:
- system:serviceaccount:${KUBERNETES_APPLICATION_NAMESPACE}:${APPLICATION_SERVICE_ACCOUNT}
EOF
```

Add the security context constraint for the application.

```shell-session
$ kubectl apply -f application-scc.yaml
```

layout  docs page title  Vault CSI Provider Installation description  The Vault CSI Provider can be installed using Vault Helm         Installing the Vault CSI provider     Prerequisites    Kubernetes 1 16  for both the master and worker nodes  Linux only     Secrets store CSI driver  https   secrets store csi driver sigs k8s io getting started installation html  installed    TokenRequest  endpoint available  which requires setting the flags      service account signing key file  and    service account issuer  for    kube apiserver   Set by default from 1 20  and earlier in most managed services      Installation using helm  The  Vault Helm chart   vault docs platform k8s helm  is the recommended way to install and configure the Vault CSI Provider in Kubernetes   To install a new instance of Vault and the Vault CSI Provider  first add the HashiCorp helm repository and ensure you have access to the chart        Note    Vault CSI Provider Helm installation requires Vault Helm 0 10 0     include  helm repo mdx   Then install the chart and enable the CSI feature by setting the  csi enabled  value to  true         Note    this will also install the Vault server and Agent Injector      shell session   helm install vault hashicorp vault   set  csi enabled true       Upgrades may be performed with  helm upgrade  on an existing installation  Please always run Helm with    dry run  before any install or upgrade to verify changes   You can see all the available values settings by running  helm inspect values hashicorp vault  or by reading the  Vault Helm Configuration Docs   vault docs platform k8s helm configuration   Commonly used values in the Helm chart include limiting the namespaces the Vault CSI Provider runs in  TLS options and more      Installation on OpenShift  We recommend using the  Vault agent injector on Openshift   vault docs platform k8s helm openshift  instead of the Secrets Store CSI driver  OpenShift  does not recommend  https   docs openshift com container platform 4 9 storage persistent storage persistent storage hostpath html  using  hostPath  mounting in production or  certify Helm charts  https   github com redhat certification chart verifier blob dbf89bff2d09142e4709d689a9f4037a739c2244 docs helm chart checks md table 2 helm chart default checks  using CSI objects because pods must run as privileged  Pods will have elevated access to other pods on the same node  which OpenShift does not recommend   You can run the Secrets Store CSI driver with additional security configurations on a OpenShift development or testing cluster   Deploy the Secrets Store CSI driver and Vault Helm chart to your OpenShift cluster   Then  patch the  DaemonSet  for the Vault CSI provider to run with a privileged security context      shell session   kubectl patch daemonset vault csi provider       type  json        patch     op    add    path     spec template spec containers 0 securityContext    value     privileged   true           The Secrets Store CSI driver and Vault CSI provider need  hostPath  mount access  Add the service account for the Secrets Store CSI driver to the  privileged   security context constraint  https   cloud redhat com blog managing sccs in openshift       shell session   oc adm policy add scc to user privileged system serviceaccount   KUBERNETES VAULT NAMESPACE  secrets store csi driver      Add the service account for the Vault CSI provider to the  privileged  security context constraint      shell session   oc adm policy add scc to user privileged system serviceaccount   KUBERNETES VAULT NAMESPACE  vault csi provider      You need to give additional access to the application retrieving secrets with the Vault CSI provider  Create a  SecurityContextConstraint  to  allowHostDirVolumePlugin    allowHostDirVolumePlugin   and  allowHostPorts  for the application s service account  You can adjust the other attributes based on your application s runtime configuration      shell session   cat   application scc yaml    EOF apiVersion  security openshift io v1 kind  SecurityContextConstraints metadata    name  vault csi provider allowPrivilegedContainer  false allowHostDirVolumePlugin  true allowHostNetwork  true allowHostPorts  true allowHostIPC  false allowHostPID  false readOnlyRootFilesystem  false defaultAddCapabilities    SYS ADMIN runAsUser    type  RunAsAny seLinuxContext    type  RunAsAny fsGroup    type  RunAsAny users    system serviceaccount   KUBERNETES APPLICATION NAMESPACE    APPLICATION SERVICE ACCOUNT  EOF      Add the security context constraint for the application      shell session   kubectl apply  f application scc yaml