vault Azure secrets engine page title Azure Secrets Engine The Azure Vault secrets engine dynamically generates Azure layout docs service principals and role assignments

Answer:
---
layout: docs
page_title: Azure - Secrets Engine
description: |-
  The Azure Vault secrets engine dynamically generates Azure
  service principals and role assignments.
---

# Azure secrets engine

The Azure secrets engine dynamically generates Azure service principals along
with role and group assignments. Vault roles can be mapped to one or more Azure
roles, and optionally group assignments, providing a simple, flexible way to
manage the permissions granted to generated service principals.

Each service principal is associated with a Vault lease. When the lease expires
(either during normal revocation or through early revocation), the service
principal is automatically deleted.

If an existing service principal is specified as part of the role configuration,
a new password will be dynamically generated instead of a new service principal.
The password will be deleted when the lease is revoked.

## Setup

<Note>

  You can configure the Azure secrets engine with the Vault API or
  established environment variables such as `AZURE_CLIENT_ID` or
  `AZURE_CLIENT_SECRET`. If you use both methods, note that
  environment variables always take precedence over API values.

</Note>

Most secrets engines must be configured in advance before they can perform their
functions. These steps are usually completed by an operator or configuration
management tool.

1. Enable the Azure secrets engine:

   ```shell
   $ vault secrets enable azure
   Success! Enabled the azure secrets engine at: azure/
   ```

   By default, the secrets engine will mount at the name of the engine. To
   enable the secrets engine at a different path, use the `-path` argument.

