terraform Learn how to use the web UI to connect a workspace to a version control system repository that contains Terraform configuration You can connect any HCP Terraform workspace terraform cloud docs workspaces to a version control system VCS repository that contains a Terraform configuration This page explains the workspace VCS connection settings in the HCP Terraform UI page title VCS Connections Workspaces HCP Terraform Configuring Workspace VCS Connections

Answer:
---
page_title: VCS Connections - Workspaces - HCP Terraform
description: >-
  Learn how to use the web UI to connect a workspace to a version control system repository that contains Terraform configuration.
---

# Configuring Workspace VCS Connections

You can connect any HCP Terraform [workspace](/terraform/cloud-docs/workspaces) to a version control system (VCS) repository that contains a Terraform configuration. This page explains the workspace VCS connection settings in the HCP Terraform UI.

Refer to [Terraform Configurations in HCP Terraform Workspaces](/terraform/cloud-docs/workspaces/configurations) for details on handling configuration versions and connected repositories. Refer to [Connecting VCS Providers](/terraform/cloud-docs/vcs) for a list of supported VCS providers and details about configuring VCS access, viewing VCS events, etc.

## API

You can use the [Update a Workspace endpoint](/terraform/cloud-docs/api-docs/workspaces#update-a-workspace) in the Workspaces API to change one or more VCS settings. We also recommend using this endpoint to automate changing VCS connections for many workspaces at once. For example, when you move a VCS server or remove a deprecated API version.

## Version Control Settings

To change a workspace's VCS settings:

1. Go to the workspace and click **Settings > Version Control**. The **Version Control** page appears.
1. Choose the desired settings and click **Update VCS settings**.

You can update the following types of VCS settings for the workspace.

### VCS Connection

You can take one of the following actions:

- To add a new VCS connection, click **Connect to version control**. Select **Version control workflow** and follow the steps to [select a VCS provider and repository](/terraform/cloud-docs/workspaces/create#create-a-workspace).
- To edit an existing VCS connection, click **Change source**. Choose the **Version control workflow** and follow the steps to [select VCS provider and repository](/terraform/cloud-docs/workspaces/create#create-a-workspace).
- To remove the VCS connection, click **Change source**. Select either the **CLI-driven workflow** or the **API-driven workflow**, and click **Update VCS settings**. The workspace is no longer connected to VCS.

[permissions-citation]: #intentionally-unused---keep-for-maintainers

### Terraform Working Directory

Specify the directory where Terraform will execute runs. This defaults to the root directory in your repository, but you may want to specify another directory if you have directories for multiple different Terraform configurations within the same repository. For example, if you had one `staging` directory and one `production` directory.

A working directory is required when you use [trigger prefixes](#automatic-run-triggering).

### Apply Method

Choose a workflow for Terraform runs.

- **Auto apply:** Terraform will apply changes from successful plans without prompting for approval. A push to the default branch of your repository will trigger a plan and apply cycle. You may want to do this in non-interactive environments, like continuous deployment workflows.

  !> **Warning:** If you choose auto apply, make sure that no one can change your infrastructure outside of your automated build pipeline. This reduces the risk of configuration drift and unexpected changes.

- **Manual apply:** Terraform will ask for approval before applying changes from a successful plan. A push to the default branch of your repository will trigger a plan, and then Terraform will wait for confirmation.

### Automatic Run Triggering

HCP Terraform uses your VCS provider's API to retrieve the changed files in your repository. You can choose one of the following options to specify which changes trigger Terraform runs.

#### Always trigger runs

This option instructs Terraform to begin a run when changes are pushed to any file within the repository. This can be useful for repositories that do not have multiple configurations but require a working directory for some other reason. However, we do not recommend this approach for true monorepos, as it queues unnecessary runs and slows down your ability to provision infrastructure.

#### Only trigger runs when files in specified paths change

This option instructs Terraform to begin new runs only for changes that affect specified files and directories. This behavior also applies to [speculative plans](/terraform/cloud-docs/run/remote-operations#speculative-plans) on pull requests.

You can use trigger patterns and trigger prefixes in the **Add path** field to specify groups of files and directories.
- **Trigger Patterns:** (Recommended) Use glob patterns to specify the files that should trigger a new run. For example, `/submodule/**/*.tf`, specifies all files with the `.tf` extension that are nested below the `submodule` directory. You can also use more complex patterns like `/**/networking/**/*`, which specifies all files that have a `networking` folder in their file path. (e.g., `/submodule/service-1/networking/private/main.tf`). Refer to [Glob Patterns for Automatic Run Triggering](#glob-patterns-for-automatic-run-triggering) for details.
- **Trigger Prefixes:** HCP Terraform will queue runs for changes in any of the specified trigger directories matching the provided prefixes (including the working directory). For example, if you use a top-level `modules` directory to share Terraform code across multiple configurations, changes to the shared modules are relevant to every workspace that uses that repository. You can add `modules` as a trigger directory for each workspace to track changes to shared code.

-> **Note:** HCP Terraform triggers runs on all attached workspaces if it does not receive a list of changed files or if that list is too large to process. When this happens, HCP Terraform may show several runs with completed plans that do not result in infrastructure changes.

#### Trigger runs when a git tag is published

This option instructs Terraform to begin new runs only for changes that have a specific tag format.

The tag format can be chosen between the following options:
- **Semantic Versioning:** It matches tags in the popular [SemVer format](https://semver.org/). For example, `0.4.2`.
- **Version contains a prefix:** It matches tags which have an additional prefix before the [SemVer format](https://semver.org/). For example, `version-0.4.2`.
- **Version contains a suffix:** It matches tags which have an additional suffix after the [SemVer format](https://semver.org/). For example `0.4.2-alpha`.
- **Custom Regular Expression:** You can define your own regex for HCP Terraform to match against tags.

You must include an additional `\` to escape the regex pattern when you manage your workspace with the [hashicorp/tfe provider](https://registry.terraform.io/providers/hashicorp/tfe/latest/docs/resources/workspace#tags_regex) and trigger runs through matching git tags. Refer to [Terraform escape sequences](/terraform/language/expressions/strings#escape-sequences) for more details.

| Tag Format                    | Regex Pattern             | Regex Pattern (Escaped)  |
|-------------------------------|---------------------------|--------------------------|
| **Semantic Versioning**       | `^\d+.\d+.\d+$`           | `^\\d+.\\d+.\\d+$`       |
| **Version contains a prefix** | `\d+.\d+.\d+$`            | `\\d+.\\d+.\\d+$`        |
| **Version contains a suffix** | `^\d+.\d+.\d+`            | `^\\d+.\\d+.\\d+`        |

HCP Terraform triggers runs for all tags matching this pattern, regardless of the value in the [VCS Branch](#vcs-branch) setting.

### VCS Branch

This setting designates which branch of the repository HCP Terraform should use when the workspace is set to [Always Trigger Runs](#always-trigger-runs) or [Only trigger runs when files in specified paths change](#only-trigger-runs-when-files-in-specified-paths-change). If you leave this setting blank, HCP Terraform uses the repository's default branch. If the workspace is set to trigger runs when a [git tag is published](#trigger-runs-when-a-git-tag-is-published), all tags will trigger runs, regardless of the branch specified in this setting.

### Automatic Speculative Plans

Whether to perform [speculative plans on pull requests](/terraform/cloud-docs/run/ui#speculative-plans-on-pull-requests) to the connected repository, to assist in reviewing proposed changes. Automatic speculative plans are enabled by default, but you can disable them for any workspace.

### Include Submodules on Clone

Select **Include submodules on clone** to recursively clone all of the repository's Git submodules when HCP Terraform fetches a configuration.

-> **Note:** The [SSH key for cloning Git submodules](/terraform/cloud-docs/vcs#ssh-keys) is set in the VCS provider settings for the organization and is not related to the workspace's SSH key for Terraform modules.

## Glob Patterns for Automatic Run Triggering

We support `glob` patterns to describe a set of triggers for automatic runs. Refer to [trigger patterns](#only-trigger-runs-when-files-in-specified-paths-change) for details.

Supported wildcards:
- `*`  Matches zero or more characters.
- `?`  Matches one or more characters.
- `**` Matches directories recursively.

The following examples demonstrate how to use the supported wildcards:
- `/**/*` matches every file in every directory
- `/module/**/*` matches all files in any directory below the `module` directory
- `/**/networking/*` matches every file that is inside any `networking` directory
- `/**/networking/**/*` matches every file that has `networking` directory on its path
- `/**/*.tf` matches every file in any directory that has the `.tf` extension
- `/submodule/*.???` matches every file inside `submodule` directory which has three characters long extension.

page title  VCS Connections   Workspaces   HCP Terraform description       Learn how to use the web UI to connect a workspace to a version control system repository that contains Terraform configuration         Configuring Workspace VCS Connections  You can connect any HCP Terraform  workspace   terraform cloud docs workspaces  to a version control system  VCS  repository that contains a Terraform configuration  This page explains the workspace VCS connection settings in the HCP Terraform UI   Refer to  Terraform Configurations in HCP Terraform Workspaces   terraform cloud docs workspaces configurations  for details on handling configuration versions and connected repositories  Refer to  Connecting VCS Providers   terraform cloud docs vcs  for a list of supported VCS providers and details about configuring VCS access  viewing VCS events  etc      API  You can use the  Update a Workspace endpoint   terraform cloud docs api docs workspaces update a workspace  in the Workspaces API to change one or more VCS settings  We also recommend using this endpoint to automate changing VCS connections for many workspaces at once  For example  when you move a VCS server or remove a deprecated API version      Version Control Settings  To change a workspace s VCS settings   1  Go to the workspace and click   Settings   Version Control    The   Version Control   page appears  1  Choose the desired settings and click   Update VCS settings     You can update the following types of VCS settings for the workspace       VCS Connection  You can take one of the following actions     To add a new VCS connection  click   Connect to version control    Select   Version control workflow   and follow the steps to  select a VCS provider and repository   terraform cloud docs workspaces create create a workspace     To edit an existing VCS connection  click   Change source    Choose the   Version control workflow   and follow the steps to  select VCS provider and repository   terraform cloud docs workspaces create create a workspace     To remove the VCS connection  click   Change source    Select either the   CLI driven workflow   or the   API driven workflow    and click   Update VCS settings    The workspace is no longer connected to VCS    permissions citation    intentionally unused   keep for maintainers      Terraform Working Directory  Specify the directory where Terraform will execute runs  This defaults to the root directory in your repository  but you may want to specify another directory if you have directories for multiple different Terraform configurations within the same repository  For example  if you had one  staging  directory and one  production  directory   A working directory is required when you use  trigger prefixes   automatic run triggering        Apply Method  Choose a workflow for Terraform runs       Auto apply    Terraform will apply changes from successful plans without prompting for approval  A push to the default branch of your repository will trigger a plan and apply cycle  You may want to do this in non interactive environments  like continuous deployment workflows          Warning    If you choose auto apply  make sure that no one can change your infrastructure outside of your automated build pipeline  This reduces the risk of configuration drift and unexpected changes       Manual apply    Terraform will ask for approval before applying changes from a successful plan  A push to the default branch of your repository will trigger a plan  and then Terraform will wait for confirmation       Automatic Run Triggering  HCP Terraform uses your VCS provider s API to retrieve the changed files in your repository  You can choose one of the following options to specify which changes trigger Terraform runs        Always trigger runs  This option instructs Terraform to begin a run when changes are pushed to any file within the repository  This can be useful for repositories that do not have multiple configurations but require a working directory for some other reason  However  we do not recommend this approach for true monorepos  as it queues unnecessary runs and slows down your ability to provision infrastructure        Only trigger runs when files in specified paths change  This option instructs Terraform to begin new runs only for changes that affect specified files and directories  This behavior also applies to  speculative plans   terraform cloud docs run remote operations speculative plans  on pull requests   You can use trigger patterns and trigger prefixes in the   Add path   field to specify groups of files and directories      Trigger Patterns     Recommended  Use glob patterns to specify the files that should trigger a new run  For example    submodule      tf   specifies all files with the   tf  extension that are nested below the  submodule  directory  You can also use more complex patterns like      networking        which specifies all files that have a  networking  folder in their file path   e g     submodule service 1 networking private main tf    Refer to  Glob Patterns for Automatic Run Triggering   glob patterns for automatic run triggering  for details      Trigger Prefixes    HCP Terraform will queue runs for changes in any of the specified trigger directories matching the provided prefixes  including the working directory   For example  if you use a top level  modules  directory to share Terraform code across multiple configurations  changes to the shared modules are relevant to every workspace that uses that repository  You can add  modules  as a trigger directory for each workspace to track changes to shared code        Note    HCP Terraform triggers runs on all attached workspaces if it does not receive a list of changed files or if that list is too large to process  When this happens  HCP Terraform may show several runs with completed plans that do not result in infrastructure changes        Trigger runs when a git tag is published  This option instructs Terraform to begin new runs only for changes that have a specific tag format   The tag format can be chosen between the following options      Semantic Versioning    It matches tags in the popular  SemVer format  https   semver org    For example   0 4 2       Version contains a prefix    It matches tags which have an additional prefix before the  SemVer format  https   semver org    For example   version 0 4 2       Version contains a suffix    It matches tags which have an additional suffix after the  SemVer format  https   semver org    For example  0 4 2 alpha       Custom Regular Expression    You can define your own regex for HCP Terraform to match against tags   You must include an additional     to escape the regex pattern when you manage your workspace with the  hashicorp tfe provider  https   registry terraform io providers hashicorp tfe latest docs resources workspace tags regex  and trigger runs through matching git tags  Refer to  Terraform escape sequences   terraform language expressions strings escape sequences  for more details     Tag Format                      Regex Pattern               Regex Pattern  Escaped                                                                                Semantic Versioning              d   d   d                    d    d    d                Version contains a prefix       d   d   d                    d    d    d                 Version contains a suffix        d   d   d                    d    d    d             HCP Terraform triggers runs for all tags matching this pattern  regardless of the value in the  VCS Branch   vcs branch  setting       VCS Branch  This setting designates which branch of the repository HCP Terraform should use when the workspace is set to  Always Trigger Runs   always trigger runs  or  Only trigger runs when files in specified paths change   only trigger runs when files in specified paths change   If you leave this setting blank  HCP Terraform uses the repository s default branch  If the workspace is set to trigger runs when a  git tag is published   trigger runs when a git tag is published   all tags will trigger runs  regardless of the branch specified in this setting       Automatic Speculative Plans  Whether to perform  speculative plans on pull requests   terraform cloud docs run ui speculative plans on pull requests  to the connected repository  to assist in reviewing proposed changes  Automatic speculative plans are enabled by default  but you can disable them for any workspace       Include Submodules on Clone  Select   Include submodules on clone   to recursively clone all of the repository s Git submodules when HCP Terraform fetches a configuration        Note    The  SSH key for cloning Git submodules   terraform cloud docs vcs ssh keys  is set in the VCS provider settings for the organization and is not related to the workspace s SSH key for Terraform modules      Glob Patterns for Automatic Run Triggering  We support  glob  patterns to describe a set of triggers for automatic runs  Refer to  trigger patterns   only trigger runs when files in specified paths change  for details   Supported wildcards         Matches zero or more characters         Matches one or more characters         Matches directories recursively   The following examples demonstrate how to use the supported wildcards            matches every file in every directory     module       matches all files in any directory below the  module  directory        networking    matches every file that is inside any  networking  directory        networking       matches every file that has  networking  directory on its path          tf  matches every file in any directory that has the   tf  extension     submodule        matches every file inside  submodule  directory which has three characters long extension


terraform entitlement terraform cloud docs api docs feature entitlements Learn how to integrate third party tools into the run lifecycle Create and delete run tasks and associate them with workspaces Run Tasks page title Run Tasks Workspaces HCP Terraform

Answer:
---
page_title: Run Tasks - Workspaces - HCP Terraform
description: >-
  Learn how to integrate third-party tools into the run lifecycle. Create and delete run tasks and associate them with workspaces.
---

[entitlement]: /terraform/cloud-docs/api-docs#feature-entitlements

# Run Tasks

HCP Terraform run tasks let you directly integrate third-party tools and services at certain stages in the HCP Terraform run lifecycle. Use run tasks to validate Terraform configuration files, analyze execution plans before applying them, scan for security vulnerabilities, or perform other custom actions.

Run tasks send data about a run to an external service at [specific run stages](#understanding-run-tasks-within-a-run). The external service processes the data, evaluates whether the run passes or fails, and sends a response to HCP Terraform. HCP Terraform then uses this response and the run task enforcement level to determine if a run can proceed. [Explore run tasks in the Terraform registry](https://registry.terraform.io/browse/run-tasks).

<!-- BEGIN: TFC:only name:pnp-callout -->
@include 'tfc-package-callouts/run-tasks.mdx'
<!-- END: TFC:only name:pnp-callout -->

You can manage run tasks through the HCP Terraform UI or the [Run Tasks API](/terraform/cloud-docs/api-docs/run-tasks/run-tasks).

> **Hands-on:** Try the [HCP Packer validation run task](/packer/tutorials/hcp/setup-hcp-terraform-run-task) tutorial.

## Requirements

**Terraform Version** - You can assign run tasks to workspaces that use a Terraform version of 1.1.9 and later. You can downgrade a workspace with existing runs to use a prior Terraform version without causing an error. However, HCP Terraform no longer triggers the run tasks during plan and apply operations.

**Permissions** - To create a run task, you must have a user account with the [Manage Run Tasks permission](/terraform/cloud-docs/users-teams-organizations/permissions#manage-run-tasks). To associate run tasks with a workspace, you need the [Manage Workspace Run Tasks permission](/terraform/cloud-docs/users-teams-organizations/permissions#general-workspace-permissions) on that particular workspace.

## Creating a Run Task

Explore the full list of [run tasks in the Terraform Registry](https://registry.terraform.io/browse/run-tasks).

Run tasks send an API payload to an external service. The API payload contains run-related information, including a callback URL, which the service uses to return a pass or fail status to HCP Terraform.

For example, the [HCP Packer integration](/terraform/cloud-docs/integrations/run-tasks#hcp-packer-run-task) checks image artifacts within a Terraform configuration for validity. If the configuration references images marked as unusable (revoked), then the run task fails and provides an error message.

To create a new run task:

1. Navigate to the desired workspace, open the **Settings** menu, and select **Run Tasks**.

1. Click **Create a new run task**. The **Run Tasks** page appears.

1. Enter the information about the run task to be configured:

   - **Enabled** (optional): Whether the run task will run across all associated workspaces. New tasks are enabled by default.
   - **Name** (required): A human-readable name for the run task. This will be displayed in workspace configuration pages and can contain letters, numbers, dashes and underscores.
   - **Endpoint URL** (required): The URL for the external service. Run tasks will POST the [run tasks payload](/terraform/cloud-docs/integrations/run-tasks#integration-details) to this URL.
   - **Description** (optional): A human-readable description for the run task. This information can contain letters, numbers, spaces, and special characters.
   - **HMAC key** (optional): A secret key that may be required by the external service to verify request authenticity.

1. Click **Create run task**. The run task is now available within the organization, and you can associate it with one or more workspaces.

### Global Run Tasks

When you create a new run task, you can choose to apply it globally to every workspace in an organization. Your organization must have the `global-run-task` [entitlement][] to use global run tasks.

1. Select the **Global** checkbox

1. Choose when HCP Terraform should start the run task:

   - **Pre-plan**: Before Terraform creates the plan.
   - **Post-plan**: After Terraform creates the plan.
   - **Pre-apply**: Before Terraform applies a plan.
   - **Post-apply**: After Terraform applies a plan.

1. Choose an enforcement level:

    - **Advisory**: Run tasks can not block a run from completing. If the task fails, the run proceeds with a warning in the user interface.
    - **Mandatory**: Failed run tasks can block a run from completing. If the task fails (including timeouts or unexpected remote errors), the run stops and errors with a warning in the user interface.

## Associating Run Tasks with a Workspace

1. Click **Workspaces** and then go to the workspace where you want to associate run tasks.

1. Open the **Settings** menu and select **Run Tasks**.

1. Click the **+** next to the task you want to add to the workspace.

1. Choose when HCP Terraform should start the run task:

   - **Pre-plan**: Before Terraform creates the plan.
   - **Post-plan**: After Terraform creates the plan.
   - **Pre-apply**: Before Terraform applies a plan.
   - **Post-apply**: After Terraform applies a plan.

1. Choose an enforcement level:

   - **Advisory**: Run tasks can not block a run from completing. If the task fails, the run will proceed with a warning in the UI.
   - **Mandatory**: Run tasks can block a run from completing. If the task fails (including a timeout or unexpected remote error condition), the run will transition to an Errored state with a warning in the UI.

1. Click **Create**. Your run task is now configured.

## Understanding Run Tasks Within a Run

Run tasks perform actions before and after, the [plan](/terraform/cloud-docs/run/states#the-plan-stage) and [apply](/terraform/cloud-docs/run/states#the-apply-stage) stages of a [Terraform run](/terraform/cloud-docs/run/remote-operations). Once all run tasks complete, the run ends based on the most restrictive enforcement level in each associated run task.

For example, if a mandatory task fails and an advisory task succeeds, the run fails. If an advisory task fails, but a mandatory task succeeds, the run succeeds and proceeds to the apply stage. Regardless of the exit status of a task, HCP Terraform displays the status and any related message data in the UI.

## Removing a Run Task from a Workspace

Removing a run task from a workspace does not delete it from the organization. To remove a run task from a specific workspace:

1. Navigate to the desired workspace, open the **Settings** menu and select **Run Tasks**.

1. Click the ellipses (...) on the associated run task, and then click **Remove**. The run task will no longer be applied to runs within the workspace.

## Deleting a Run Task

You must remove a run task from all associated workspaces before you can delete it. To delete a run task:

1. Navigate to **Settings** and click **Run Tasks**.

1. Click the ellipses (...) next to the run task you want to delete, and then click **Edit**.

1. Click **Delete run task**.

You cannot delete run tasks that are still associated with a workspace. If you attempt this, you will see a warning in the UI containing a list of all workspaces that are associated with the run task

page title  Run Tasks   Workspaces   HCP Terraform description       Learn how to integrate third party tools into the run lifecycle  Create and delete run tasks and associate them with workspaces        entitlement    terraform cloud docs api docs feature entitlements    Run Tasks  HCP Terraform run tasks let you directly integrate third party tools and services at certain stages in the HCP Terraform run lifecycle  Use run tasks to validate Terraform configuration files  analyze execution plans before applying them  scan for security vulnerabilities  or perform other custom actions   Run tasks send data about a run to an external service at  specific run stages   understanding run tasks within a run   The external service processes the data  evaluates whether the run passes or fails  and sends a response to HCP Terraform  HCP Terraform then uses this response and the run task enforcement level to determine if a run can proceed   Explore run tasks in the Terraform registry  https   registry terraform io browse run tasks         BEGIN  TFC only name pnp callout      include  tfc package callouts run tasks mdx       END  TFC only name pnp callout      You can manage run tasks through the HCP Terraform UI or the  Run Tasks API   terraform cloud docs api docs run tasks run tasks        Hands on    Try the  HCP Packer validation run task   packer tutorials hcp setup hcp terraform run task  tutorial      Requirements    Terraform Version     You can assign run tasks to workspaces that use a Terraform version of 1 1 9 and later  You can downgrade a workspace with existing runs to use a prior Terraform version without causing an error  However  HCP Terraform no longer triggers the run tasks during plan and apply operations     Permissions     To create a run task  you must have a user account with the  Manage Run Tasks permission   terraform cloud docs users teams organizations permissions manage run tasks   To associate run tasks with a workspace  you need the  Manage Workspace Run Tasks permission   terraform cloud docs users teams organizations permissions general workspace permissions  on that particular workspace      Creating a Run Task  Explore the full list of  run tasks in the Terraform Registry  https   registry terraform io browse run tasks     Run tasks send an API payload to an external service  The API payload contains run related information  including a callback URL  which the service uses to return a pass or fail status to HCP Terraform    For example  the  HCP Packer integration   terraform cloud docs integrations run tasks hcp packer run task  checks image artifacts within a Terraform configuration for validity  If the configuration references images marked as unusable  revoked   then the run task fails and provides an error message   To create a new run task   1  Navigate to the desired workspace  open the   Settings   menu  and select   Run Tasks     1  Click   Create a new run task    The   Run Tasks   page appears   1  Enter the information about the run task to be configured          Enabled    optional   Whether the run task will run across all associated workspaces  New tasks are enabled by default         Name    required   A human readable name for the run task  This will be displayed in workspace configuration pages and can contain letters  numbers  dashes and underscores         Endpoint URL    required   The URL for the external service  Run tasks will POST the  run tasks payload   terraform cloud docs integrations run tasks integration details  to this URL         Description    optional   A human readable description for the run task  This information can contain letters  numbers  spaces  and special characters         HMAC key    optional   A secret key that may be required by the external service to verify request authenticity   1  Click   Create run task    The run task is now available within the organization  and you can associate it with one or more workspaces       Global Run Tasks  When you create a new run task  you can choose to apply it globally to every workspace in an organization  Your organization must have the  global run task   entitlement    to use global run tasks   1  Select the   Global   checkbox  1  Choose when HCP Terraform should start the run task          Pre plan    Before Terraform creates the plan         Post plan    After Terraform creates the plan         Pre apply    Before Terraform applies a plan         Post apply    After Terraform applies a plan   1  Choose an enforcement level           Advisory    Run tasks can not block a run from completing  If the task fails  the run proceeds with a warning in the user interface          Mandatory    Failed run tasks can block a run from completing  If the task fails  including timeouts or unexpected remote errors   the run stops and errors with a warning in the user interface      Associating Run Tasks with a Workspace  1  Click   Workspaces   and then go to the workspace where you want to associate run tasks   1  Open the   Settings   menu and select   Run Tasks     1  Click the       next to the task you want to add to the workspace   1  Choose when HCP Terraform should start the run task          Pre plan    Before Terraform creates the plan         Post plan    After Terraform creates the plan         Pre apply    Before Terraform applies a plan         Post apply    After Terraform applies a plan   1  Choose an enforcement level          Advisory    Run tasks can not block a run from completing  If the task fails  the run will proceed with a warning in the UI         Mandatory    Run tasks can block a run from completing  If the task fails  including a timeout or unexpected remote error condition   the run will transition to an Errored state with a warning in the UI   1  Click   Create    Your run task is now configured      Understanding Run Tasks Within a Run  Run tasks perform actions before and after  the  plan   terraform cloud docs run states the plan stage  and  apply   terraform cloud docs run states the apply stage  stages of a  Terraform run   terraform cloud docs run remote operations   Once all run tasks complete  the run ends based on the most restrictive enforcement level in each associated run task   For example  if a mandatory task fails and an advisory task succeeds  the run fails  If an advisory task fails  but a mandatory task succeeds  the run succeeds and proceeds to the apply stage  Regardless of the exit status of a task  HCP Terraform displays the status and any related message data in the UI      Removing a Run Task from a Workspace  Removing a run task from a workspace does not delete it from the organization  To remove a run task from a specific workspace   1  Navigate to the desired workspace  open the   Settings   menu and select   Run Tasks     1  Click the ellipses       on the associated run task  and then click   Remove    The run task will no longer be applied to runs within the workspace      Deleting a Run Task  You must remove a run task from all associated workspaces before you can delete it  To delete a run task   1  Navigate to   Settings   and click   Run Tasks     1  Click the ellipses       next to the run task you want to delete  and then click   Edit     1  Click   Delete run task     You cannot delete run tasks that are still associated with a workspace  If you attempt this  you will see a warning in the UI containing a list of all workspaces that are associated with the run task


terraform your HCP Terraform runs Use OpenID Connect to get short term credentials for the Kubernetes and Helm Terraform providers in page title Dynamic Credentials with the Kubernetes and Helm Provider Workspaces HCP Terraform Dynamic Credentials with the Kubernetes and Helm providers Important If you are self hosting HCP Terraform agents terraform cloud docs agents ensure your agents use v1 13 1 terraform cloud docs agents changelog 1 13 1 10 25 2023 or above To use the latest dynamic credentials features upgrade your agents to the latest version terraform cloud docs agents changelog

Answer:
---
page_title: Dynamic Credentials with the Kubernetes and Helm Provider - Workspaces - HCP Terraform
description: >-
  Use OpenID Connect to get short-term credentials for the Kubernetes and Helm Terraform providers in
  your HCP Terraform runs.
---

# Dynamic Credentials with the Kubernetes and Helm providers

~> **Important:** If you are self-hosting [HCP Terraform agents](/terraform/cloud-docs/agents), ensure your agents use [v1.13.1](/terraform/cloud-docs/agents/changelog#1-13-1-10-25-2023) or above. To use the latest dynamic credentials features, [upgrade your agents to the latest version](/terraform/cloud-docs/agents/changelog).

You can use HCP Terraform’s native OpenID Connect integration with Kubernetes to use [dynamic credentials](/terraform/cloud-docs/workspaces/dynamic-provider-credentials) for the Kubernetes and Helm providers in your HCP Terraform runs. Configuring the integration requires the following steps:

1. **[Configure Kubernetes](#configure-kubernetes):** Set up a trust configuration between Kubernetes and HCP Terraform. Next, create Kubernetes role bindings for your HCP Terraform identities.
2. **[Configure HCP Terraform](#configure-hcp-terraform):** Add environment variables to the HCP Terraform workspaces where you want to use dynamic credentials.
3. **[Configure the Kubernetes or Helm provider](#configure-the-provider)**: Set the required attributes on the provider block.

Once you complete the setup, HCP Terraform automatically authenticates to Kubernetes during each run. The Kubernetes and Helm providers' authentication is valid for the length of a plan or apply operation.

## Configure Kubernetes

You must enable and configure an OIDC identity provider in the Kubernetes API. This workflow changes based on the platform hosting your Kubernetes cluster. HCP Terraform only supports dynamic credentials with Kubernetes in AWS and GCP.

### Configure an OIDC identity provider

Refer to the AWS documentation for guidance on [setting up an EKS cluster for OIDC authentication](https://docs.aws.amazon.com/eks/latest/userguide/authenticate-oidc-identity-provider.html). You can also refer to our [example configuration](https://github.com/hashicorp-education/learn-terraform-dynamic-credentials/tree/main/eks/trust).

Refer to the GCP documentation for guidance on [setting up a GKE cluster for OIDC authentication](https://cloud.google.com/kubernetes-engine/docs/how-to/oidc). You can also refer to our [example configuration](https://github.com/hashicorp-education/learn-terraform-dynamic-credentials/tree/main/gke/trust).

When inputting an "issuer URL", use the address of HCP Terraform (`https://app.terraform.io` _without_ a trailing slash) or the URL of your Terraform Enterprise instance. The value of "client ID" is your audience in OIDC terminology, and it should match the value of the `TFC_KUBERNETES_WORKLOAD_IDENTITY_AUDIENCE` environment variable in your workspace.

The OIDC identity resolves authentication to the Kubernetes API, but it first requires authorization to interact with that API. So, you must bind RBAC roles to the OIDC identity in Kubernetes.

You can use both "User" and "Group" subjects in your role bindings. For OIDC identities coming from TFC, the "User" value is formatted like so: `organization:<MY-ORG-NAME>:project:<MY-PROJECT-NAME>:workspace:<MY-WORKSPACE-NAME>:run_phase:<plan|apply>`.

You can extract the "Group" value from the token claim you configured in your cluster OIDC configuration. For details on the structure of the HCP Terraform token, refer to [Workload Identity](/terraform/cloud-docs/workspaces/dynamic-provider-credentials/workload-identity-tokens).

Below, we show an example of a `RoleBinding` for the HCP Terraform OIDC identity.

```hcl
resource "kubernetes_cluster_role_binding_v1" "oidc_role" {
  metadata {
    name = "odic-identity"
  }

  role_ref {
    api_group = "rbac.authorization.k8s.io"
    kind      = "ClusterRole"
    name      = var.rbac_group_cluster_role
  }

  // Option A - Bind RBAC roles to groups
  //
  // Groups are extracted from the token claim designated by 'rbac_group_oidc_claim'
  //
  subject {
    api_group = "rbac.authorization.k8s.io"
    kind      = "Group"
    name      = var.tfc_organization_name
  }

  // Option B - Bind RBAC roles to user identities
  //
  // Users are extracted from the 'sub' token claim.
  // Plan and apply phases get assigned different users identities.
  // For HCP Terraform tokens, the format of the user id is always the one described bellow.
  //
  subject {
    api_group = "rbac.authorization.k8s.io"
    kind      = "User"
    name      = "${var.tfc_hostname}#organization:${var.tfc_organization_name}:project:${var.tfc_project_name}:workspace:${var.tfc_workspace_name}:run_phase:plan"
  }

  subject {
    api_group = "rbac.authorization.k8s.io"
    kind      = "User"
    name      = "${var.tfc_hostname}#organization:${var.tfc_organization_name}:project:${var.tfc_project_name}:workspace:${var.tfc_workspace_name}:run_phase:apply"
  }
}
```

If binding with "User" subjects, be aware that plan and apply phases are assigned different identities, each requiring specific bindings. Meaning you can tailor permissions for each Terraform operation. Planning operations usually require "read-only" permissions, while apply operations also require "write" access.

!> **Warning**:  Always check, at minimum, the audience and the organization's name to prevent unauthorized access from other HCP Terraform organizations.

## Configure HCP Terraform

You must set certain environment variables in your HCP Terraform workspace to configure HCP Terraform to authenticate with Kubernetes or Helm using dynamic credentials. You can set these as workspace variables, or if you’d like to share one Kubernetes role across multiple workspaces, you can use a variable set. When you configure dynamic provider credentials with multiple provider configurations of the same type, use either a default variable or a tagged alias variable name for each provider configuration. Refer to [Specifying Multiple Configurations](#specifying-multiple-configurations) for more details.

### Required Environment Variables
| Variable                                                                                | Value                                                                         | Notes                                                                                |
|-------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `TFC_KUBERNETES_PROVIDER_AUTH`
`TFC_KUBERNETES_PROVIDER_AUTH[_TAG]`
_(Default variable not supported)_                                            | `true`                                                                        | Requires **v1.14.0** or later if self-managing agents. Must be present and set to `true`, or HCP Terraform will not attempt to authenticate to Kubernetes. |
| `TFC_KUBERNETES_WORKLOAD_IDENTITY_AUDIENCE`
`TFC_KUBERNETES_WORKLOAD_IDENTITY_AUDIENCE[_TAG]`
`TFC_DEFAULT_KUBERNETES_WORKLOAD_IDENTITY_AUDIENCE` | The audience name in your cluster's OIDC configuration, such as `kubernetes`. | Requires **v1.14.0** or later if self-managing agents.                                                                                |

## Configure the provider

The Kubernetes and Helm providers share the same schema of configuration attributes for the provider block. The example below illustrates using the Kubernetes provider but the same configuration applies to the Helm provider.

Make sure that you are not using any of the other arguments or methods listed in the [authentication](https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs#authentication) section of the provider documentation as these settings may interfere with dynamic provider credentials. The only allowed provider attributes are `host` and `cluster_ca_certificate`.

### Single provider instance

HCP Terraform automatically sets the `KUBE_TOKEN` environment variable and includes the workload identity token.

The provider needs to be configured with the URL of the API endpoint using the `host` attribute (or `KUBE_HOST` environment variable). In most cases, the `cluster_ca_certificate` (or `KUBE_CLUSTER_CA_CERT_DATA` environment variable) is also required.

#### Example Usage

```hcl
provider "kubernetes" {
  host                   = var.cluster-endpoint-url
  cluster_ca_certificate = base64decode(var.cluster-endpoint-ca)
}
```

### Multiple aliases

You can add additional variables to handle multiple distinct Kubernetes clusters, enabling you to use multiple [provider aliases](/terraform/language/providers/configuration#alias-multiple-provider-configurations) within the same workspace. You can configure each set of credentials independently, or use default values by configuring the variables prefixed with `TFC_DEFAULT_`.

For more details, see [Specifying Multiple Configurations](/terraform/cloud-docs/workspaces/dynamic-provider-credentials/specifying-multiple-configurations).

#### Required Terraform Variable

To use additional configurations, add the following code to your Terraform configuration. This lets HCP Terraform supply variable values that you can then use to map authentication and configuration details to the correct provider blocks.

```hcl
variable "tfc_kubernetes_dynamic_credentials" {
  description = "Object containing Kubernetes dynamic credentials configuration"
  type = object({
    default = object({
      token_path = string
    })
    aliases = map(object({
      token_path = string
    }))
  })
}
```

#### Example Usage

```hcl
provider "kubernetes" {
  alias                  = "ALIAS1"
  host                   = var.alias1-endpoint-url
  cluster_ca_certificate = base64decode(var.alias1-cluster-ca)
  token                  = file(var.tfc_kubernetes_dynamic_credentials.aliases["ALIAS1"].token_path)
}

provider "kubernetes" {
  alias                  = "ALIAS2"
  host                   = var.alias1-endpoint-url
  cluster_ca_certificate = base64decode(var.alias1-cluster-ca)
  token                  = file(var.tfc_kubernetes_dynamic_credentials.aliases["ALIAS2"].token_path)
}
```

The `tfc_kubernetes_dynamic_credentials` variable is also available to use for single provider configurations, instead of the `KUBE_TOKEN` environment variable.

```hcl
provider "kubernetes" {
  host                   = var.cluster-endpoint-url
  cluster_ca_certificate = base64decode(var.cluster-endpoint-ca)
  token                  = file(var.tfc_kubernetes_dynamic_credentials.default.token_path)
}
```

page title  Dynamic Credentials with the Kubernetes and Helm Provider   Workspaces   HCP Terraform description       Use OpenID Connect to get short term credentials for the Kubernetes and Helm Terraform providers in   your HCP Terraform runs         Dynamic Credentials with the Kubernetes and Helm providers       Important    If you are self hosting  HCP Terraform agents   terraform cloud docs agents   ensure your agents use  v1 13 1   terraform cloud docs agents changelog 1 13 1 10 25 2023  or above  To use the latest dynamic credentials features   upgrade your agents to the latest version   terraform cloud docs agents changelog    You can use HCP Terraform s native OpenID Connect integration with Kubernetes to use  dynamic credentials   terraform cloud docs workspaces dynamic provider credentials  for the Kubernetes and Helm providers in your HCP Terraform runs  Configuring the integration requires the following steps   1     Configure Kubernetes   configure kubernetes     Set up a trust configuration between Kubernetes and HCP Terraform  Next  create Kubernetes role bindings for your HCP Terraform identities  2     Configure HCP Terraform   configure hcp terraform     Add environment variables to the HCP Terraform workspaces where you want to use dynamic credentials  3     Configure the Kubernetes or Helm provider   configure the provider     Set the required attributes on the provider block   Once you complete the setup  HCP Terraform automatically authenticates to Kubernetes during each run  The Kubernetes and Helm providers  authentication is valid for the length of a plan or apply operation      Configure Kubernetes  You must enable and configure an OIDC identity provider in the Kubernetes API  This workflow changes based on the platform hosting your Kubernetes cluster  HCP Terraform only supports dynamic credentials with Kubernetes in AWS and GCP       Configure an OIDC identity provider  Refer to the AWS documentation for guidance on  setting up an EKS cluster for OIDC authentication  https   docs aws amazon com eks latest userguide authenticate oidc identity provider html   You can also refer to our  example configuration  https   github com hashicorp education learn terraform dynamic credentials tree main eks trust    Refer to the GCP documentation for guidance on  setting up a GKE cluster for OIDC authentication  https   cloud google com kubernetes engine docs how to oidc   You can also refer to our  example configuration  https   github com hashicorp education learn terraform dynamic credentials tree main gke trust    When inputting an  issuer URL   use the address of HCP Terraform   https   app terraform io   without  a trailing slash  or the URL of your Terraform Enterprise instance  The value of  client ID  is your audience in OIDC terminology  and it should match the value of the  TFC KUBERNETES WORKLOAD IDENTITY AUDIENCE  environment variable in your workspace   The OIDC identity resolves authentication to the Kubernetes API  but it first requires authorization to interact with that API  So  you must bind RBAC roles to the OIDC identity in Kubernetes   You can use both  User  and  Group  subjects in your role bindings  For OIDC identities coming from TFC  the  User  value is formatted like so   organization  MY ORG NAME  project  MY PROJECT NAME  workspace  MY WORKSPACE NAME  run phase  plan apply      You can extract the  Group  value from the token claim you configured in your cluster OIDC configuration  For details on the structure of the HCP Terraform token  refer to  Workload Identity   terraform cloud docs workspaces dynamic provider credentials workload identity tokens    Below  we show an example of a  RoleBinding  for the HCP Terraform OIDC identity      hcl resource  kubernetes cluster role binding v1   oidc role      metadata       name    odic identity         role ref       api group    rbac authorization k8s io      kind         ClusterRole      name        var rbac group cluster role           Option A   Bind RBAC roles to groups           Groups are extracted from the token claim designated by  rbac group oidc claim         subject       api group    rbac authorization k8s io      kind         Group      name        var tfc organization name           Option B   Bind RBAC roles to user identities           Users are extracted from the  sub  token claim       Plan and apply phases get assigned different users identities       For HCP Terraform tokens  the format of the user id is always the one described bellow         subject       api group    rbac authorization k8s io      kind         User      name           var tfc hostname  organization   var tfc organization name  project   var tfc project name  workspace   var tfc workspace name  run phase plan         subject       api group    rbac authorization k8s io      kind         User      name           var tfc hostname  organization   var tfc organization name  project   var tfc project name  workspace   var tfc workspace name  run phase apply             If binding with  User  subjects  be aware that plan and apply phases are assigned different identities  each requiring specific bindings  Meaning you can tailor permissions for each Terraform operation  Planning operations usually require  read only  permissions  while apply operations also require  write  access        Warning     Always check  at minimum  the audience and the organization s name to prevent unauthorized access from other HCP Terraform organizations      Configure HCP Terraform  You must set certain environment variables in your HCP Terraform workspace to configure HCP Terraform to authenticate with Kubernetes or Helm using dynamic credentials  You can set these as workspace variables  or if you d like to share one Kubernetes role across multiple workspaces  you can use a variable set  When you configure dynamic provider credentials with multiple provider configurations of the same type  use either a default variable or a tagged alias variable name for each provider configuration  Refer to  Specifying Multiple Configurations   specifying multiple configurations  for more details       Required Environment Variables   Variable                                                                                Value                                                                           Notes                                                                                TFC KUBERNETES PROVIDER AUTH  br    TFC KUBERNETES PROVIDER AUTH  TAG   br     Default variable not supported                                                 true                                                                           Requires   v1 14 0   or later if self managing agents  Must be present and set to  true   or HCP Terraform will not attempt to authenticate to Kubernetes       TFC KUBERNETES WORKLOAD IDENTITY AUDIENCE  br    TFC KUBERNETES WORKLOAD IDENTITY AUDIENCE  TAG   br    TFC DEFAULT KUBERNETES WORKLOAD IDENTITY AUDIENCE    The audience name in your cluster s OIDC configuration  such as  kubernetes     Requires   v1 14 0   or later if self managing agents                                                                                Configure the provider  The Kubernetes and Helm providers share the same schema of configuration attributes for the provider block  The example below illustrates using the Kubernetes provider but the same configuration applies to the Helm provider   Make sure that you are not using any of the other arguments or methods listed in the  authentication  https   registry terraform io providers hashicorp kubernetes latest docs authentication  section of the provider documentation as these settings may interfere with dynamic provider credentials  The only allowed provider attributes are  host  and  cluster ca certificate        Single provider instance  HCP Terraform automatically sets the  KUBE TOKEN  environment variable and includes the workload identity token   The provider needs to be configured with the URL of the API endpoint using the  host  attribute  or  KUBE HOST  environment variable   In most cases  the  cluster ca certificate   or  KUBE CLUSTER CA CERT DATA  environment variable  is also required        Example Usage     hcl provider  kubernetes      host                     var cluster endpoint url   cluster ca certificate   base64decode var cluster endpoint ca             Multiple aliases  You can add additional variables to handle multiple distinct Kubernetes clusters  enabling you to use multiple  provider aliases   terraform language providers configuration alias multiple provider configurations  within the same workspace  You can configure each set of credentials independently  or use default values by configuring the variables prefixed with  TFC DEFAULT     For more details  see  Specifying Multiple Configurations   terraform cloud docs workspaces dynamic provider credentials specifying multiple configurations         Required Terraform Variable  To use additional configurations  add the following code to your Terraform configuration  This lets HCP Terraform supply variable values that you can then use to map authentication and configuration details to the correct provider blocks      hcl variable  tfc kubernetes dynamic credentials      description    Object containing Kubernetes dynamic credentials configuration    type   object       default   object         token path   string            aliases   map object         token path   string                          Example Usage     hcl provider  kubernetes      alias                     ALIAS1    host                     var alias1 endpoint url   cluster ca certificate   base64decode var alias1 cluster ca    token                    file var tfc kubernetes dynamic credentials aliases  ALIAS1   token path     provider  kubernetes      alias                     ALIAS2    host                     var alias1 endpoint url   cluster ca certificate   base64decode var alias1 cluster ca    token                    file var tfc kubernetes dynamic credentials aliases  ALIAS2   token path         The  tfc kubernetes dynamic credentials  variable is also available to use for single provider configurations  instead of the  KUBE TOKEN  environment variable      hcl provider  kubernetes      host                     var cluster endpoint url   cluster ca certificate   base64decode var cluster endpoint ca    token                    file var tfc kubernetes dynamic credentials default token path


terraform Dynamic Credentials with the Vault Provider your HCP Terraform runs Important If you are self hosting HCP Terraform agents terraform cloud docs agents ensure your agents use v1 7 0 terraform cloud docs agents changelog 1 7 0 03 02 2023 or above To use the latest dynamic credentials features upgrade your agents to the latest version terraform cloud docs agents changelog Use OpenID Connect to get short term credentials for the Vault Terraform provider in page title Dynamic Credentials with the Vault Provider Workspaces HCP Terraform

Answer:
---
page_title: Dynamic Credentials with the Vault Provider - Workspaces - HCP Terraform
description: >-
  Use OpenID Connect to get short-term credentials for the Vault Terraform provider in
  your HCP Terraform runs.
---

# Dynamic Credentials with the Vault Provider

~> **Important:** If you are self-hosting [HCP Terraform agents](/terraform/cloud-docs/agents), ensure your agents use [v1.7.0](/terraform/cloud-docs/agents/changelog#1-7-0-03-02-2023) or above. To use the latest dynamic credentials features, [upgrade your agents to the latest version](/terraform/cloud-docs/agents/changelog).

You can use HCP Terraform’s native OpenID Connect integration with Vault to get [dynamic credentials](/terraform/cloud-docs/workspaces/dynamic-provider-credentials) for the Vault provider in your HCP Terraform runs. Configuring the integration requires the following steps:

1. **[Configure Vault](#configure-vault):** Set up a trust configuration between Vault and HCP Terraform. Then, you must create Vault roles and policies for your HCP Terraform workspaces.
2. **[Configure HCP Terraform](#configure-hcp-terraform):** Add environment variables to the HCP Terraform workspaces where you want to use Dynamic Credentials.

Once you complete the setup, HCP Terraform automatically authenticates to Vault during each run. The Vault provider authentication is valid for the length of the plan or apply. Vault does not revoke authentication until the run is complete.

If you are using Vault's [secrets engines](/vault/docs/secrets), you must complete the following set up before continuing to configure [Vault-backed dynamic credentials](/terraform/cloud-docs/workspaces/dynamic-provider-credentials/vault-backed).

## Configure Vault
You must enable and configure the JWT backend in Vault. These instructions use the Vault CLI commands, but you can also use Terraform to configure Vault. Refer to our [example Terraform configuration](https://github.com/hashicorp/terraform-dynamic-credentials-setup-examples/tree/main/vault).
### Enable the JWT Auth Backend
Run the following command to enable the JWT auth backend in Vault:
```shell
vault auth enable jwt
```
### Configure Trust with HCP Terraform
You must configure Vault to trust HCP Terraform’s identity tokens and verify them using HCP Terraform’s public key. The following command configures the `jwt` auth backend in Vault to trust HCP Terraform as an OIDC identity provider:
```shell
vault write auth/jwt/config \
    oidc_discovery_url="https://app.terraform.io" \
    bound_issuer="https://app.terraform.io"
```
The `oidc_discovery_url` and `bound_issuer` should both be the root address of HCP Terraform, including the scheme and without a trailing slash.

#### Terraform Enterprise Specific Requirements

If you are using a custom or self-signed CA certificate you may need to specify the CA certificate or chain of certificates, in PEM format, via the [`oidc_discovery_ca_pem`](/vault/api-docs/auth/jwt#oidc_discovery_ca_pem) argument as shown in the following example command:
```shell
vault write auth/jwt/config \
    oidc_discovery_url="https://app.terraform.io" \
    bound_issuer="https://app.terraform.io" \
    oidc_discovery_ca_pem=@my-cert.pem
```

In the example above, `my-cert.pem` is a PEM formatted file containing the certificate.

### Create a Vault Policy

You must create a Vault policy that controls what paths and secrets your HCP Terraform workspace can access in Vault.
Create a file called tfc-policy.hcl with the following content:
```hcl
# Allow tokens to query themselves
path "auth/token/lookup-self" {
  capabilities = ["read"]
}

# Allow tokens to renew themselves
path "auth/token/renew-self" {
    capabilities = ["update"]
}

# Allow tokens to revoke themselves
path "auth/token/revoke-self" {
    capabilities = ["update"]
}

# Configure the actual secrets the token should have access to
path "secret/*" {
  capabilities = ["read"]
}
```

Then create the policy in Vault:

```shell
vault policy write tfc-policy tfc-policy.hcl
```

### Create a JWT Auth Role
Create a Vault role that HCP Terraform can use when authenticating to Vault.

Vault offers a lot of flexibility in determining how to map roles and permissions in Vault to workspaces in HCP Terraform. You can have one role for each workspace, one role for a group of workspaces, or one role for all workspaces in an organization. You can also configure different roles for the plan and apply phases of a run.

-> **Note:** If you set your `user_claim` to be per workspace, then Vault ties the entity it creates to that workspace's name. If you rename the workspace tied to your `user_claim`, Vault will create an additional identity object. To avoid this, update the alias name in Vault to your new workspace name before you update it in HCP Terraform.

The following example creates a role called `tfc-role`. The role is mapped to a single workspace and HCP Terraform can use it for both plan and apply runs.

Create a file called `vault-jwt-auth-role.json` with the following content:
```json
{
  "policies": ["tfc-policy"],
  "bound_audiences": ["vault.workload.identity"],
  "bound_claims_type": "glob",
  "bound_claims": {
    "sub":
"organization:my-org-name:project:my-project-name:workspace:my-workspace-name:run_phase:*"
  },
  "user_claim": "terraform_full_workspace",
  "role_type": "jwt",
  "token_ttl": "20m"
}
```

Then run the following command to create a role named `tfc-role` with this configuration in Vault:
```shell
vault write auth/jwt/role/tfc-role @vault-jwt-auth-role.json
```
To understand all the available options for matching bound claims, refer to the [Terraform workload identity claim specification](/terraform/cloud-docs/workspaces/dynamic-provider-credentials) and the [Vault documentation on configuring bound claims](/vault/docs/auth/jwt#bound-claims). To understand all the options available when configuring Vault JWT auth roles, refer to the [Vault API documentation](/vault/api-docs/auth/jwt#create-role).

!> **Warning:** you should always check, at minimum, the audience and the name of the organization in order to prevent unauthorized access from other HCP Terraform organizations!

#### Token TTLs
We recommend setting token_ttl to a relatively short value. HCP Terraform can renew the token periodically until the plan or apply is complete, then revoke it to prevent it from being used further.

## Configure HCP Terraform
You’ll need to set some environment variables in your HCP Terraform workspace in order to configure HCP Terraform to authenticate with Vault using dynamic credentials. You can set these as workspace variables, or if you’d like to share one Vault role across multiple workspaces, you can use a variable set. When you configure dynamic provider credentials with multiple provider configurations of the same type, use either a default variable or a tagged alias variable name for each provider configuration. Refer to [Specifying Multiple Configurations](#specifying-multiple-configurations) for more details.

### Required Environment Variables
| Variable                                                                                | Value                                                                            | Notes                                                                                |
|--------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `TFC_VAULT_PROVIDER_AUTH`
`TFC_VAULT_PROVIDER_AUTH[_TAG]`
_(Default variable not supported)_ | `true`                                                                           | Requires **v1.7.0** or later if self-managing agents. Must be present and set to `true`, or HCP Terraform will not attempt to authenticate to Vault.                                                                                |
| `TFC_VAULT_ADDR`
`TFC_VAULT_ADDR[_TAG]`
`TFC_DEFAULT_VAULT_ADDR`                             | The address of the Vault instance to authenticate against.                       | Requires **v1.7.0** or later if self-managing agents. Will also be used to set `VAULT_ADDR` in the run environment.                                                                                |
| `TFC_VAULT_RUN_ROLE`
`TFC_VAULT_RUN_ROLE[_TAG]`
`TFC_DEFAULT_VAULT_RUN_ROLE`                 | The name of the Vault role to authenticate against (`tfc-role`, in our example). | Requires **v1.7.0** or later if self-managing agents. Optional if `TFC_VAULT_PLAN_ROLE` and `TFC_VAULT_APPLY_ROLE` are both provided. These variables are described [below](/terraform/cloud-docs/workspaces/dynamic-provider-credentials/vault-configuration#optional-environment-variables) |

### Optional Environment Variables
You may need to set these variables, depending on your Vault configuration and use case.

| Variable                                                                                | Value                                                                                | Notes                                                                                |
|----------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `TFC_VAULT_NAMESPACE`
`TFC_VAULT_NAMESPACE[_TAG]`
`TFC_DEFAULT_VAULT_NAMESPACE`                                                    | The namespace to use when authenticating to Vault.                                             | Requires **v1.7.0** or later if self-managing agents. Will also be used to set `VAULT_NAMESPACE` in the run environment.                                                                                |
| `TFC_VAULT_AUTH_PATH`
`TFC_VAULT_AUTH_PATH[_TAG]`
`TFC_DEFAULT_VAULT_AUTH_PATH`                                                    | The path where the JWT auth backend is mounted in Vault. Defaults to jwt.                      | Requires **v1.7.0** or later if self-managing agents.                                                                                |
| `TFC_VAULT_WORKLOAD_IDENTITY_AUDIENCE`
`TFC_VAULT_WORKLOAD_IDENTITY_AUDIENCE[_TAG]`
`TFC_DEFAULT_VAULT_WORKLOAD_IDENTITY_AUDIENCE` | Will be used as the `aud` claim for the identity token. Defaults to `vault.workload.identity`. | Requires **v1.7.0** or later if self-managing agents. Must match the `bound_audiences` configured for the role in Vault.                                                                                |
| `TFC_VAULT_PLAN_ROLE`
`TFC_VAULT_PLAN_ROLE[_TAG]`
`TFC_DEFAULT_VAULT_PLAN_ROLE`                                                    | The Vault role to use for the plan phase of a run.                                             | Requires **v1.7.0** or later if self-managing agents. Will fall back to the value of `TFC_VAULT_RUN_ROLE` if not provided.                                                                                |
| `TFC_VAULT_APPLY_ROLE`
`TFC_VAULT_APPLY_ROLE[_TAG]`
`TFC_DEFAULT_VAULT_APPLY_ROLE`                                                 | The Vault role to use for the apply phase of a run.                                            | Requires **v1.7.0** or later if self-managing agents. Will fall back to the value of `TFC_VAULT_RUN_ROLE` if not provided.                                                                                |
| `TFC_VAULT_ENCODED_CACERT`
`TFC_VAULT_ENCODED_CACERT[_TAG]`
`TFC_DEFAULT_VAULT_ENCODED_CACERT`                                     | A PEM-encoded CA certificate that has been Base64 encoded.                                     | Requires **v1.9.0** or later if self-managing agents. This certificate will be used when connecting to Vault. May be required when connecting to Vault instances that use a custom or self-signed certificate. |

## Vault Provider Configuration
Once you set up dynamic credentials for a workspace, HCP Terraform automatically authenticates to Vault for each run. Do not pass the `address`, `token`, or `namespace` arguments into the provider configuration block. HCP Terraform sets these values as environment variables in the run environment.

You can use the Vault provider to read static secrets from Vault and use them with other Terraform resources. You can also access the other resources and data sources available in the [Vault provider documentation](https://registry.terraform.io/providers/hashicorp/vault/latest). You must adjust your [Vault policy](#create-a-vault-policy) to give your HCP Terraform workspace access to all required Vault paths.

~> **Important:** data sources that use secrets engines to generate dynamic secrets must not be used with Vault dynamic credentials. You can use Vault's dynamic secrets engines for AWS, GCP, and Azure by adding additional configurations. For more details, see [Vault-backed dynamic credentials](/terraform/cloud-docs/workspaces/dynamic-provider-credentials/vault-backed).

### Specifying Multiple Configurations

~> **Important:** If you are self-hosting [HCP Terraform agents](/terraform/cloud-docs/agents), ensure your agents use [v1.12.0](/terraform/cloud-docs/agents/changelog#1-12-0-07-26-2023) or above. To use the latest dynamic credentials features, [upgrade your agents to the latest version](/terraform/cloud-docs/agents/changelog).

~> **Important:** Ensure you are using version **3.18.0** or later of the **Vault provider** as the required [`auth_login_token_file`](https://registry.terraform.io/providers/hashicorp/vault/latest/docs#token-file) block was introduced in this provider version.

You can add additional variables to handle multiple distinct Vault setups, enabling you to use multiple [provider aliases](/terraform/language/providers/configuration#alias-multiple-provider-configurations) within the same workspace. You can configure each set of credentials independently, or use default values by configuring the variables prefixed with `TFC_DEFAULT_`.

For more details, see [Specifying Multiple Configurations](/terraform/cloud-docs/workspaces/dynamic-provider-credentials/specifying-multiple-configurations).

#### Required Terraform Variable

To use additional configurations, add the following code to your Terraform configuration. This lets HCP Terraform supply variable values that you can then use to map authentication and configuration details to the correct provider blocks.

```hcl
variable "tfc_vault_dynamic_credentials" {
  description = "Object containing Vault dynamic credentials configuration"
  type = object({
    default = object({
      token_filename = string
      address = string
      namespace = string
      ca_cert_file = string
    })
    aliases = map(object({
      token_filename = string
      address = string
      namespace = string
      ca_cert_file = string
    }))
  })
}
```

#### Example Usage

```hcl
provider "vault" {
  // skip_child_token must be explicitly set to true as HCP Terraform manages the token lifecycle
  skip_child_token = true
  address          = var.tfc_vault_dynamic_credentials.default.address
  namespace        = var.tfc_vault_dynamic_credentials.default.namespace

  auth_login_token_file {
    filename = var.tfc_vault_dynamic_credentials.default.token_filename
  }
}

provider "vault" {
  // skip_child_token must be explicitly set to true as HCP Terraform manages the token lifecycle
  skip_child_token = true
  alias            = "ALIAS1"
  address          = var.tfc_vault_dynamic_credentials.aliases["ALIAS1"].address
  namespace        = var.tfc_vault_dynamic_credentials.aliases["ALIAS1"].namespace

  auth_login_token_file {
    filename = var.tfc_vault_dynamic_credentials.aliases["ALIAS1"].token_filename
  }
}
```

page title  Dynamic Credentials with the Vault Provider   Workspaces   HCP Terraform description       Use OpenID Connect to get short term credentials for the Vault Terraform provider in   your HCP Terraform runs         Dynamic Credentials with the Vault Provider       Important    If you are self hosting  HCP Terraform agents   terraform cloud docs agents   ensure your agents use  v1 7 0   terraform cloud docs agents changelog 1 7 0 03 02 2023  or above  To use the latest dynamic credentials features   upgrade your agents to the latest version   terraform cloud docs agents changelog    You can use HCP Terraform s native OpenID Connect integration with Vault to get  dynamic credentials   terraform cloud docs workspaces dynamic provider credentials  for the Vault provider in your HCP Terraform runs  Configuring the integration requires the following steps   1     Configure Vault   configure vault     Set up a trust configuration between Vault and HCP Terraform  Then  you must create Vault roles and policies for your HCP Terraform workspaces  2     Configure HCP Terraform   configure hcp terraform     Add environment variables to the HCP Terraform workspaces where you want to use Dynamic Credentials   Once you complete the setup  HCP Terraform automatically authenticates to Vault during each run  The Vault provider authentication is valid for the length of the plan or apply  Vault does not revoke authentication until the run is complete   If you are using Vault s  secrets engines   vault docs secrets   you must complete the following set up before continuing to configure  Vault backed dynamic credentials   terraform cloud docs workspaces dynamic provider credentials vault backed       Configure Vault You must enable and configure the JWT backend in Vault  These instructions use the Vault CLI commands  but you can also use Terraform to configure Vault  Refer to our  example Terraform configuration  https   github com hashicorp terraform dynamic credentials setup examples tree main vault       Enable the JWT Auth Backend Run the following command to enable the JWT auth backend in Vault     shell vault auth enable jwt         Configure Trust with HCP Terraform You must configure Vault to trust HCP Terraform s identity tokens and verify them using HCP Terraform s public key  The following command configures the  jwt  auth backend in Vault to trust HCP Terraform as an OIDC identity provider     shell vault write auth jwt config       oidc discovery url  https   app terraform io        bound issuer  https   app terraform io      The  oidc discovery url  and  bound issuer  should both be the root address of HCP Terraform  including the scheme and without a trailing slash        Terraform Enterprise Specific Requirements  If you are using a custom or self signed CA certificate you may need to specify the CA certificate or chain of certificates  in PEM format  via the   oidc discovery ca pem    vault api docs auth jwt oidc discovery ca pem  argument as shown in the following example command     shell vault write auth jwt config       oidc discovery url  https   app terraform io        bound issuer  https   app terraform io        oidc discovery ca pem  my cert pem      In the example above   my cert pem  is a PEM formatted file containing the certificate       Create a Vault Policy  You must create a Vault policy that controls what paths and secrets your HCP Terraform workspace can access in Vault  Create a file called tfc policy hcl with the following content     hcl   Allow tokens to query themselves path  auth token lookup self      capabilities     read        Allow tokens to renew themselves path  auth token renew self        capabilities     update        Allow tokens to revoke themselves path  auth token revoke self        capabilities     update        Configure the actual secrets the token should have access to path  secret        capabilities     read          Then create the policy in Vault      shell vault policy write tfc policy tfc policy hcl          Create a JWT Auth Role Create a Vault role that HCP Terraform can use when authenticating to Vault   Vault offers a lot of flexibility in determining how to map roles and permissions in Vault to workspaces in HCP Terraform  You can have one role for each workspace  one role for a group of workspaces  or one role for all workspaces in an organization  You can also configure different roles for the plan and apply phases of a run        Note    If you set your  user claim  to be per workspace  then Vault ties the entity it creates to that workspace s name  If you rename the workspace tied to your  user claim   Vault will create an additional identity object  To avoid this  update the alias name in Vault to your new workspace name before you update it in HCP Terraform   The following example creates a role called  tfc role   The role is mapped to a single workspace and HCP Terraform can use it for both plan and apply runs   Create a file called  vault jwt auth role json  with the following content     json      policies     tfc policy       bound audiences     vault workload identity       bound claims type    glob      bound claims          sub    organization my org name project my project name workspace my workspace name run phase            user claim    terraform full workspace      role type    jwt      token ttl    20m         Then run the following command to create a role named  tfc role  with this configuration in Vault     shell vault write auth jwt role tfc role  vault jwt auth role json     To understand all the available options for matching bound claims  refer to the  Terraform workload identity claim specification   terraform cloud docs workspaces dynamic provider credentials  and the  Vault documentation on configuring bound claims   vault docs auth jwt bound claims   To understand all the options available when configuring Vault JWT auth roles  refer to the  Vault API documentation   vault api docs auth jwt create role         Warning    you should always check  at minimum  the audience and the name of the organization in order to prevent unauthorized access from other HCP Terraform organizations        Token TTLs We recommend setting token ttl to a relatively short value  HCP Terraform can renew the token periodically until the plan or apply is complete  then revoke it to prevent it from being used further      Configure HCP Terraform You ll need to set some environment variables in your HCP Terraform workspace in order to configure HCP Terraform to authenticate with Vault using dynamic credentials  You can set these as workspace variables  or if you d like to share one Vault role across multiple workspaces  you can use a variable set  When you configure dynamic provider credentials with multiple provider configurations of the same type  use either a default variable or a tagged alias variable name for each provider configuration  Refer to  Specifying Multiple Configurations   specifying multiple configurations  for more details       Required Environment Variables   Variable                                                                                Value                                                                              Notes                                                                                TFC VAULT PROVIDER AUTH  br    TFC VAULT PROVIDER AUTH  TAG   br     Default variable not supported      true                                                                              Requires   v1 7 0   or later if self managing agents  Must be present and set to  true   or HCP Terraform will not attempt to authenticate to Vault                                                                                TFC VAULT ADDR  br    TFC VAULT ADDR  TAG   br    TFC DEFAULT VAULT ADDR                                The address of the Vault instance to authenticate against                          Requires   v1 7 0   or later if self managing agents  Will also be used to set  VAULT ADDR  in the run environment                                                                                TFC VAULT RUN ROLE  br    TFC VAULT RUN ROLE  TAG   br    TFC DEFAULT VAULT RUN ROLE                    The name of the Vault role to authenticate against   tfc role   in our example     Requires   v1 7 0   or later if self managing agents  Optional if  TFC VAULT PLAN ROLE  and  TFC VAULT APPLY ROLE  are both provided  These variables are described  below   terraform cloud docs workspaces dynamic provider credentials vault configuration optional environment variables         Optional Environment Variables You may need to set these variables  depending on your Vault configuration and use case     Variable                                                                                Value                                                                                Notes                                                                                TFC VAULT NAMESPACE  br    TFC VAULT NAMESPACE  TAG   br    TFC DEFAULT VAULT NAMESPACE                                                       The namespace to use when authenticating to Vault                                                Requires   v1 7 0   or later if self managing agents  Will also be used to set  VAULT NAMESPACE  in the run environment                                                                                TFC VAULT AUTH PATH  br    TFC VAULT AUTH PATH  TAG   br    TFC DEFAULT VAULT AUTH PATH                                                       The path where the JWT auth backend is mounted in Vault  Defaults to jwt                         Requires   v1 7 0   or later if self managing agents                                                                                TFC VAULT WORKLOAD IDENTITY AUDIENCE  br    TFC VAULT WORKLOAD IDENTITY AUDIENCE  TAG   br    TFC DEFAULT VAULT WORKLOAD IDENTITY AUDIENCE    Will be used as the  aud  claim for the identity token  Defaults to  vault workload identity     Requires   v1 7 0   or later if self managing agents  Must match the  bound audiences  configured for the role in Vault                                                                                TFC VAULT PLAN ROLE  br    TFC VAULT PLAN ROLE  TAG   br    TFC DEFAULT VAULT PLAN ROLE                                                       The Vault role to use for the plan phase of a run                                                Requires   v1 7 0   or later if self managing agents  Will fall back to the value of  TFC VAULT RUN ROLE  if not provided                                                                                TFC VAULT APPLY ROLE  br    TFC VAULT APPLY ROLE  TAG   br    TFC DEFAULT VAULT APPLY ROLE                                                    The Vault role to use for the apply phase of a run                                               Requires   v1 7 0   or later if self managing agents  Will fall back to the value of  TFC VAULT RUN ROLE  if not provided                                                                                TFC VAULT ENCODED CACERT  br    TFC VAULT ENCODED CACERT  TAG   br    TFC DEFAULT VAULT ENCODED CACERT                                        A PEM encoded CA certificate that has been Base64 encoded                                        Requires   v1 9 0   or later if self managing agents  This certificate will be used when connecting to Vault  May be required when connecting to Vault instances that use a custom or self signed certificate        Vault Provider Configuration Once you set up dynamic credentials for a workspace  HCP Terraform automatically authenticates to Vault for each run  Do not pass the  address    token   or  namespace  arguments into the provider configuration block  HCP Terraform sets these values as environment variables in the run environment   You can use the Vault provider to read static secrets from Vault and use them with other Terraform resources  You can also access the other resources and data sources available in the  Vault provider documentation  https   registry terraform io providers hashicorp vault latest   You must adjust your  Vault policy   create a vault policy  to give your HCP Terraform workspace access to all required Vault paths        Important    data sources that use secrets engines to generate dynamic secrets must not be used with Vault dynamic credentials  You can use Vault s dynamic secrets engines for AWS  GCP  and Azure by adding additional configurations  For more details  see  Vault backed dynamic credentials   terraform cloud docs workspaces dynamic provider credentials vault backed        Specifying Multiple Configurations       Important    If you are self hosting  HCP Terraform agents   terraform cloud docs agents   ensure your agents use  v1 12 0   terraform cloud docs agents changelog 1 12 0 07 26 2023  or above  To use the latest dynamic credentials features   upgrade your agents to the latest version   terraform cloud docs agents changelog         Important    Ensure you are using version   3 18 0   or later of the   Vault provider   as the required   auth login token file   https   registry terraform io providers hashicorp vault latest docs token file  block was introduced in this provider version   You can add additional variables to handle multiple distinct Vault setups  enabling you to use multiple  provider aliases   terraform language providers configuration alias multiple provider configurations  within the same workspace  You can configure each set of credentials independently  or use default values by configuring the variables prefixed with  TFC DEFAULT     For more details  see  Specifying Multiple Configurations   terraform cloud docs workspaces dynamic provider credentials specifying multiple configurations         Required Terraform Variable  To use additional configurations  add the following code to your Terraform configuration  This lets HCP Terraform supply variable values that you can then use to map authentication and configuration details to the correct provider blocks      hcl variable  tfc vault dynamic credentials      description    Object containing Vault dynamic credentials configuration    type   object       default   object         token filename   string       address   string       namespace   string       ca cert file   string            aliases   map object         token filename   string       address   string       namespace   string       ca cert file   string                          Example Usage     hcl provider  vault         skip child token must be explicitly set to true as HCP Terraform manages the token lifecycle   skip child token   true   address            var tfc vault dynamic credentials default address   namespace          var tfc vault dynamic credentials default namespace    auth login token file       filename   var tfc vault dynamic credentials default token filename        provider  vault         skip child token must be explicitly set to true as HCP Terraform manages the token lifecycle   skip child token   true   alias               ALIAS1    address            var tfc vault dynamic credentials aliases  ALIAS1   address   namespace          var tfc vault dynamic credentials aliases  ALIAS1   namespace    auth login token file       filename   var tfc vault dynamic credentials aliases  ALIAS1   token filename