1. Configure the secrets engine with account credentials:

   ```shell
   $ vault write azure/config \
       subscription_id=$AZURE_SUBSCRIPTION_ID \
       tenant_id=$AZURE_TENANT_ID \
       client_id=$AZURE_CLIENT_ID \
       client_secret=$AZURE_CLIENT_SECRET

   Success! Data written to: azure/config
   ```

   If you are running Vault inside an Azure VM with MSI enabled, `client_id` and
   `client_secret` may be omitted. For more information on authentication, see the [authentication](#authentication) section below.

   In some cases, you cannot set sensitive account credentials in your
   Vault configuration. For example, your organization may require that all
   security credentials are short-lived or explicitly tied to a machine identity.

   To provide managed identity security credentials to Vault, we recommend using Vault
   [plugin workload identity federation](#plugin-workload-identity-federation-wif)
   (WIF) as shown below.

1.  Alternatively, configure the audience claim value and the Client, Tenant and Subscription IDs for plugin workload identity federation:

   ```text
   $ vault write azure/config \
       subscription_id=$AZURE_SUBSCRIPTION_ID \
       tenant_id=$AZURE_TENANT_ID \
       client_id=$AZURE_CLIENT_ID \
       identity_token_audience=$TOKEN_AUDIENCE
   ```

   The Vault identity token provider signs the plugin identity token JWT internally.
   If a trust relationship exists between Vault and Azure through WIF, the secrets
   engine can exchange the Vault identity token for a federated access token.

   To configure a trusted relationship between Vault and Azure:

     - You must configure the [identity token issuer backend](/vault/api-docs/secret/identity/tokens#configure-the-identity-tokens-backend)
       for Vault.
     - Azure must have a
       [federated identity credential](https://learn.microsoft.com/en-us/entra/workload-id/workload-identity-federation-create-trust?pivots=identity-wif-apps-methods-azp#configure-a-federated-identity-credential-on-an-app)
       configured with information about the fully qualified and network-reachable
       issuer URL for the Vault plugin
       [identity token provider](/vault/api-docs/secret/identity/tokens#read-plugin-identity-well-known-configurations).

   Establishing a trusted relationship between Vault and Azure ensures that Azure
   can fetch JWKS
   [public keys](/vault/api-docs/secret/identity/tokens#read-active-public-keys)
   and verify the plugin identity token signature.

1. Configure a role. A role may be set up with either an existing service principal, or
   a set of Azure roles that will be assigned to a dynamically created service principal.

To configure a role called "my-role" with an existing service principal:

```shell-session
$ vault write azure/roles/my-role \
    application_object_id=<existing_app_obj_id> \
    ttl=1h
```

Alternatively, to configure the role to create a new service principal with Azure roles:

```shell-session
$ vault write azure/roles/my-role ttl=1h azure_roles=-<<EOF
    [
        {
            "role_name": "Contributor",
            "scope":  "/subscriptions/<uuid>/resourceGroups/Website"
        }
    ]
EOF
```

Roles may also have their own TTL configuration that is separate from the mount's
TTL. For more information on roles see the [roles](#roles) section below.

## Usage

After the secrets engine is configured and a user/machine has a Vault token with
the proper permissions, it can generate credentials. The usage pattern is the same
whether an existing or dynamic service principal is used.

To generate a credential using the "my-role" role:

```shell-session
$ vault read azure/creds/my-role

Key                Value
---                -----
lease_id           azure/creds/sp_role/1afd0969-ad23-73e2-f974-962f7ac1c2b4
lease_duration     60m
lease_renewable    true
client_id          408bf248-dd4e-4be5-919a-7f6207a307ab
client_secret      ad06228a-2db9-4e0a-8a5d-e047c7f32594
```

This endpoint generates a renewable set of credentials. The application can login
using the `client_id`/`client_secret` and will have access provided by configured service
principal or the Azure roles set in the "my-role" configuration.

## Root credential rotation

If the mount is configured with credentials directly, the credential's key may be
rotated to a Vault-generated value that is not accessible by the operator.
This will ensure that only Vault is able to access the "root" user that Vault uses to
manipulate dynamic & static credentials.

```shell-session
vault write -f azure/rotate-root
```

For more details on this operation, please see the
[Root Credential Rotation](/vault/api-docs/secret/azure#rotate-root) API docs.

## Roles

Vault roles let you configure either an existing service principal or a set of Azure roles, along with
role-specific TTL parameters. If an existing service principal is not provided, the configured Azure
roles will be assigned to a newly created service principal. The Vault role may optionally specify
role-specific `ttl` and/or `max_ttl` values. When the lease is created, the more restrictive of the
mount or role TTL value will be used.

### Application object IDs

If an existing service principal is to be used, the Application Object ID must be set on the Vault role.
This ID can be found by inspecting the desired Application with the `az` CLI tool, or via the Azure Portal. Note
that the Application **Object** ID must be provided, not the Application ID.

### Azure roles

If dynamic service principals are used, Azure roles must be configured on the Vault role.
Azure roles are provided as a JSON list, with each element describing an Azure role and scope to be assigned.
Azure roles may be specified using the `role_name` parameter ("Owner"), or `role_id`
("/subscriptions/.../roleDefinitions/...").
`role_id` is the definitive ID that's used during Vault operation; `role_name` is a convenience during
role management operations. All roles _must exist_ when the configuration is written or the operation will fail. The role lookup priority is:

1. If `role_id` is provided, it is validated and the corresponding `role_name` updated.
1. If only `role_name` is provided, a case-insensitive search-by-name is made, succeeding
   only if _exactly one_ matching role is found. The `role_id` field will updated with the matching role ID.

The `scope` must be provided for every role assignment.

### Azure groups

If dynamic service principals are used, a list of Azure groups may be configured on the Vault role.
When the service principal is created, it will be assigned to these groups. Similar to the format used
for specifying Azure roles, Azure groups may be referenced by either their `group_name` or `object_id`.
Group specification by name must yield a single matching group.

Example of role configuration:

```shell-session
$ vault write azure/roles/my-role \
    ttl=1h \
    max_ttl=24h \
    azure_roles=@az_roles.json \
    azure_groups=@az_groups.json

$ cat az_roles.json
[
  {
    "role_name": "Contributor",
    "scope":  "/subscriptions/<uuid>/resourceGroups/Website"
  },
  {
    "role_id": "/subscriptions/<uuid>/providers/Microsoft.Authorization/roleDefinitions/<uuid>",
    "scope":  "/subscriptions/<uuid>"
  },
  {
    "role_name": "This won't matter as it will be overwritten",
    "role_id": "/subscriptions/<uuid>/providers/Microsoft.Authorization/roleDefinitions/<uuid>",
    "scope":  "/subscriptions/<uuid>/resourceGroups/Database"
  }
]

$ cat az_groups.json
[
  {
    "group_name": "foo"
  },
  {
    "group_name": "This won't matter as it will be overwritten",
    "object_id": "a6a834a6-36c3-4575-8e2b-05095963d603"
  }
]
```

### Permanently delete Azure objects

If dynamic service principals are used, the option to permanently delete the applications and service principals created by Vault may be configured on the Vault role.
When this option is enabled and a lease is expired or revoked, the application and service principal associated with the lease will be [permanently deleted](https://docs.microsoft.com/en-us/graph/api/directory-deleteditems-delete) from the Azure Active Directory.
As a result, these objects will not count toward the [quota](https://docs.microsoft.com/en-us/azure/azure-resource-manager/management/azure-subscription-service-limits#active-directory-limits) of total resources in an Azure tenant. When this option is not enabled
and a lease is expired or revoked, the application and service principal associated with the lease will be deleted, but not permanently. These objects will be available to restore for 30 days from deletion.

Example of role configuration:

```shell-session
$ vault write azure/roles/my-role permanently_delete=true ttl=1h azure_roles=-<<EOF
    [
        {
            "role_name": "Contributor",
            "scope":  "/subscriptions/<uuid>/resourceGroups/Website"
        }
    ]
EOF
```

## Authentication

The Azure secrets backend must have sufficient permissions to read Azure role information and manage
service principals. The authentication parameters can be set in the backend configuration or as environment
variables. Environment variables will take precedence. The individual parameters are described in the
[configuration][config] section of the API docs.

If the client ID or secret are not present and Vault is running on an Azure VM, Vault will attempt to use
[Managed Service Identity (MSI)](https://docs.microsoft.com/en-us/azure/active-directory/managed-service-identity/overview)
to access Azure. Note that when MSI is used, tenant and subscription IDs must still be explicitly provided
in the configuration or environment variables.

### MS Graph API permissions

The following MS Graph [API permissions](https://learn.microsoft.com/en-us/azure/active-directory/develop/permissions-consent-overview#types-of-permissions)
must be assigned to the service principal provided to Vault for managing Azure. The permissions
differ depending on if you're using [dynamic or existing](#choosing-between-dynamic-or-existing-service-principals)
service principals.

#### Dynamic Service Principals

| Permission Name               | Type        |
| ----------------------------- | ----------- |
| Application.ReadWrite.OwnedBy | Application |
| GroupMember.ReadWrite.All     | Application |

~> **Note**: If you plan to use the [rotate root](/vault/api-docs/secret/azure#rotate-root)
credentials API, you'll need to change `Application.ReadWrite.OwnedBy` to `Application.ReadWrite.All`.

#### Existing Service Principals

| Permission Name               | Type        |
| ----------------------------- | ----------- |
| Application.ReadWrite.All     | Application |
| GroupMember.ReadWrite.All     | Application |

### Role assignments

The following Azure [role assignments](https://learn.microsoft.com/en-us/azure/role-based-access-control/role-assignments-cli)
must be granted in order for the secrets engine to manage role assignments for service
principles it creates.

| Role                                           | Scope        | Security Principal                          |
|------------------------------------------------| ------------ | ------------------------------------------- |
| [User Access Administrator][user_access_admin] | Subscription | Service Principal ID given in configuration |

## Plugin Workload Identity Federation (WIF)

<EnterpriseAlert product="vault" />

The Azure secrets engine supports the plugin WIF workflow, and has a source of identity called
a plugin identity token. The plugin identity token is a JWT that is signed internally by Vault's
[plugin identity token issuer](/vault/api-docs/secret/identity/tokens#read-plugin-workload-identity-issuer-s-openid-configuration).

If there is a trust relationship configured between Vault and Azure through
[workload identity federation](https://learn.microsoft.com/en-us/entra/workload-id/workload-identity-federation),
the secrets engine can exchange its identity token for short-lived access tokens needed to
perform its actions.

Exchanging identity tokens for access tokens lets the Azure secrets engine
operate without configuring explicit access to sensitive client credentials.

To configure the secrets engine to use plugin WIF:

1. Ensure that Vault [openid-configuration](/vault/api-docs/secret/identity/tokens#read-plugin-identity-token-issuer-s-openid-configuration)
   and [public JWKS](/vault/api-docs/secret/identity/tokens#read-plugin-identity-token-issuer-s-public-jwks)
   APIs are network-reachable by Azure. We recommend using an API proxy or gateway
   if you need to limit Vault API exposure.

1. Configure a
   [federated identity credential](https://learn.microsoft.com/en-us/entra/workload-id/workload-identity-federation-create-trust?pivots=identity-wif-apps-methods-azp#configure-a-federated-identity-credential-on-an-app)
   on a dedicated application registration in Azure to establish a trust relationship with Vault.
   1. The issuer URL **must** point at your [Vault plugin identity token issuer](/vault/api-docs/secret/identity/tokens#read-plugin-workload-identity-issuer-s-openid-configuration) with the
   `/.well-known/openid-configuration` suffix removed. For example:
   `https://host:port/v1/identity/oidc/plugins`.
   1. The subject identifier **must** match the unique `sub` claim issued by plugin identity tokens.
   The subject identifier should have the form `plugin-identity:<NAMESPACE>:secret:<AZURE_MOUNT_ACCESSOR>`.
   1. The audience should be under 600 characters. The default value in Azure is `api://AzureADTokenExchange`.

1. Configure the Azure secrets engine with the subscription, client and tenant IDs and the OIDC audience value.

   ```shell-session
   $ vault write azure/config \
     subscription_id=$AZURE_SUBSCRIPTION_ID \
     tenant_id=$AZURE_TENANT_ID \
     client_id=$AZURE_CLIENT_ID \
     identity_token_audience="vault.example/v1/identity/oidc/plugins"
   ```

Your secrets engine can now use plugin WIF for its configuration credentials.
By default, WIF [credentials](https://learn.microsoft.com/en-us/entra/identity-platform/access-tokens#token-lifetime)
have a time-to-live of 1 hour and automatically refresh when they expire.

Please see the [API documentation](/vault/api-docs/secret/azure#configure-access)
for more details on the fields associated with plugin WIF.

## Choosing between dynamic or existing service principals

Dynamic service principals are preferred if the desired Azure resources can be provided
via the RBAC system and Azure roles defined in the Vault role. This form of credential is
completely decoupled from any other clients, is not subject to permission changes after
issuance, and offers the best audit granularity.

Access to some Azure services cannot be provided with the RBAC system, however. In these
cases, an existing service principal can be set up with the necessary access, and Vault
can create new passwords for this service principal. Any changes to the service principal
permissions affect all clients. Furthermore, Azure does not provide any logging with
regard to _which_ credential was used for an operation.

An important limitation when using an existing service principal is that Azure limits the
number of passwords for a single Application. This limit is based on Application object
size and isn't firmly specified, but in practice hundreds of passwords can be issued per
Application. An error will be returned if the object size is reached. This limit can be
managed by reducing the role TTL, or by creating another Vault role against a different
Azure service principal configured with the same permissions.

## Additional notes

- **If a referenced Azure role doesn't exist, a credential will not be generated.**
  Service principals will only be generated if _all_ role assignments are successful.
  This is important to note if you're using custom Azure role definitions that might be deleted
  at some point.

- Azure roles are assigned only once, when the service principal is created. If the
  Vault role changes the list of Azure roles, these changes will not be reflected in
  any existing service principal, even after token renewal.

- The time required to issue a credential is roughly proportional to the number of
  Azure roles that must be assigned. This operation make take some time (10s of seconds
  are common, and over a minute has been seen).

- Service principal credential timeouts are not used. Vault will revoke access by
  deleting the service principal.

- The Application Name for dynamic service principals will be prefixed with `vault-`. Similarly
  the `keyId` of any passwords added to an existing service principal will begin with
  `ffffff`. These may be used to search for Vault-created credentials using the `az` tool
  or Portal.

## Azure debug logs

The Azure secret engine plugin supports debug logging which includes additional information
about requests and responses from the Azure API.

To enable the Azure debug logs, set the `AZURE_SDK_GO_LOGGING`  environment variable to `all` on your Vault
server:

```shell
AZURE_SDK_GO_LOGGING=all
```

## Help & support

The Azure secrets engine is written as an external Vault plugin and
thus exists outside the main Vault repository. It is automatically bundled with
Vault releases, but the code is managed separately.

Please report issues, add feature requests, and submit contributions to the
[vault-plugin-secrets-azure repo][repo] on GitHub.

## Tutorial

Refer to the [Azure Secrets
Engine](/vault/tutorials/secrets-management/azure-secrets) tutorial
to learn how to use the Azure secrets engine to dynamically generate Azure credentials.

## API

The Azure secrets engine has a full HTTP API. Please see the [Azure secrets engine API docs][api]
for more details.

[api]: /vault/api-docs/secret/azure
[config]: /vault/api-docs/secret/azure#configure-access
[repo]: https://github.com/hashicorp/vault-plugin-secrets-azure
[user_access_admin]: https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#user-access-administrator

layout  docs page title  Azure   Secrets Engine description       The Azure Vault secrets engine dynamically generates Azure   service principals and role assignments         Azure secrets engine  The Azure secrets engine dynamically generates Azure service principals along with role and group assignments  Vault roles can be mapped to one or more Azure roles  and optionally group assignments  providing a simple  flexible way to manage the permissions granted to generated service principals   Each service principal is associated with a Vault lease  When the lease expires  either during normal revocation or through early revocation   the service principal is automatically deleted   If an existing service principal is specified as part of the role configuration  a new password will be dynamically generated instead of a new service principal  The password will be deleted when the lease is revoked      Setup   Note     You can configure the Azure secrets engine with the Vault API or   established environment variables such as  AZURE CLIENT ID  or    AZURE CLIENT SECRET   If you use both methods  note that   environment variables always take precedence over API values     Note   Most secrets engines must be configured in advance before they can perform their functions  These steps are usually completed by an operator or configuration management tool   1  Enable the Azure secrets engine         shell      vault secrets enable azure    Success  Enabled the azure secrets engine at  azure             By default  the secrets engine will mount at the name of the engine  To    enable the secrets engine at a different path  use the   path  argument   1  Configure the secrets engine with account credentials         shell      vault write azure config          subscription id  AZURE SUBSCRIPTION ID          tenant id  AZURE TENANT ID          client id  AZURE CLIENT ID          client secret  AZURE CLIENT SECRET     Success  Data written to  azure config            If you are running Vault inside an Azure VM with MSI enabled   client id  and     client secret  may be omitted  For more information on authentication  see the  authentication   authentication  section below      In some cases  you cannot set sensitive account credentials in your    Vault configuration  For example  your organization may require that all    security credentials are short lived or explicitly tied to a machine identity      To provide managed identity security credentials to Vault  we recommend using Vault     plugin workload identity federation   plugin workload identity federation wif      WIF  as shown below   1   Alternatively  configure the audience claim value and the Client  Tenant and Subscription IDs for plugin workload identity federation         text      vault write azure config          subscription id  AZURE SUBSCRIPTION ID          tenant id  AZURE TENANT ID          client id  AZURE CLIENT ID          identity token audience  TOKEN AUDIENCE            The Vault identity token provider signs the plugin identity token JWT internally     If a trust relationship exists between Vault and Azure through WIF  the secrets    engine can exchange the Vault identity token for a federated access token      To configure a trusted relationship between Vault and Azure          You must configure the  identity token issuer backend   vault api docs secret identity tokens configure the identity tokens backend         for Vault         Azure must have a         federated identity credential  https   learn microsoft com en us entra workload id workload identity federation create trust pivots identity wif apps methods azp configure a federated identity credential on an app         configured with information about the fully qualified and network reachable        issuer URL for the Vault plugin         identity token provider   vault api docs secret identity tokens read plugin identity well known configurations       Establishing a trusted relationship between Vault and Azure ensures that Azure    can fetch JWKS     public keys   vault api docs secret identity tokens read active public keys     and verify the plugin identity token signature   1  Configure a role  A role may be set up with either an existing service principal  or    a set of Azure roles that will be assigned to a dynamically created service principal   To configure a role called  my role  with an existing service principal      shell session   vault write azure roles my role       application object id  existing app obj id        ttl 1h      Alternatively  to configure the role to create a new service principal with Azure roles      shell session   vault write azure roles my role ttl 1h azure roles    EOF                              role name    Contributor                scope      subscriptions  uuid  resourceGroups Website                  EOF      Roles may also have their own TTL configuration that is separate from the mount s TTL  For more information on roles see the  roles   roles  section below      Usage  After the secrets engine is configured and a user machine has a Vault token with the proper permissions  it can generate credentials  The usage pattern is the same whether an existing or dynamic service principal is used   To generate a credential using the  my role  role      shell session   vault read azure creds my role  Key                Value                          lease id           azure creds sp role 1afd0969 ad23 73e2 f974 962f7ac1c2b4 lease duration     60m lease renewable    true client id          408bf248 dd4e 4be5 919a 7f6207a307ab client secret      ad06228a 2db9 4e0a 8a5d e047c7f32594      This endpoint generates a renewable set of credentials  The application can login using the  client id   client secret  and will have access provided by configured service principal or the Azure roles set in the  my role  configuration      Root credential rotation  If the mount is configured with credentials directly  the credential s key may be rotated to a Vault generated value that is not accessible by the operator  This will ensure that only Vault is able to access the  root  user that Vault uses to manipulate dynamic   static credentials      shell session vault write  f azure rotate root      For more details on this operation  please see the  Root Credential Rotation   vault api docs secret azure rotate root  API docs      Roles  Vault roles let you configure either an existing service principal or a set of Azure roles  along with role specific TTL parameters  If an existing service principal is not provided  the configured Azure roles will be assigned to a newly created service principal  The Vault role may optionally specify role specific  ttl  and or  max ttl  values  When the lease is created  the more restrictive of the mount or role TTL value will be used       Application object IDs  If an existing service principal is to be used  the Application Object ID must be set on the Vault role  This ID can be found by inspecting the desired Application with the  az  CLI tool  or via the Azure Portal  Note that the Application   Object   ID must be provided  not the Application ID       Azure roles  If dynamic service principals are used  Azure roles must be configured on the Vault role  Azure roles are provided as a JSON list  with each element describing an Azure role and scope to be assigned  Azure roles may be specified using the  role name  parameter   Owner    or  role id     subscriptions     roleDefinitions         role id  is the definitive ID that s used during Vault operation   role name  is a convenience during role management operations  All roles  must exist  when the configuration is written or the operation will fail  The role lookup priority is   1  If  role id  is provided  it is validated and the corresponding  role name  updated  1  If only  role name  is provided  a case insensitive search by name is made  succeeding    only if  exactly one  matching role is found  The  role id  field will updated with the matching role ID   The  scope  must be provided for every role assignment       Azure groups  If dynamic service principals are used  a list of Azure groups may be configured on the Vault role  When the service principal is created  it will be assigned to these groups  Similar to the format used for specifying Azure roles  Azure groups may be referenced by either their  group name  or  object id   Group specification by name must yield a single matching group   Example of role configuration      shell session   vault write azure roles my role       ttl 1h       max ttl 24h       azure roles  az roles json       azure groups  az groups json    cat az roles json            role name    Contributor        scope      subscriptions  uuid  resourceGroups Website                role id     subscriptions  uuid  providers Microsoft Authorization roleDefinitions  uuid         scope      subscriptions  uuid                 role name    This won t matter as it will be overwritten        role id     subscriptions  uuid  providers Microsoft Authorization roleDefinitions  uuid         scope      subscriptions  uuid  resourceGroups Database           cat az groups json            group name    foo                group name    This won t matter as it will be overwritten        object id    a6a834a6 36c3 4575 8e2b 05095963d603                 Permanently delete Azure objects  If dynamic service principals are used  the option to permanently delete the applications and service principals created by Vault may be configured on the Vault role  When this option is enabled and a lease is expired or revoked  the application and service principal associated with the lease will be  permanently deleted  https   docs microsoft com en us graph api directory deleteditems delete  from the Azure Active Directory  As a result  these objects will not count toward the  quota  https   docs microsoft com en us azure azure resource manager management azure subscription service limits active directory limits  of total resources in an Azure tenant  When this option is not enabled and a lease is expired or revoked  the application and service principal associated with the lease will be deleted  but not permanently  These objects will be available to restore for 30 days from deletion   Example of role configuration      shell session   vault write azure roles my role permanently delete true ttl 1h azure roles    EOF                              role name    Contributor                scope      subscriptions  uuid  resourceGroups Website                  EOF         Authentication  The Azure secrets backend must have sufficient permissions to read Azure role information and manage service principals  The authentication parameters can be set in the backend configuration or as environment variables  Environment variables will take precedence  The individual parameters are described in the  configuration  config  section of the API docs   If the client ID or secret are not present and Vault is running on an Azure VM  Vault will attempt to use  Managed Service Identity  MSI   https   docs microsoft com en us azure active directory managed service identity overview  to access Azure  Note that when MSI is used  tenant and subscription IDs must still be explicitly provided in the configuration or environment variables       MS Graph API permissions  The following MS Graph  API permissions  https   learn microsoft com en us azure active directory develop permissions consent overview types of permissions  must be assigned to the service principal provided to Vault for managing Azure  The permissions differ depending on if you re using  dynamic or existing   choosing between dynamic or existing service principals  service principals        Dynamic Service Principals    Permission Name                 Type                                                            Application ReadWrite OwnedBy   Application     GroupMember ReadWrite All       Application         Note    If you plan to use the  rotate root   vault api docs secret azure rotate root  credentials API  you ll need to change  Application ReadWrite OwnedBy  to  Application ReadWrite All         Existing Service Principals    Permission Name                 Type                                                            Application ReadWrite All       Application     GroupMember ReadWrite All       Application        Role assignments  The following Azure  role assignments  https   learn microsoft com en us azure role based access control role assignments cli  must be granted in order for the secrets engine to manage role assignments for service principles it creates     Role                                             Scope          Security Principal                                                                                User Access Administrator  user access admin    Subscription   Service Principal ID given in configuration       Plugin Workload Identity Federation  WIF    EnterpriseAlert product  vault      The Azure secrets engine supports the plugin WIF workflow  and has a source of identity called a plugin identity token  The plugin identity token is a JWT that is signed internally by Vault s  plugin identity token issuer   vault api docs secret identity tokens read plugin workload identity issuer s openid configuration    If there is a trust relationship configured between Vault and Azure through  workload identity federation  https   learn microsoft com en us entra workload id workload identity federation   the secrets engine can exchange its identity token for short lived access tokens needed to perform its actions   Exchanging identity tokens for access tokens lets the Azure secrets engine operate without configuring explicit access to sensitive client credentials   To configure the secrets engine to use plugin WIF   1  Ensure that Vault  openid configuration   vault api docs secret identity tokens read plugin identity token issuer s openid configuration     and  public JWKS   vault api docs secret identity tokens read plugin identity token issuer s public jwks     APIs are network reachable by Azure  We recommend using an API proxy or gateway    if you need to limit Vault API exposure   1  Configure a     federated identity credential  https   learn microsoft com en us entra workload id workload identity federation create trust pivots identity wif apps methods azp configure a federated identity credential on an app     on a dedicated application registration in Azure to establish a trust relationship with Vault     1  The issuer URL   must   point at your  Vault plugin identity token issuer   vault api docs secret identity tokens read plugin workload identity issuer s openid configuration  with the       well known openid configuration  suffix removed  For example      https   host port v1 identity oidc plugins      1  The subject identifier   must   match the unique  sub  claim issued by plugin identity tokens     The subject identifier should have the form  plugin identity  NAMESPACE  secret  AZURE MOUNT ACCESSOR       1  The audience should be under 600 characters  The default value in Azure is  api   AzureADTokenExchange    1  Configure the Azure secrets engine with the subscription  client and tenant IDs and the OIDC audience value         shell session      vault write azure config        subscription id  AZURE SUBSCRIPTION ID        tenant id  AZURE TENANT ID        client id  AZURE CLIENT ID        identity token audience  vault example v1 identity oidc plugins          Your secrets engine can now use plugin WIF for its configuration credentials  By default  WIF  credentials  https   learn microsoft com en us entra identity platform access tokens token lifetime  have a time to live of 1 hour and automatically refresh when they expire   Please see the  API documentation   vault api docs secret azure configure access  for more details on the fields associated with plugin WIF      Choosing between dynamic or existing service principals  Dynamic service principals are preferred if the desired Azure resources can be provided via the RBAC system and Azure roles defined in the Vault role  This form of credential is completely decoupled from any other clients  is not subject to permission changes after issuance  and offers the best audit granularity   Access to some Azure services cannot be provided with the RBAC system  however  In these cases  an existing service principal can be set up with the necessary access  and Vault can create new passwords for this service principal  Any changes to the service principal permissions affect all clients  Furthermore  Azure does not provide any logging with regard to  which  credential was used for an operation   An important limitation when using an existing service principal is that Azure limits the number of passwords for a single Application  This limit is based on Application object size and isn t firmly specified  but in practice hundreds of passwords can be issued per Application  An error will be returned if the object size is reached  This limit can be managed by reducing the role TTL  or by creating another Vault role against a different Azure service principal configured with the same permissions      Additional notes      If a referenced Azure role doesn t exist  a credential will not be generated      Service principals will only be generated if  all  role assignments are successful    This is important to note if you re using custom Azure role definitions that might be deleted   at some point     Azure roles are assigned only once  when the service principal is created  If the   Vault role changes the list of Azure roles  these changes will not be reflected in   any existing service principal  even after token renewal     The time required to issue a credential is roughly proportional to the number of   Azure roles that must be assigned  This operation make take some time  10s of seconds   are common  and over a minute has been seen      Service principal credential timeouts are not used  Vault will revoke access by   deleting the service principal     The Application Name for dynamic service principals will be prefixed with  vault    Similarly   the  keyId  of any passwords added to an existing service principal will begin with    ffffff   These may be used to search for Vault created credentials using the  az  tool   or Portal      Azure debug logs  The Azure secret engine plugin supports debug logging which includes additional information about requests and responses from the Azure API   To enable the Azure debug logs  set the  AZURE SDK GO LOGGING   environment variable to  all  on your Vault server      shell AZURE SDK GO LOGGING all         Help  amp  support  The Azure secrets engine is written as an external Vault plugin and thus exists outside the main Vault repository  It is automatically bundled with Vault releases  but the code is managed separately   Please report issues  add feature requests  and submit contributions to the  vault plugin secrets azure repo  repo  on GitHub      Tutorial  Refer to the  Azure Secrets Engine   vault tutorials secrets management azure secrets  tutorial to learn how to use the Azure secrets engine to dynamically generate Azure credentials      API  The Azure secrets engine has a full HTTP API  Please see the  Azure secrets engine API docs  api  for more details    api    vault api docs secret azure  config    vault api docs secret azure configure access  repo   https   github com hashicorp vault plugin secrets azure  user access admin   https   learn microsoft com en us azure role based access control built in roles user access administrator


vault LDAP secrets engine page title LDAP Secrets Engine The LDAP secret engine manages LDAP entry passwords layout docs include x509 sha1 deprecation mdx

Answer:
---
layout: docs
page_title: LDAP - Secrets Engine
description: >-
  The LDAP secret engine manages LDAP entry passwords.
---

# LDAP secrets engine

@include 'x509-sha1-deprecation.mdx'

The LDAP secrets engine provides management of LDAP credentials as well as dynamic
creation of credentials. It supports integration with implementations of the LDAP
v3 protocol, including OpenLDAP, Active Directory, and IBM Resource Access Control
Facility (RACF).

The secrets engine has three primary features:
- [Static Credentials](/vault/docs/secrets/ldap#static-credentials)
- [Dynamic Credentials](/vault/docs/secrets/ldap#dynamic-credentials)
- [Service Account Check-Out](/vault/docs/secrets/ldap#service-account-check-out)

## Setup

1. Enable the LDAP secret engine:

   ```sh
   $ vault secrets enable ldap
   ```

   By default, the secrets engine will mount at the name of the engine. To
   enable the secrets engine at a different path, use the `-path` argument.

2. Configure the credentials that Vault uses to communicate with LDAP
   to generate passwords:

   ```sh
   $ vault write ldap/config \
       binddn=$USERNAME \
       bindpass=$PASSWORD \
       url=ldaps://138.91.247.105
   ```

   Note: it's recommended a dedicated entry management account be created specifically for Vault.

3. Rotate the root password so only Vault knows the credentials:

   ```sh
   $ vault write -f ldap/rotate-root
   ```

   Note: it's not possible to retrieve the generated password once rotated by Vault.
   It's recommended a dedicated entry management account be created specifically for Vault.

### Schemas

The LDAP Secret Engine supports three different schemas:

- `openldap` (default)
- `racf`
- `ad`

#### OpenLDAP

By default, the LDAP Secret Engine assumes the entry password is stored in `userPassword`.
There are many object classes that provide `userPassword` including for example:

- `organization`
- `organizationalUnit`
- `organizationalRole`
- `inetOrgPerson`
- `person`
- `posixAccount`

#### Resource access control facility (RACF)

For managing IBM's Resource Access Control Facility (RACF) security system, the secret
engine must be configured to use the schema `racf`.

Generated passwords must be 8 characters or less to support RACF. The length of the
password can be configured using a [password policy](/vault/docs/concepts/password-policies):

```bash
$ vault write ldap/config \
	binddn=$USERNAME \
	bindpass=$PASSWORD \
	url=ldaps://138.91.247.105 \
	schema=racf \
	password_policy=racf_password_policy
```

#### Active directory (AD)

For managing Active Directory instances, the secret engine must be configured to use the
schema `ad`.

```bash
$ vault write ldap/config \
	binddn=$USERNAME \
	bindpass=$PASSWORD \
	url=ldaps://138.91.247.105 \
	schema=ad
```

## Static credentials

### Setup

1. Configure a static role that maps a name in Vault to an entry in LDAP.
   Password rotation settings will be managed by this role.

   ```sh
   $ vault write ldap/static-role/hashicorp \
       dn='uid=hashicorp,ou=users,dc=hashicorp,dc=com' \
       username='hashicorp' \
       rotation_period="24h"
   ```

2. Request credentials for the "hashicorp" role:

   ```sh
   $ vault read ldap/static-cred/hashicorp
   ```

### Password rotation

Passwords can be managed in two ways:

- automatic time based rotation
- manual rotation

### Auto password rotation

Passwords will automatically be rotated based on the `rotation_period` configured
in the static role (minimum of 5 seconds). When requesting credentials for a static
role, the response will include the time before the next rotation (`ttl`).

Auto-rotation is currently only supported for static roles. The `binddn` account used
by Vault should be rotated using the `rotate-root` endpoint to generate a password
only Vault will know.

### Manual rotation

Static roles can be manually rotated using the `rotate-role` endpoint. When manually
rotated the rotation period will start over.

### Deleting static roles

Passwords are not rotated upon deletion of a static role. The password should be manually
rotated prior to deleting the role or revoking access to the static role.

## Dynamic credentials

### Setup

Dynamic credentials can be configured by calling the `/role/:role_name` endpoint:

```bash
$ vault write ldap/role/dynamic-role \
  creation_ldif=@/path/to/creation.ldif \
  deletion_ldif=@/path/to/deletion.ldif \
  rollback_ldif=@/path/to/rollback.ldif \
  default_ttl=1h \
  max_ttl=24h
```

-> Note: The `rollback_ldif` argument is optional, but recommended. The statements within `rollback_ldif` will be
executed if the creation fails for any reason. This ensures any entities are removed in the event of a failure.

To generate credentials:

```bash
$ vault read ldap/creds/dynamic-role
Key                    Value
---                    -----
lease_id               ldap/creds/dynamic-role/HFgd6uKaDomVMvJpYbn9q4q5
lease_duration         1h
lease_renewable        true
distinguished_names    [cn=v_token_dynamic-role_FfH2i1c4dO_1611952635,ou=users,dc=learn,dc=example]
password               xWMjkIFMerYttEbzfnBVZvhRQGmhpAA0yeTya8fdmDB3LXDzGrjNEPV2bCPE9CW6
username               v_token_testrole_FfH2i1c4dO_1611952635
```

The `distinguished_names` field is an array of DNs that are created from the `creation_ldif` statements. If more than
one LDIF entry is included, the DN from each statement will be included in this field. Each entry in this field
corresponds to a single LDIF statement. No de-duplication occurs and order is maintained.

### LDIF entries

User account management is provided through LDIF entries. The LDIF entries may be a base64-encoded version of the
LDIF string. The string will be parsed and validated to ensure that it adheres to LDIF syntax. A good reference
for proper LDIF syntax can be found [here](https://ldap.com/ldif-the-ldap-data-interchange-format/).

Some important things to remember when crafting your LDIF entries:

- There should not be any trailing spaces on any line, including empty lines
- Each `modify` block needs to be preceded with an empty line
- Multiple modifications for a `dn` can be defined in a single `modify` block. Each modification needs to close
  with a single dash (`-`)

### Active directory (AD)

<Note>

  Windows Servers hosting Active Directory include a
  `lifetime period of an old password` configuration setting that lets clients
  authenticate with old passwords for a specified amount of time.

  For more information, refer to the
 [NTLM network authentication behavior](https://learn.microsoft.com/en-us/troubleshoot/windows-server/windows-security new-setting-modifies-ntlm-network-authentication)
  guide by Microsoft.

</Note>

For Active Directory, there are a few additional details that are important to remember:

To create a user programmatically in AD, you first `add` a user object and then `modify` that user to provide a
password and enable the account.

- Passwords in AD are set using the `unicodePwd` field. This must be proceeded by two (2) colons (`::`).
- When setting a password programmatically in AD, the following criteria must be met:

  - The password must be enclosed in double quotes (`" "`)
  - The password must be in [`UTF16LE` format](https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/6e803168-f140-4d23-b2d3-c3a8ab5917d2)
  - The password must be `base64`-encoded
  - Additional details can be found [here](https://docs.microsoft.com/en-us/troubleshoot/windows-server/identity/set-user-password-with-ldifde)

- Once a user's password has been set, it can be enabled. AD uses the `userAccountControl` field for this purpose:
  - To enable the account, set `userAccountControl` to `512`
  - You will likely also want to disable AD's password expiration for this dynamic user account. The
    `userAccountControl` value for this is: `65536`
  - `userAccountControl` flags are cumulative, so to set both of the above two flags, add up the two values
    (`512 + 65536 = 66048`): set `userAccountControl` to `66048`
  - See [here](https://docs.microsoft.com/en-us/troubleshoot/windows-server/identity/useraccountcontrol-manipulate-account-properties#property-flag-descriptions)
    for details on `userAccountControl` flags

`sAMAccountName` is a common field when working with AD users. It is used to provide compatibility with legacy
Windows NT systems and has a limit of 20 characters. Keep this in mind when defining your `username_template`.
See [here](https://docs.microsoft.com/en-us/windows/win32/adschema/a-samaccountname) for additional details.

Since the default `username_template` is longer than 20 characters which follows the template of `v____`, we recommend customising the `username_template` on the role configuration to generate accounts with names less than 20 characters. Please refer to the [username templating document](/vault/docs/concepts/username-templating) for more information.

With regard to adding dynamic users to groups, AD doesn't let you directly modify a user's `memberOf` attribute.
The `member` attribute of a group and `memberOf` attribute of a user are
[linked attributes](https://docs.microsoft.com/en-us/windows/win32/ad/linked-attributes). Linked attributes are
forward link/back link pairs, with the forward link able to be modified. In the case of AD group membership, the
group's `member` attribute is the forward link. In order to add a newly-created dynamic user to a group, we also
need to issue a `modify` request to the desired group and update the group membership with the new user.

#### Active directory LDIF example

The various `*_ldif` parameters are templates that use the [go template](https://golang.org/pkg/text/template/)
language. A complete LDIF example for creating an Active Directory user account is provided here for reference:

```ldif
dn: CN=,OU=HashiVault,DC=adtesting,DC=lab
changetype: add
objectClass: top
objectClass: person
objectClass: organizationalPerson
objectClass: user
userPrincipalName: @adtesting.lab
sAMAccountName:

dn: CN=,OU=HashiVault,DC=adtesting,DC=lab
changetype: modify
replace: unicodePwd
unicodePwd::
-
replace: userAccountControl
userAccountControl: 66048
-

dn: CN=test-group,OU=HashiVault,DC=adtesting,DC=lab
changetype: modify
add: member
member: CN=,OU=HashiVault,DC=adtesting,DC=lab
-
```

## Service account Check-Out

Service account check-out provides a library of service accounts that can be checked out
by a person or by machines. Vault will automatically rotate the password each time a
service account is checked in. Service accounts can be voluntarily checked in, or Vault
will check them in when their lending period (or, "ttl", in Vault's language) ends.

The service account check-out functionality works with various [schemas](/vault/api-docs/secret/ldap#schema),
including OpenLDAP, Active Directory, and RACF. In the following usage example, the secrets
engine is configured to manage a library of service accounts in an Active Directory instance.

First we'll need to enable the LDAP secrets engine and tell it how to securely connect
to an AD server.

```shell-session
$ vault secrets enable ldap
Success! Enabled the ad secrets engine at: ldap/

$ vault write ldap/config \
    binddn=$USERNAME \
    bindpass=$PASSWORD \
    url=ldaps://138.91.247.105 \
    userdn='dc=example,dc=com'
```

Our next step is to designate a set of service accounts for check-out.

```shell-session
$ vault write ldap/library/accounting-team \
    service_account_names=fizz@example.com,buzz@example.com \
    ttl=10h \
    max_ttl=20h \
    disable_check_in_enforcement=false
```

In this example, the service account names of `fizz@example.com` and `buzz@example.com` have
already been created on the remote AD server. They've been set aside solely for Vault to handle.
The `ttl` is how long each check-out will last before Vault checks in a service account,
rotating its password during check-in. The `max_ttl` is the maximum amount of time it can live
if it's renewed. These default to `24h`, and both use [duration format strings](/vault/docs/concepts/duration-format).
Also by default, a service account must be checked in by the same Vault entity or client token that
checked it out. However, if this behavior causes problems, set `disable_check_in_enforcement=true`.

When a library of service accounts has been created, view their status at any time to see if they're
available or checked out.

```shell-session
$ vault read ldap/library/accounting-team/status
Key                 Value
---                 -----
buzz@example.com    map[available:true]
fizz@example.com    map[available:true]
```

To check out any service account that's available, simply execute:

```shell-session
$ vault write -f ldap/library/accounting-team/check-out
Key                     Value
---                     -----
lease_id                ldap/library/accounting-team/check-out/EpuS8cX7uEsDzOwW9kkKOyGW
lease_duration          10h
lease_renewable         true
password                ?@09AZKh03hBORZPJcTDgLfntlHqxLy29tcQjPVThzuwWAx/Twx4a2ZcRQRqrZ1w
service_account_name    fizz@example.com
```

If the default `ttl` for the check-out is higher than needed, set the check-out to last
for a shorter time by using:

```shell-session
$ vault write ldap/library/accounting-team/check-out ttl=30m
Key                     Value
---                     -----
lease_id                ldap/library/accounting-team/check-out/gMonJ2jB6kYs6d3Vw37WFDCY
lease_duration          30m
lease_renewable         true
password                ?@09AZerLLuJfEMbRqP+3yfQYDSq6laP48TCJRBJaJu/kDKLsq9WxL9szVAvL/E1
service_account_name    buzz@example.com
```

This can be a nice way to say, "Although I _can_ have a check-out for 24 hours, if I
haven't checked it in after 30 minutes, I forgot or I'm a dead instance, so you can just
check it back in."

If no service accounts are available for check-out, Vault will return a 400 Bad Request.

```shell-session
$ vault write -f ldap/library/accounting-team/check-out
Error writing data to ldap/library/accounting-team/check-out: Error making API request.

URL: POST http://localhost:8200/v1/ldap/library/accounting-team/check-out
Code: 400. Errors:

* No service accounts available for check-out.
```

To extend a check-out, renew its lease.

```shell-session
$ vault lease renew ldap/library/accounting-team/check-out/0C2wmeaDmsToVFc0zDiX9cMq
Key                Value
---                -----
lease_id           ldap/library/accounting-team/check-out/0C2wmeaDmsToVFc0zDiX9cMq
lease_duration     10h
lease_renewable    true
```

Renewing a check-out means its current password will live longer, since passwords are rotated
anytime a password is _checked in_ either by a caller, or by Vault because the check-out `ttl`
ends.

To check a service account back in for others to use, call:

```shell-session
$ vault write -f ldap/library/accounting-team/check-in
Key          Value
---          -----
check_ins    [fizz@example.com]
```

Most of the time this will just work, but if multiple service accounts are checked out by the same
caller, Vault will need to know which one(s) to check in.

```shell-session
$ vault write ldap/library/accounting-team/check-in service_account_names=fizz@example.com
Key          Value
---          -----
check_ins    [fizz@example.com]
```

To perform a check-in, Vault verifies that the caller _should_ be able to check in a given service account.
To do this, Vault looks for either the same [entity ID](/vault/tutorials/auth-methods/identity)
used to check out the service account, or the same client token.

If a caller is unable to check in a service account, or simply doesn't try,
Vault will check it back in automatically when the `ttl` expires. However, if that is too long,
service accounts can be forcibly checked in by a highly privileged user through:

```shell-session
$ vault write -f ldap/library/manage/accounting-team/check-in
Key          Value
---          -----
check_ins    [fizz@example.com]
```

Or, alternatively, revoking the secret's lease has the same effect.

```shell-session
$ vault lease revoke ldap/library/accounting-team/check-out/PvBVG0m7pEg2940Cb3Jw3KpJ
All revocation operations queued successfully!
```

## Password generation

This engine previously allowed configuration of the length of the password that is generated
when rotating credentials. This mechanism was deprecated in Vault 1.5 in favor of
[password policies](/vault/docs/concepts/password-policies). This means the `length` field should
no longer be used. The following password policy can be used to mirror the same behavior
that the `length` field provides:

```hcl
length=<length>
rule "charset" {
  charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
}
```

## LDAP password policy

The LDAP secret engine does not hash or encrypt passwords prior to modifying
values in LDAP. This behavior can cause plaintext passwords to be stored in LDAP.

To avoid having plaintext passwords stored, the LDAP server should be configured
with an LDAP password policy (ppolicy, not to be confused with a Vault password
policy). A ppolicy can enforce rules such as hashing plaintext passwords by default.

The following is an example of an LDAP password policy to enforce hashing on the
data information tree (DIT) `dc=hashicorp,dc=com`:

```
dn: cn=module{0},cn=config
changetype: modify
add: olcModuleLoad
olcModuleLoad: ppolicy

dn: olcOverlay={2}ppolicy,olcDatabase={1}mdb,cn=config
changetype: add
objectClass: olcPPolicyConfig
objectClass: olcOverlayConfig
olcOverlay: {2}ppolicy
olcPPolicyDefault: cn=default,ou=pwpolicies,dc=hashicorp,dc=com
olcPPolicyForwardUpdates: FALSE
olcPPolicyHashCleartext: TRUE
olcPPolicyUseLockout: TRUE
```

## Hierarchical paths

The LDAP secrets engine lets you define role and set names that contain an
arbitrary number of forward slashes. Names with forward slashes define
hierarchical path structures.

For example, you can configure two static roles with the names `org/secure` and `org/platform/dev`:

```shell-session
$ vault write ldap/static-role/org/secure \
    username="user1" \
    rotation_period="1h"
Success! Data written to: ldap/static-role/org/secure

$ vault write ldap/static-role/org/platform/dev \
    username="user2" \
    rotation_period="1h"
Success! Data written to: ldap/static-role/org/platform/dev
```

Names with hierarchical paths let you use the Vault API to query the available
roles at a specific path with arbitrary depth. Names that end with a forward
slash indicate that sub-paths reside under that path.

For example, to list all direct children under the `org/` path:

```shell-session
$ vault list ldap/static-role/org/
Keys
----
platform/
secure
```

The `platform/` key also ends in a forward slash. To list the `platform` sub-keys:

```shell-session
$ vault list ldap/static-role/org/platform
Keys
----
dev
```

You can read and rotate credentials using the same role name and the respective
APIs. For example,

```shell-session
$ vault read ldap/static-cred/org/platform/dev
Key                    Value
---                    -----
dn                     n/a
last_password          a3sQ6OkmXKt2dtx22kAt36YLkkxLsg4RmhMZCLYCBCbvvv67ILROaOokdCaGPEAE
last_vault_rotation    2024-05-03T16:39:27.174164-05:00
password               ECf7ZoxfDxGuJEYZrzgzTffSIDI4tx5TojBR9wuEGp8bqUXbl4Kr9eAgPjmizcvg
rotation_period        5m
ttl                    4m58s
username               user2
```

```shell-session
$ vault write -f ldap/rotate-role/org/platform/dev
```

Since [Vault policies](/vault/docs/concepts/policies) are also path-based,
hierarchical names also let you define policies that map 1-1 to LDAP secrets
engine roles and set paths.

The following Vault API endpoints support hierarchical path handling:

- [Static roles](/vault/api-docs/secret/ldap#static-roles)
- [Static role passwords](/vault/api-docs/secret/ldap#static-role-passwords)
- [Manually rotate static role password](/vault/api-docs/secret/ldap#manually-rotate-static-role-password)
- [Dynamic roles](/vault/api-docs/secret/ldap#dynamic-roles)
- [Dynamic role passwords](/vault/api-docs/secret/ldap#dynamic-role-passwords)
- [Library set management](/vault/api-docs/secret/ldap#library-set-management)
- [Library set status check](/vault/api-docs/secret/ldap#library-set-status-check)
- [Check-Out management](/vault/api-docs/secret/ldap#check-out-management)
- [Check-In management](/vault/api-docs/secret/ldap#check-in-management)

## Tutorial

Refer to the [LDAP Secrets Engine](/vault/tutorials/secrets-management/openldap)
tutorial to learn how to configure and use the LDAP secrets engine.

## API

The LDAP secrets engine has a full HTTP API. Please see the [LDAP secrets engine API docs](/vault/api-docs/secret/ldap)
for more details.

layout  docs page title  LDAP   Secrets Engine description       The LDAP secret engine manages LDAP entry passwords         LDAP secrets engine   include  x509 sha1 deprecation mdx   The LDAP secrets engine provides management of LDAP credentials as well as dynamic creation of credentials  It supports integration with implementations of the LDAP v3 protocol  including OpenLDAP  Active Directory  and IBM Resource Access Control Facility  RACF    The secrets engine has three primary features     Static Credentials   vault docs secrets ldap static credentials     Dynamic Credentials   vault docs secrets ldap dynamic credentials     Service Account Check Out   vault docs secrets ldap service account check out      Setup  1  Enable the LDAP secret engine         sh      vault secrets enable ldap            By default  the secrets engine will mount at the name of the engine  To    enable the secrets engine at a different path  use the   path  argument   2  Configure the credentials that Vault uses to communicate with LDAP    to generate passwords         sh      vault write ldap config          binddn  USERNAME          bindpass  PASSWORD          url ldaps   138 91 247 105            Note  it s recommended a dedicated entry management account be created specifically for Vault   3  Rotate the root password so only Vault knows the credentials         sh      vault write  f ldap rotate root            Note  it s not possible to retrieve the generated password once rotated by Vault     It s recommended a dedicated entry management account be created specifically for Vault       Schemas  The LDAP Secret Engine supports three different schemas      openldap   default     racf     ad        OpenLDAP  By default  the LDAP Secret Engine assumes the entry password is stored in  userPassword   There are many object classes that provide  userPassword  including for example      organization     organizationalUnit     organizationalRole     inetOrgPerson     person     posixAccount        Resource access control facility  RACF   For managing IBM s Resource Access Control Facility  RACF  security system  the secret engine must be configured to use the schema  racf    Generated passwords must be 8 characters or less to support RACF  The length of the password can be configured using a  password policy   vault docs concepts password policies       bash   vault write ldap config    binddn  USERNAME    bindpass  PASSWORD    url ldaps   138 91 247 105    schema racf    password policy racf password policy           Active directory  AD   For managing Active Directory instances  the secret engine must be configured to use the schema  ad       bash   vault write ldap config    binddn  USERNAME    bindpass  PASSWORD    url ldaps   138 91 247 105    schema ad         Static credentials      Setup  1  Configure a static role that maps a name in Vault to an entry in LDAP     Password rotation settings will be managed by this role         sh      vault write ldap static role hashicorp          dn  uid hashicorp ou users dc hashicorp dc com           username  hashicorp           rotation period  24h          2  Request credentials for the  hashicorp  role         sh      vault read ldap static cred hashicorp             Password rotation  Passwords can be managed in two ways     automatic time based rotation   manual rotation      Auto password rotation  Passwords will automatically be rotated based on the  rotation period  configured in the static role  minimum of 5 seconds   When requesting credentials for a static role  the response will include the time before the next rotation   ttl     Auto rotation is currently only supported for static roles  The  binddn  account used by Vault should be rotated using the  rotate root  endpoint to generate a password only Vault will know       Manual rotation  Static roles can be manually rotated using the  rotate role  endpoint  When manually rotated the rotation period will start over       Deleting static roles  Passwords are not rotated upon deletion of a static role  The password should be manually rotated prior to deleting the role or revoking access to the static role      Dynamic credentials      Setup  Dynamic credentials can be configured by calling the   role  role name  endpoint      bash   vault write ldap role dynamic role     creation ldif   path to creation ldif     deletion ldif   path to deletion ldif     rollback ldif   path to rollback ldif     default ttl 1h     max ttl 24h         Note  The  rollback ldif  argument is optional  but recommended  The statements within  rollback ldif  will be executed if the creation fails for any reason  This ensures any entities are removed in the event of a failure   To generate credentials      bash   vault read ldap creds dynamic role Key                    Value                              lease id               ldap creds dynamic role HFgd6uKaDomVMvJpYbn9q4q5 lease duration         1h lease renewable        true distinguished names     cn v token dynamic role FfH2i1c4dO 1611952635 ou users dc learn dc example  password               xWMjkIFMerYttEbzfnBVZvhRQGmhpAA0yeTya8fdmDB3LXDzGrjNEPV2bCPE9CW6 username               v token testrole FfH2i1c4dO 1611952635      The  distinguished names  field is an array of DNs that are created from the  creation ldif  statements  If more than one LDIF entry is included  the DN from each statement will be included in this field  Each entry in this field corresponds to a single LDIF statement  No de duplication occurs and order is maintained       LDIF entries  User account management is provided through LDIF entries  The LDIF entries may be a base64 encoded version of the LDIF string  The string will be parsed and validated to ensure that it adheres to LDIF syntax  A good reference for proper LDIF syntax can be found  here  https   ldap com ldif the ldap data interchange format     Some important things to remember when crafting your LDIF entries     There should not be any trailing spaces on any line  including empty lines   Each  modify  block needs to be preceded with an empty line   Multiple modifications for a  dn  can be defined in a single  modify  block  Each modification needs to close   with a single dash            Active directory  AD    Note      Windows Servers hosting Active Directory include a     lifetime period of an old password  configuration setting that lets clients   authenticate with old passwords for a specified amount of time     For more information  refer to the   NTLM network authentication behavior  https   learn microsoft com en us troubleshoot windows server windows security new setting modifies ntlm network authentication    guide by Microsoft     Note   For Active Directory  there are a few additional details that are important to remember   To create a user programmatically in AD  you first  add  a user object and then  modify  that user to provide a password and enable the account     Passwords in AD are set using the  unicodePwd  field  This must be proceeded by two  2  colons           When setting a password programmatically in AD  the following criteria must be met       The password must be enclosed in double quotes             The password must be in   UTF16LE  format  https   docs microsoft com en us openspecs windows protocols ms adts 6e803168 f140 4d23 b2d3 c3a8ab5917d2      The password must be  base64  encoded     Additional details can be found  here  https   docs microsoft com en us troubleshoot windows server identity set user password with ldifde     Once a user s password has been set  it can be enabled  AD uses the  userAccountControl  field for this purpose      To enable the account  set  userAccountControl  to  512      You will likely also want to disable AD s password expiration for this dynamic user account  The      userAccountControl  value for this is   65536       userAccountControl  flags are cumulative  so to set both of the above two flags  add up the two values       512   65536   66048    set  userAccountControl  to  66048      See  here  https   docs microsoft com en us troubleshoot windows server identity useraccountcontrol manipulate account properties property flag descriptions      for details on  userAccountControl  flags   sAMAccountName  is a common field when working with AD users  It is used to provide compatibility with legacy Windows NT systems and has a limit of 20 characters  Keep this in mind when defining your  username template   See  here  https   docs microsoft com en us windows win32 adschema a samaccountname  for additional details   Since the default  username template  is longer than 20 characters which follows the template of  v       we recommend customising the  username template  on the role configuration to generate accounts with names less than 20 characters  Please refer to the  username templating document   vault docs concepts username templating  for more information   With regard to adding dynamic users to groups  AD doesn t let you directly modify a user s  memberOf  attribute  The  member  attribute of a group and  memberOf  attribute of a user are  linked attributes  https   docs microsoft com en us windows win32 ad linked attributes   Linked attributes are forward link back link pairs  with the forward link able to be modified  In the case of AD group membership  the group s  member  attribute is the forward link  In order to add a newly created dynamic user to a group  we also need to issue a  modify  request to the desired group and update the group membership with the new user        Active directory LDIF example  The various    ldif  parameters are templates that use the  go template  https   golang org pkg text template   language  A complete LDIF example for creating an Active Directory user account is provided here for reference      ldif dn  CN  OU HashiVault DC adtesting DC lab changetype  add objectClass  top objectClass  person objectClass  organizationalPerson objectClass  user userPrincipalName   adtesting lab sAMAccountName    dn  CN  OU HashiVault DC adtesting DC lab changetype  modify replace  unicodePwd unicodePwd     replace  userAccountControl userAccountControl  66048    dn  CN test group OU HashiVault DC adtesting DC lab changetype  modify add  member member  CN  OU HashiVault DC adtesting DC lab           Service account Check Out  Service account check out provides a library of service accounts that can be checked out by a person or by machines  Vault will automatically rotate the password each time a service account is checked in  Service accounts can be voluntarily checked in  or Vault will check them in when their lending period  or   ttl   in Vault s language  ends   The service account check out functionality works with various  schemas   vault api docs secret ldap schema   including OpenLDAP  Active Directory  and RACF  In the following usage example  the secrets engine is configured to manage a library of service accounts in an Active Directory instance   First we ll need to enable the LDAP secrets engine and tell it how to securely connect to an AD server      shell session   vault secrets enable ldap Success  Enabled the ad secrets engine at  ldap     vault write ldap config       binddn  USERNAME       bindpass  PASSWORD       url ldaps   138 91 247 105       userdn  dc example dc com       Our next step is to designate a set of service accounts for check out      shell session   vault write ldap library accounting team       service account names fizz example com buzz example com       ttl 10h       max ttl 20h       disable check in enforcement false      In this example  the service account names of  fizz example com  and  buzz example com  have already been created on the remote AD server  They ve been set aside solely for Vault to handle  The  ttl  is how long each check out will last before Vault checks in a service account  rotating its password during check in  The  max ttl  is the maximum amount of time it can live if it s renewed  These default to  24h   and both use  duration format strings   vault docs concepts duration format   Also by default  a service account must be checked in by the same Vault entity or client token that checked it out  However  if this behavior causes problems  set  disable check in enforcement true    When a library of service accounts has been created  view their status at any time to see if they re available or checked out      shell session   vault read ldap library accounting team status Key                 Value                           buzz example com    map available true  fizz example com    map available true       To check out any service account that s available  simply execute      shell session   vault write  f ldap library accounting team check out Key                     Value                               lease id                ldap library accounting team check out EpuS8cX7uEsDzOwW9kkKOyGW lease duration          10h lease renewable         true password                  09AZKh03hBORZPJcTDgLfntlHqxLy29tcQjPVThzuwWAx Twx4a2ZcRQRqrZ1w service account name    fizz example com      If the default  ttl  for the check out is higher than needed  set the check out to last for a shorter time by using      shell session   vault write ldap library accounting team check out ttl 30m Key                     Value                               lease id                ldap library accounting team check out gMonJ2jB6kYs6d3Vw37WFDCY lease duration          30m lease renewable         true password                  09AZerLLuJfEMbRqP 3yfQYDSq6laP48TCJRBJaJu kDKLsq9WxL9szVAvL E1 service account name    buzz example com      This can be a nice way to say   Although I  can  have a check out for 24 hours  if I haven t checked it in after 30 minutes  I forgot or I m a dead instance  so you can just check it back in    If no service accounts are available for check out  Vault will return a 400 Bad Request      shell session   vault write  f ldap library accounting team check out Error writing data to ldap library accounting team check out  Error making API request   URL  POST http   localhost 8200 v1 ldap library accounting team check out Code  400  Errors     No service accounts available for check out       To extend a check out  renew its lease      shell session   vault lease renew ldap library accounting team check out 0C2wmeaDmsToVFc0zDiX9cMq Key                Value                          lease id           ldap library accounting team check out 0C2wmeaDmsToVFc0zDiX9cMq lease duration     10h lease renewable    true      Renewing a check out means its current password will live longer  since passwords are rotated anytime a password is  checked in  either by a caller  or by Vault because the check out  ttl  ends   To check a service account back in for others to use  call      shell session   vault write  f ldap library accounting team check in Key          Value                    check ins     fizz example com       Most of the time this will just work  but if multiple service accounts are checked out by the same caller  Vault will need to know which one s  to check in      shell session   vault write ldap library accounting team check in service account names fizz example com Key          Value                    check ins     fizz example com       To perform a check in  Vault verifies that the caller  should  be able to check in a given service account  To do this  Vault looks for either the same  entity ID   vault tutorials auth methods identity  used to check out the service account  or the same client token   If a caller is unable to check in a service account  or simply doesn t try  Vault will check it back in automatically when the  ttl  expires  However  if that is too long  service accounts can be forcibly checked in by a highly privileged user through      shell session   vault write  f ldap library manage accounting team check in Key          Value                    check ins     fizz example com       Or  alternatively  revoking the secret s lease has the same effect      shell session   vault lease revoke ldap library accounting team check out PvBVG0m7pEg2940Cb3Jw3KpJ All revocation operations queued successfully          Password generation  This engine previously allowed configuration of the length of the password that is generated when rotating credentials  This mechanism was deprecated in Vault 1 5 in favor of  password policies   vault docs concepts password policies   This means the  length  field should no longer be used  The following password policy can be used to mirror the same behavior that the  length  field provides      hcl length  length  rule  charset      charset    abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789            LDAP password policy  The LDAP secret engine does not hash or encrypt passwords prior to modifying values in LDAP  This behavior can cause plaintext passwords to be stored in LDAP   To avoid having plaintext passwords stored  the LDAP server should be configured with an LDAP password policy  ppolicy  not to be confused with a Vault password policy   A ppolicy can enforce rules such as hashing plaintext passwords by default   The following is an example of an LDAP password policy to enforce hashing on the data information tree  DIT   dc hashicorp dc com        dn  cn module 0  cn config changetype  modify add  olcModuleLoad olcModuleLoad  ppolicy  dn  olcOverlay  2 ppolicy olcDatabase  1 mdb cn config changetype  add objectClass  olcPPolicyConfig objectClass  olcOverlayConfig olcOverlay   2 ppolicy olcPPolicyDefault  cn default ou pwpolicies dc hashicorp dc com olcPPolicyForwardUpdates  FALSE olcPPolicyHashCleartext  TRUE olcPPolicyUseLockout  TRUE         Hierarchical paths  The LDAP secrets engine lets you define role and set names that contain an arbitrary number of forward slashes  Names with forward slashes define hierarchical path structures   For example  you can configure two static roles with the names  org secure  and  org platform dev       shell session   vault write ldap static role org secure       username  user1        rotation period  1h  Success  Data written to  ldap static role org secure    vault write ldap static role org platform dev       username  user2        rotation period  1h  Success  Data written to  ldap static role org platform dev      Names with hierarchical paths let you use the Vault API to query the available roles at a specific path with arbitrary depth  Names that end with a forward slash indicate that sub paths reside under that path   For example  to list all direct children under the  org   path      shell session   vault list ldap static role org  Keys      platform  secure      The  platform   key also ends in a forward slash  To list the  platform  sub keys      shell session   vault list ldap static role org platform Keys      dev      You can read and rotate credentials using the same role name and the respective APIs  For example      shell session   vault read ldap static cred org platform dev Key                    Value                              dn                     n a last password          a3sQ6OkmXKt2dtx22kAt36YLkkxLsg4RmhMZCLYCBCbvvv67ILROaOokdCaGPEAE last vault rotation    2024 05 03T16 39 27 174164 05 00 password               ECf7ZoxfDxGuJEYZrzgzTffSIDI4tx5TojBR9wuEGp8bqUXbl4Kr9eAgPjmizcvg rotation period        5m ttl                    4m58s username               user2         shell session   vault write  f ldap rotate role org platform dev      Since  Vault policies   vault docs concepts policies  are also path based  hierarchical names also let you define policies that map 1 1 to LDAP secrets engine roles and set paths   The following Vault API endpoints support hierarchical path handling      Static roles   vault api docs secret ldap static roles     Static role passwords   vault api docs secret ldap static role passwords     Manually rotate static role password   vault api docs secret ldap manually rotate static role password     Dynamic roles   vault api docs secret ldap dynamic roles     Dynamic role passwords   vault api docs secret ldap dynamic role passwords     Library set management   vault api docs secret ldap library set management     Library set status check   vault api docs secret ldap library set status check     Check Out management   vault api docs secret ldap check out management     Check In management   vault api docs secret ldap check in management      Tutorial  Refer to the  LDAP Secrets Engine   vault tutorials secrets management openldap  tutorial to learn how to configure and use the LDAP secrets engine       API  The LDAP secrets engine has a full HTTP API  Please see the  LDAP secrets engine API docs   vault api docs secret ldap  for more details