terraform Define OPA policies This topic describes how to create and manage custom policies using the open policy agent OPA framework Refer to the following topics for instructions on using HashiCorp Sentinel policies Use the Rego policy language to define Open Policy Agent OPA policies for HCP Terraform page title Defining Policies Open Policy Agent HCP Terraform

Answer:
---
page_title:  Defining Policies - Open Policy Agent - HCP Terraform
description: Use the Rego policy language to define Open Policy Agent (OPA) policies for HCP Terraform.

---

# Define OPA policies

This topic describes how to create and manage custom policies using the open policy agent (OPA) framework. Refer to the following topics for instructions on using HashiCorp Sentinel policies:

[Define custom Sentinel policies](/terraform/cloud-docs/policy-enforcement/define-policies/custom-sentinel)
[Copy pre-written Sentinel policies](/terraform/cloud-docs/policy-enforcement/define-policies/prewritten-sentinel)

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

> **Hands-on:** Try the [Detect Infrastructure Drift and Enforce OPA Policies](/terraform/tutorials/cloud/drift-and-opa) tutorial.

## Overview

You can write OPA policies using the Rego policy language, which is the native query language for the OPA framework. Refer to the following topics in the [OPA documentation](https://www.openpolicyagent.org/docs/latest/policy-language/) for additional information:

[How Do I Write Rego Policies?](https://www.openpolicyagent.org/docs/v0.13.5/how-do-i-write-policies/)
[Rego Policy Playground](https://play.openpolicyagent.org/)

## OPA query

You must write a query to identify a specific policy rule within your Rego code. The query may evaluate code from multiple Rego files.

The result of each query must return an array, which HCP Terraform uses to determine whether the policy has passed or failed. If the array is empty, HCP Terraform reports that the policy has passed.

The query is typically a combination of the policy package name and rule name, such as `data.terraform.deny`.

## OPA input

HCP Terraform combines the output from the Terraform run and plan into a single JSON file and passes that file to OPA as input. Refer to the [OPA Overview documentation](https://www.openpolicyagent.org/docs/latest/#the-input-document) for more details about how OPA uses JSON input data.

The run data contains information like workspace details and the organization name. To access the properties from the Terraform plan data in your policies, use  `input.plan`. To access properties from the Terraform run, use  `input.run`.

The following example shows sample OPA input data.

```json
{
"plan": {
 "format_version": "1.1",
 "output_changes": {
 },
 "planned_values": {
  },
  "resource_changes": [
 ],
 "terraform_version": "1.2.7"
},

"run": {
  "organization": {
  "name": "hashicorp"
  },
  "workspace": {
  }
}
}
```

Use the [Retrieve JSON Execution Plan endpoint](/terraform/cloud-docs/api-docs/plans#retrieve-the-json-execution-plan) to retrieve Terraform plan output data for testing. Refer to [Terraform Run Data](#terraform-run-data) for the properties included in Terraform run output data.

## Example Policies

The following example policy parses a Terraform plan and checks whether it includes security group updates that allow ingress traffic from all CIDRs (`0.0.0.0/0`).

The OPA query for this example policy is `data.terraform.policies.public_ingress.deny`.

```rego
package terraform.policies.public_ingress

import input.plan as plan

deny[msg] {
  r := plan.resource_changes[_]
  r.type == "aws_security_group"
  r.change.after.ingress[_].cidr_blocks[_] == "0.0.0.0/0"
  msg := sprintf("%v has 0.0.0.0/0 as allowed ingress", [r.address])
}
```

The following example policy ensures that databases are no larger than 128 GB.

The OPA query for this policy is `data.terraform.policies.fws.database.fws_db_001.rule`.

```rego
package terraform.policies.fws.database.fws_db_001

import future.keywords.in
import input.plan as tfplan

actions := [
	["no-op"],
	["create"],
	["update"],
]

db_size := 128

resources := [resource_changes |
	resource_changes := tfplan.resource_changes[_]
	resource_changes.type == "fakewebservices_database"
	resource_changes.mode == "managed"
	resource_changes.change.actions in actions
]

violations := [resource |
	resource := resources[_]
	not resource.change.after.size == db_size
]

violators[address] {
	address := violations[_].address
}

rule[msg] {
	count(violations) != 0
  msg := sprintf(
    "%d %q severity resource violation(s) have been detected.",
		[count(violations), rego.metadata.rule().custom.severity]
	)
}
```

## Test policies

You can write tests for your policies by [mocking](https://www.openpolicyagent.org/docs/latest/policy-testing/#data-and-function-mocking) the input data the policies use during Terraform runs.

The following example policy called `block_auto_apply_runs` checks whether or not an HCP Terraform workspace has been configured to automatically apply a successful Terraform plan.

```rego
package terraform.tfc.block_auto_apply_runs

import input.run as run

deny[msg] {
	run.workspace.auto_apply != false
	msg := sprintf(
		"HCP Terraform workspace %s has been configured to automatically provision Terraform infrastructure. Change the workspace Apply Method settings to 'Manual Apply'",
		[run.workspace.name],
	)
}
```

The following test validates `block_auto_apply_runs`. The test is written in rego and uses the OPA [test format](https://www.openpolicyagent.org/docs/latest/policy-testing/#test-format) to check that the workspace [apply method](/terraform/cloud-docs/workspaces/settings#apply-method) is not configured to auto apply. You can run this test with the `opa test` CLI command. Refer to [Policy Testing](https://www.openpolicyagent.org/docs/latest/policy-testing/) in the OPA documentation for more details.

```rego
package terraform.tfc.block_auto_apply_runs

import future.keywords

test_run_workspace_auto_apply if {
	deny with input as {"run": {"workspace": {"auto_apply": true}}}
}
```

## Terraform run data

Each [Terraform run](/terraform/docs/glossary#run) outputs data describing the run settings and the associated workspace.

### Schema

The following code shows the schema for Terraform run data.

```
run
├── id (string)
├── created_at (string)
├── created_by (string)
├── message (string)
├── commit_sha (string)
├── is_destroy (boolean)
├── refresh (boolean)
├── refresh_only (boolean)
├── replace_addrs (array of strings)
├── speculative (boolean)
├── target_addrs (array of strings)
└── project
│    ├── id (string)
│    └── name (string)
├── variables (map of keys)
├── organization
│   └── name (string)
└── workspace
    ├── id (string)
    ├── name (string)
    ├── created_at (string)
    ├── description (string)
    ├── execution_mode (string)
    ├── auto_apply (bool)
    ├── tags (array of strings)
    ├── working_directory (string)
    └── vcs_repo (map of keys)
```

### Properties

The following sections contain details about each property in Terraform run data.

#### Run namespace

The following table contains the attributes for the `run` namespace.

| Properties Name |  Type  | Description |
|---------| ----------| ----------|
|  `id`   | String | The ID associated with the current Terraform run |
|  `created_at` | String | The time Terraform created the run. The timestamp follows the [standard timestamp format in RFC 3339](https://datatracker.ietf.org/doc/html/rfc3339). |
|  `created_by` | String | A string that specifies the user name of the HCP Terraform user for the specific run.|
|  `message` |  String | The message associated with the Terraform run. The default value is "Queued manually via the Terraform Enterprise API". |
|  `commit_sha` |  String |  The checksum hash (SHA) that identifies the commit |
|  `is_destroy` |  Boolean | Whether the plan is a destroy plan that destroys all provisioned resources |
|  `refresh` | Boolean |  Whether the state refreshed prior to the plan |
|   `refresh_only` |  Boolean | Whether the plan is in refresh-only mode. In refresh-only mode, Terraform ignores configuration changes and updates state with any changes made outside of Terraform. |
|  `replace_addrs` | An array of strings representing [resource addresses](/terraform/cli/state/resource-addressing) | The targets specified using the [`-replace`](/terraform/cli/commands/plan#replace-address) flag in the CLI or the `replace-addrs` property in the API. Undefined if there are no specified resource targets. |
|  `speculative` | Boolean | Whether the plan associated with the run is a [speculative plan](/terraform/cloud-docs/run/remote-operations#speculative-plans) only |
|  `target_addrs` |  An array of strings representing [resource addresses](/terraform/cli/state/resource-addressing). | The targets specified using the [`-target`](/terraform/cli/commands/plan#resource-targeting) flag in the CLI or the `target-addrs` property in the API. Undefined if there are no specified resource targets. |
|   `variables` |  A string-keyed map of values. | Provides the variables configured within the run. Each variable `name` maps to two properties: `category` and `sensitive`.  The `category` property is a string indicating the variable type, either "input" or "environment". The `sensitive` property is a boolean, indicating whether the variable is a [sensitive value](/terraform/cloud-docs/workspaces/variables/managing-variables#sensitive-values).  |

#### Project Namespace

The following table contains the properties for the `project` namespace.

| Property Name |  Type  | Description |
|---------- | ------------ | -----------|
| `id` | String | The ID associated with the Terraform project |
|  `name` |  String | The name of the project, which can only include letters, numbers, spaces, `-`, and `_`. |

#### Organization namespace

The `organization` namespace has one property called `name`. The `name` property is a string that specifies the name of the HCP Terraform organization for the run.

#### Workspace namespace

The following table contains the properties for the `workspace` namespace.

| Property Name |  Type  | Description |
|---------- | ------------ | -----------|
| `id` | String | The ID associated with the Terraform workspace |
|  `name` |  String | The name of the workspace, which can only include letters, numbers, `-`, and `_` |
|  `created_at` | String | The time of the workspace's creation. The timestamp follows the [standard timestamp format in RFC 3339](https://datatracker.ietf.org/doc/html/rfc3339). |
|  `description` | String | The description for the workspace. This value can be `null`. |
|  `auto_apply` | Boolean | The workspace's [auto-apply](/terraform/cloud-docs/workspaces/settings#apply-method) setting |
|  `tags` | Array of strings | The list of tag names for the workspace |
|  `working_directory` |  String | The configured [Terraform working directory](/terraform/cloud-docs/workspaces/settings#terraform-working-directory) of the workspace. This value can be `null`. |
|  `execution_mode` |  String | The configured Terraform execution mode of the workspace. The default value is `remote`. |
|  `vcs_repo` |  A string-keyed map to objects | Data associated with a VCS repository connected to the workspace. The map contains `identifier` (string), ` display_identifier` (string), `branch` (string), and  `ingress_submodules` (boolean). Refer to the HCP Terraform [Workspaces API documentation](/terraform/cloud-docs/api-docs/workspaces) for details about each property. This value can be `null`. |

## Next steps

- Group your policies into sets and apply them to your workspaces. Refer to [Create policy sets](/terraform/cloud-docs//policy-enforcement/create-sets) for additional information.
- View results and address Terraform runs that do not comply with your policies. Refer to [View results](/terraform/cloud-docs/policy-enforcement/view-results) for additional information.
- You can also view Sentinel policy results in JSON format. Refer to [View Sentinel JSON results]((/terraform/cloud-docs/policy-enforcement/view-json-results) for additional information.

page title   Defining Policies   Open Policy Agent   HCP Terraform description  Use the Rego policy language to define Open Policy Agent  OPA  policies for HCP Terraform          Define OPA policies   This topic describes how to create and manage custom policies using the open policy agent  OPA  framework  Refer to the following topics for instructions on using HashiCorp Sentinel policies    Define custom Sentinel policies   terraform cloud docs policy enforcement define policies custom sentinel   Copy pre written Sentinel policies   terraform cloud docs policy enforcement define policies prewritten sentinel        BEGIN  TFC only name pnp callout      include  tfc package callouts policies mdx       END  TFC only name pnp callout          Hands on    Try the  Detect Infrastructure Drift and Enforce OPA Policies   terraform tutorials cloud drift and opa  tutorial      Overview  You can write OPA policies using the Rego policy language  which is the native query language for the OPA framework  Refer to the following topics in the  OPA documentation  https   www openpolicyagent org docs latest policy language   for additional information    How Do I Write Rego Policies   https   www openpolicyagent org docs v0 13 5 how do i write policies    Rego Policy Playground  https   play openpolicyagent org        OPA query  You must write a query to identify a specific policy rule within your Rego code  The query may evaluate code from multiple Rego files   The result of each query must return an array  which HCP Terraform uses to determine whether the policy has passed or failed  If the array is empty  HCP Terraform reports that the policy has passed   The query is typically a combination of the policy package name and rule name  such as  data terraform deny       OPA input  HCP Terraform combines the output from the Terraform run and plan into a single JSON file and passes that file to OPA as input  Refer to the  OPA Overview documentation  https   www openpolicyagent org docs latest  the input document  for more details about how OPA uses JSON input data   The run data contains information like workspace details and the organization name  To access the properties from the Terraform plan data in your policies  use   input plan   To access properties from the Terraform run  use   input run    The following example shows sample OPA input data      json    plan       format version    1 1     output changes           planned values             resource changes           terraform version    1 2 7       run        organization        name    hashicorp          workspace                  Use the  Retrieve JSON Execution Plan endpoint   terraform cloud docs api docs plans retrieve the json execution plan  to retrieve Terraform plan output data for testing  Refer to  Terraform Run Data   terraform run data  for the properties included in Terraform run output data      Example Policies  The following example policy parses a Terraform plan and checks whether it includes security group updates that allow ingress traffic from all CIDRs   0 0 0 0 0     The OPA query for this example policy is  data terraform policies public ingress deny       rego package terraform policies public ingress  import input plan as plan  deny msg      r    plan resource changes      r type     aws security group    r change after ingress    cidr blocks        0 0 0 0 0    msg    sprintf   v has 0 0 0 0 0 as allowed ingress    r address          The following example policy ensures that databases are no larger than 128 GB   The OPA query for this policy is  data terraform policies fws database fws db 001 rule       rego package terraform policies fws database fws db 001  import future keywords in import input plan as tfplan  actions         no op       create       update       db size    128  resources     resource changes    resource changes    tfplan resource changes     resource changes type     fakewebservices database   resource changes mode     managed   resource changes change actions in actions    violations     resource    resource    resources     not resource change after size    db size    violators address     address    violations    address    rule msg     count violations     0   msg    sprintf        d  q severity resource violation s  have been detected       count violations   rego metadata rule   custom severity               Test policies  You can write tests for your policies by  mocking  https   www openpolicyagent org docs latest policy testing  data and function mocking  the input data the policies use during Terraform runs   The following example policy called  block auto apply runs  checks whether or not an HCP Terraform workspace has been configured to automatically apply a successful Terraform plan      rego package terraform tfc block auto apply runs  import input run as run  deny msg     run workspace auto apply    false  msg    sprintf     HCP Terraform workspace  s has been configured to automatically provision Terraform infrastructure  Change the workspace Apply Method settings to  Manual Apply       run workspace name             The following test validates  block auto apply runs   The test is written in rego and uses the OPA  test format  https   www openpolicyagent org docs latest policy testing  test format  to check that the workspace  apply method   terraform cloud docs workspaces settings apply method  is not configured to auto apply  You can run this test with the  opa test  CLI command  Refer to  Policy Testing  https   www openpolicyagent org docs latest policy testing   in the OPA documentation for more details      rego package terraform tfc block auto apply runs  import future keywords  test run workspace auto apply if    deny with input as   run     workspace     auto apply   true              Terraform run data  Each  Terraform run   terraform docs glossary run  outputs data describing the run settings and the associated workspace       Schema  The following code shows the schema for Terraform run data       run     id  string      created at  string      created by  string      message  string      commit sha  string      is destroy  boolean      refresh  boolean      refresh only  boolean      replace addrs  array of strings      speculative  boolean      target addrs  array of strings      project          id  string           name  string      variables  map of keys      organization         name  string      workspace         id  string          name  string          created at  string          description  string          execution mode  string          auto apply  bool          tags  array of strings          working directory  string          vcs repo  map of keys           Properties  The following sections contain details about each property in Terraform run data        Run namespace  The following table contains the attributes for the  run  namespace     Properties Name    Type    Description                                           id      String   The ID associated with the current Terraform run       created at    String   The time Terraform created the run  The timestamp follows the  standard timestamp format in RFC 3339  https   datatracker ietf org doc html rfc3339         created by    String   A string that specifies the user name of the HCP Terraform user for the specific run       message     String   The message associated with the Terraform run  The default value is  Queued manually via the Terraform Enterprise API         commit sha     String    The checksum hash  SHA  that identifies the commit       is destroy     Boolean   Whether the plan is a destroy plan that destroys all provisioned resources       refresh    Boolean    Whether the state refreshed prior to the plan        refresh only     Boolean   Whether the plan is in refresh only mode  In refresh only mode  Terraform ignores configuration changes and updates state with any changes made outside of Terraform        replace addrs    An array of strings representing  resource addresses   terraform cli state resource addressing    The targets specified using the    replace    terraform cli commands plan replace address  flag in the CLI or the  replace addrs  property in the API  Undefined if there are no specified resource targets        speculative    Boolean   Whether the plan associated with the run is a  speculative plan   terraform cloud docs run remote operations speculative plans  only       target addrs     An array of strings representing  resource addresses   terraform cli state resource addressing     The targets specified using the    target    terraform cli commands plan resource targeting  flag in the CLI or the  target addrs  property in the API  Undefined if there are no specified resource targets         variables     A string keyed map of values    Provides the variables configured within the run  Each variable  name  maps to two properties   category  and  sensitive    The  category  property is a string indicating the variable type  either  input  or  environment   The  sensitive  property is a boolean  indicating whether the variable is a  sensitive value   terraform cloud docs workspaces variables managing variables sensitive values            Project Namespace  The following table contains the properties for the  project  namespace     Property Name    Type    Description                                                id    String   The ID associated with the Terraform project       name     String   The name of the project  which can only include letters  numbers  spaces       and               Organization namespace  The  organization  namespace has one property called  name   The  name  property is a string that specifies the name of the HCP Terraform organization for the run        Workspace namespace  The following table contains the properties for the  workspace  namespace     Property Name    Type    Description                                                id    String   The ID associated with the Terraform workspace       name     String   The name of the workspace  which can only include letters  numbers       and           created at    String   The time of the workspace s creation  The timestamp follows the  standard timestamp format in RFC 3339  https   datatracker ietf org doc html rfc3339         description    String   The description for the workspace  This value can be  null         auto apply    Boolean   The workspace s  auto apply   terraform cloud docs workspaces settings apply method  setting       tags    Array of strings   The list of tag names for the workspace       working directory     String   The configured  Terraform working directory   terraform cloud docs workspaces settings terraform working directory  of the workspace  This value can be  null         execution mode     String   The configured Terraform execution mode of the workspace  The default value is  remote         vcs repo     A string keyed map to objects   Data associated with a VCS repository connected to the workspace  The map contains  identifier   string     display identifier   string    branch   string   and   ingress submodules   boolean   Refer to the HCP Terraform  Workspaces API documentation   terraform cloud docs api docs workspaces  for details about each property  This value can be  null         Next steps    Group your policies into sets and apply them to your workspaces  Refer to  Create policy sets   terraform cloud docs  policy enforcement create sets  for additional information    View results and address Terraform runs that do not comply with your policies  Refer to  View results   terraform cloud docs policy enforcement view results  for additional information    You can also view Sentinel policy results in JSON format  Refer to  View Sentinel JSON results    terraform cloud docs policy enforcement view json results  for additional information


terraform This topic describes how to run Sentinel policies created and maintained by HashiCorp For instructions about how to create your own custom Sentinel policies refer to Define custom Sentinel policies terraform cloud docs policy enforcement define policies custom sentinel Learn how to download and install pre written Sentinel policies created and maintained by HashiCorp Run pre written Sentinel policies page title Run pre written Sentinel policies Overview

Answer:
---
page_title: Run pre-written Sentinel policies
description: Learn how to download and install pre-written Sentinel policies created and maintained by HashiCorp.
---

# Run pre-written Sentinel policies

This topic describes how to run Sentinel policies created and maintained by HashiCorp. For instructions about how to create your own custom Sentinel policies, refer to [Define custom Sentinel policies](/terraform/cloud-docs/policy-enforcement/define-policies/custom-sentinel).

## Overview

Pre-written Sentinel policy libraries streamline your compliance processes and enhance security across your infrastructure. HashiCorp's ready-to-use policies can help you enforce best practices and security standards across your AWS environment.

Refer to the following resources for details about working with pre-written policies and information about the Sentinel language and framework:

- [Sentinel documentation](/sentinel/docs).
- The `README.md` documentation included with each of the policy libraries.

Complete the following steps to implement pre-written Sentinel policies in your workspaces:

1. Obtain the policies you want to implement. Download policies directly into your repository or create a fork of the HashiCorp repositories. Alternatively, you can add the Terraform module to your configuration, which acquires the policies and connects them to your workspaces in a single step.
1. Connect policies to your workspace. After you download policies or fork policy repositories, you must connect them to your HCP Terraform or Terraform Enterprise workspaces.

## Requirements

You must use one of the following Terraform applications:

- HCP Terraform
- Terraform Enterprise v202406-1 or newer

### Permissions

To create new policy sets and policies, your HCP Terraform or Terraform Enterprise user account must either be a member of the owners team or have the **Manage Policies** organization-level permissions enabled. Refer to the following topics for additional information:

- [Organization owners](/terraform/cloud-docs/users-teams-organizations/permissions#organization-owners)
- [Manage policies](/terraform/cloud-docs/users-teams-organizations/permissions#manage-policies)

### Version control system

You must have a GitHub account connected to HCP Terraform or Terraform Enterprise to manually connect policy sets to your workspaces. Refer to [Connecting VCS Providers](/terraform/cloud-docs/vcs) for instructions.

## Obtain policies

You can use the policy libraries created and maintained by HashiCorp. The libraries are stored in the following GitHub repositories:

- [policy-library-cis-aws-efs-terraform](https://github.com/hashicorp/policy-library-cis-aws-efs-terraform)
- [policy-library-cis-aws-rds-terraform](https://github.com/hashicorp/policy-library-cis-aws-rds-terraform)
- [policy-library-cis-aws-vpc-terraform](https://github.com/hashicorp/policy-library-cis-aws-vpc-terraform)
- [policy-library-cis-aws-iam-terraform](https://github.com/hashicorp/policy-library-cis-aws-iam-terraform)
- [policy-library-cis-aws-s3-terraform](https://github.com/hashicorp/policy-library-cis-aws-s3-terraform)
- [policv-library-cis-aws-cloudtrail-terraform](https://github.com/hashicorp/policy-library-cis-aws-cloudtrail-terraform)
- [policy-library-cis-aws-kms-terraform](https://github.com/hashicorp/policy-library-cis-aws-kms-terraform)
- [policy-library-cis-aws-ec2-terraform](https://github.com/hashicorp/policy-library-cis-aws-ec2-terraform)

Use one of the following methods to obtain pre-written policies:

- **Download policies from the registry**: Use this method if you want to assemble custom policy sets without customizing policies.
- **Fork the HashiCorp policy GitHub repository**: Use this method if you intend to customize the policies.
- **Add the Terraform module to your configuration**: Use this method to implement specific versions of the policies as-is. This method also connects the policies to workspaces in the Terraform configuration file instead of connecting them as a separate step.

### Download policies from the registry

Complete the following steps to download policies from the registry and apply them directly to your workspaces.

1. Browse the policy libraries available in the [Terraform registry](https://registry.terraform.io/browse/policies).
1. Click on a policy library and click **Choose policies**.
1. Select the policies you want to implement. The registry generates code in the **USAGE INSTRUCTIONS** box.
1. Click **Copy Code Snippet** to copy the code to your clipboard.
1. Create a GitHub repository to store the policies and the policy set configuration file.
1. Create a file called `sentinel.hcl` in the repository.
1. Paste the code from your clipboard into `sentinel.hcl` and commit your changes.
1. Complete the instructions for [connecting the policies to your workspace](#connect-policies-to-your-workspace).

### Create a fork of the policy libraries

Create a fork of the repository containing the policies you want to implement. Refer to the [GitHub documentation](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/fork-a-repo) for instructions on how to create a fork.

HashiCorp Sentinel policy libraries include a `sentinel.hcl` file. The file defines an example policy set using the policies included in the library. Modify the file to customize your policy set. Refer to [Sentinel Policy Set VCS Repositories](/terraform/cloud-docs/policy-enforcement/manage-policy-sets/sentinel-vcs) for additional information.

After forking the repository, complete the instructions for [connecting the policies to your workspace](#connect-policies-to-your-workspace).

### Add the Terraform module to your configuration
This method enables you to connect the policies to workspaces in the Terraform configuration file. As a result, you can skip the instructions described in [Connect policies to your workspaces](#connect-policies-to-your-workspaces).

1. Go to the [module in the Terraform registry](https://registry.terraform.io/modules/hashicorp/CIS-Policy-Set/AWS/latest) and copy the code generated in the **Provision Instructions** tile.
1. Add the `module` block to your Terraform configuration and define the following arguments:
   - `source`: Specify the path to the module you downloaded.
   - `tfe_organization`: Specify the name of your organization on Terraform Enterprise or HCP Terraform.
   - `policy_set_workspace_names`: Specify a list of workspace names that you want to apply the policies to.

   The following example configuration applies invokes the module for `target_workspace_1`:

   ```hcl
   module "cis_v1-2-0_policies" {
      source = "../prewritten-policy"
      name                             = "cis-1-2-0"
      tfe_organization                 = "<your-tfe-org>"
      policy_set_workspace_names       = ["target_workspace_1"]
   }
   ```

1. Run `terraform plan` to view the plan.
1. Run `terraform apply` to apply the changes. After running the command, Terraform will evaluate Sentinel policies for each following run of the workspaces you specified.

## Connect policies to your workspace

Skip this step if you [added the Terraform module](#add-the-terraform-module-to-your-configuration) to your configuration. When you use the module, the `policy_set_workspace_names` argument instructs Terraform to connect the policies to the HCP Terraform workspaces specified in the configuration.

1. Log into your organization and click **Settings** in the sidebar.
1. Click **Policy Sets** and click **Connect a new policy set**.
1. Click the **Version control provider (VCS)** tile.
1. Enable the **Sentinel** option as the policy framework.
1. Specify a name and description for the set.
1. Configure any additional options for the policy set and click **Next**.
1. Choose the GitHub connection type, then choose the repository you created in [Set up a repository for the policies](#set-up-a-repository-for-the-policies).
1. If the `sentinel.hcl` policy set file is stored in a subfolder, specify the path to the file in the **Policies path** field. The default is the root directory.
1. If you want to apply updated policy sets to the workspace from a specific branch, specify the name in the **VCS branch** field. The default is the default branch configured for the repository.
1. Click **Next** and specify any additional parameters you want to pass to the Sentinel runtime and click **Connect policy set** to finish applying the policies to the workspace.

Run a plan in the workspace to trigger the connected policies. Refer to [Start a Terraform run](/terraform/cloud-docs/run/remote-operations#starting-runs) for additional information.

## Next steps

- Group your policies into sets and apply them to your workspaces. Refer to [Create policy sets](/terraform/cloud-docs//policy-enforcement/create-sets) for additional information.
- View results and address Terraform runs that do not comply with your policies. Refer to [View results](/terraform/cloud-docs/policy-enforcement/view-results) for additional information.
- You can also view Sentinel policy results in JSON format. Refer to [View Sentinel JSON results](/terraform/cloud-docs/policy-enforcement/view-json-results) for additional information.

page title  Run pre written Sentinel policies description  Learn how to download and install pre written Sentinel policies created and maintained by HashiCorp         Run pre written Sentinel policies   This topic describes how to run Sentinel policies created and maintained by HashiCorp  For instructions about how to create your own custom Sentinel policies  refer to  Define custom Sentinel policies   terraform cloud docs policy enforcement define policies custom sentinel       Overview  Pre written Sentinel policy libraries streamline your compliance processes and enhance security across your infrastructure  HashiCorp s ready to use policies can help you enforce best practices and security standards across your AWS environment   Refer to the following resources for details about working with pre written policies and information about the Sentinel language and framework       Sentinel documentation   sentinel docs     The  README md  documentation included with each of the policy libraries   Complete the following steps to implement pre written Sentinel policies in your workspaces   1  Obtain the policies you want to implement  Download policies directly into your repository or create a fork of the HashiCorp repositories  Alternatively  you can add the Terraform module to your configuration  which acquires the policies and connects them to your workspaces in a single step  1  Connect policies to your workspace  After you download policies or fork policy repositories  you must connect them to your HCP Terraform or Terraform Enterprise workspaces             Requirements  You must use one of the following Terraform applications     HCP Terraform   Terraform Enterprise v202406 1 or newer      Permissions  To create new policy sets and policies  your HCP Terraform or Terraform Enterprise user account must either be a member of the owners team or have the   Manage Policies   organization level permissions enabled  Refer to the following topics for additional information      Organization owners   terraform cloud docs users teams organizations permissions organization owners     Manage policies   terraform cloud docs users teams organizations permissions manage policies       Version control system  You must have a GitHub account connected to HCP Terraform or Terraform Enterprise to manually connect policy sets to your workspaces  Refer to  Connecting VCS Providers   terraform cloud docs vcs  for instructions      Obtain policies  You can use the policy libraries created and maintained by HashiCorp  The libraries are stored in the following GitHub repositories      policy library cis aws efs terraform  https   github com hashicorp policy library cis aws efs terraform     policy library cis aws rds terraform  https   github com hashicorp policy library cis aws rds terraform     policy library cis aws vpc terraform  https   github com hashicorp policy library cis aws vpc terraform     policy library cis aws iam terraform  https   github com hashicorp policy library cis aws iam terraform     policy library cis aws s3 terraform  https   github com hashicorp policy library cis aws s3 terraform     policv library cis aws cloudtrail terraform  https   github com hashicorp policy library cis aws cloudtrail terraform     policy library cis aws kms terraform  https   github com hashicorp policy library cis aws kms terraform     policy library cis aws ec2 terraform  https   github com hashicorp policy library cis aws ec2 terraform   Use one of the following methods to obtain pre written policies       Download policies from the registry    Use this method if you want to assemble custom policy sets without customizing policies        Fork the HashiCorp policy GitHub repository    Use this method if you intend to customize the policies       Add the Terraform module to your configuration    Use this method to implement specific versions of the policies as is  This method also connects the policies to workspaces in the Terraform configuration file instead of connecting them as a separate step        Download policies from the registry  Complete the following steps to download policies from the registry and apply them directly to your workspaces    1  Browse the policy libraries available in the  Terraform registry  https   registry terraform io browse policies   1  Click on a policy library and click   Choose policies    1  Select the policies you want to implement  The registry generates code in the   USAGE INSTRUCTIONS   box  1  Click   Copy Code Snippet   to copy the code to your clipboard   1  Create a GitHub repository to store the policies and the policy set configuration file  1  Create a file called  sentinel hcl  in the repository   1  Paste the code from your clipboard into  sentinel hcl  and commit your changes   1  Complete the instructions for  connecting the policies to your workspace   connect policies to your workspace        Create a fork of the policy libraries   Create a fork of the repository containing the policies you want to implement  Refer to the  GitHub documentation  https   docs github com en pull requests collaborating with pull requests working with forks fork a repo  for instructions on how to create a fork    HashiCorp Sentinel policy libraries include a  sentinel hcl  file  The file defines an example policy set using the policies included in the library  Modify the file to customize your policy set  Refer to  Sentinel Policy Set VCS Repositories   terraform cloud docs policy enforcement manage policy sets sentinel vcs  for additional information   After forking the repository  complete the instructions for  connecting the policies to your workspace   connect policies to your workspace         Add the Terraform module to your configuration  This method enables you to connect the policies to workspaces in the Terraform configuration file  As a result  you can skip the instructions described in  Connect policies to your workspaces   connect policies to your workspaces       1  Go to the  module in the Terraform registry  https   registry terraform io modules hashicorp CIS Policy Set AWS latest  and copy the code generated in the   Provision Instructions   tile    1  Add the  module  block to your Terraform configuration and define the following arguments         source   Specify the path to the module you downloaded        tfe organization   Specify the name of your organization on Terraform Enterprise or HCP Terraform        policy set workspace names   Specify a list of workspace names that you want to apply the policies to       The following example configuration applies invokes the module for  target workspace 1          hcl    module  cis v1 2 0 policies          source       prewritten policy        name                                cis 1 2 0        tfe organization                     your tfe org         policy set workspace names           target workspace 1                1  Run  terraform plan  to view the plan  1  Run  terraform apply  to apply the changes  After running the command  Terraform will evaluate Sentinel policies for each following run of the workspaces you specified      Connect policies to your workspace  Skip this step if you  added the Terraform module   add the terraform module to your configuration  to your configuration  When you use the module  the  policy set workspace names  argument instructs Terraform to connect the policies to the HCP Terraform workspaces specified in the configuration    1  Log into your organization and click   Settings   in the sidebar   1  Click   Policy Sets   and click   Connect a new policy set    1  Click the   Version control provider  VCS    tile  1  Enable the   Sentinel   option as the policy framework  1  Specify a name and description for the set  1  Configure any additional options for the policy set and click   Next    1  Choose the GitHub connection type  then choose the repository you created in  Set up a repository for the policies   set up a repository for the policies    1  If the  sentinel hcl  policy set file is stored in a subfolder  specify the path to the file in the   Policies path   field  The default is the root directory  1  If you want to apply updated policy sets to the workspace from a specific branch  specify the name in the   VCS branch   field  The default is the default branch configured for the repository  1  Click   Next   and specify any additional parameters you want to pass to the Sentinel runtime and click   Connect policy set   to finish applying the policies to the workspace    Run a plan in the workspace to trigger the connected policies  Refer to  Start a Terraform run   terraform cloud docs run remote operations starting runs  for additional information      Next steps    Group your policies into sets and apply them to your workspaces  Refer to  Create policy sets   terraform cloud docs  policy enforcement create sets  for additional information    View results and address Terraform runs that do not comply with your policies  Refer to  View results   terraform cloud docs policy enforcement view results  for additional information    You can also view Sentinel policy results in JSON format  Refer to  View Sentinel JSON results   terraform cloud docs policy enforcement view json results  for additional information


terraform page title CLI driven Runs Runs HCP Terraform Trigger runs from your terminal using the Terraform CLI Learn the required private terraform cloud docs registry speculative plan terraform cloud docs run remote operations speculative plans configuration for remote CLI runs

Answer:
---
page_title: CLI-driven Runs - Runs - HCP Terraform
description: >-
  Trigger runs from your terminal using the Terraform CLI. Learn the required
  configuration for remote CLI runs.
---

[private]: /terraform/cloud-docs/registry

[speculative plan]: /terraform/cloud-docs/run/remote-operations#speculative-plans

[tfe-provider]: https://registry.terraform.io/providers/hashicorp/tfe/latest/docs

# The CLI-driven Run Workflow

> **Hands-on:** Try the [Log in to HCP Terraform from the CLI](/terraform/tutorials/0-13/cloud-login) tutorial.

HCP Terraform has three workflows for managing Terraform runs.

- The [UI/VCS-driven run workflow](/terraform/cloud-docs/run/ui), which is the primary mode of operation.
- The [API-driven run workflow](/terraform/cloud-docs/run/api), which is more flexible but requires you to create some tooling.
- The CLI-driven run workflow described below, which uses Terraform's standard CLI tools to execute runs in HCP Terraform.

## Summary

The [CLI integration](/terraform/cli/cloud) brings HCP Terraform's collaboration features into the familiar Terraform CLI workflow. It offers the best of both worlds to developers who are already comfortable with using the Terraform CLI, and it can work with existing CI/CD pipelines.

You can start runs with the standard `terraform plan` and `terraform apply` commands and then watch the progress of the run from your terminal. These runs execute remotely in HCP Terraform, use variables from the appropriate workspace, enforce any applicable [Sentinel or OPA policies](/terraform/cloud-docs/policy-enforcement), and can access HCP Terraform's [private registry][private] and remote state inputs.

HCP Terraform offers a few types of CLI-driven runs, to support different stages of your workflow:

- `terraform plan` starts a [speculative plan][] in an HCP Terraform workspace, using configuration files from a local directory. You can quickly check the results of edits (including compliance with Sentinel policies) without needing to copy sensitive variables to your local machine.

  Speculative plans work with all workspaces, and can co-exist with the [VCS-driven workflow](/terraform/cloud-docs/run/ui).

- `terraform apply` starts a standard plan and apply in an HCP Terraform workspace, using configuration files from a local directory.

  Remote `terraform apply` is for workspaces without a linked VCS repository. It replaces the VCS-driven workflow with a more traditional CLI workflow.

- `terraform plan -out <FILE>` and `terraform apply <FILE>` perform a two-part [saved plan run](/terraform/cloud-docs/run/modes-and-options/#saved-plans) in an HCP Terraform workspace, using configuration files from a local directory. The first command performs and saves the plan, and the second command applies it. You can use `terraform show <FILE>` to inspect a saved plan.

    Like remote `terraform apply`, remote saved plans are for workspaces without a linked VCS repository.

    Saved plans require at least Terraform CLI v1.6.0.

To supplement these remote operations, you can also use the optional [Terraform Enterprise Provider][tfe-provider], which interacts with the HCP Terraform-supported resources. This provider is useful for editing variables and workspace settings through the Terraform CLI.

## Configuration

To enable the CLI-driven workflow, you must:

1. Run `terraform login` to authenticate with HCP Terraform. Alternatively, you can manually configure credentials in the CLI config file or through environment variables. Refer to [CLI Configuration](/terraform/cli/config/config-file#environment-variable-credentials) for details.

1. Add the `cloud` block to your Terraform configuration. You can define its arguments directly in your configuration file or supply them through environment variables, which can be useful for [non-interactive workflows](#non-interactive-workflows). Refer to [Using HCP Terraform](/terraform/cli/cloud) for configuration details.

   The following example shows how to map CLI workspaces to HCP Terraform workspaces with a specific tag.

   ```
   terraform {
     cloud {
       organization = "my-org"
       workspaces {
         tags = ["networking"]
       }
     }
   }
   ```

   -> **Note:** The `cloud` block is available in Terraform v1.1 and later. Previous versions can use the [`remote` backend](/terraform/language/settings/backends/remote) to configure the CLI workflow and migrate state.

1. Run `terraform init`.

   ```
   $ terraform init

   Initializing HCP Terraform...

   Initializing provider plugins...
   - Reusing previous version of hashicorp/random from the dependency lock file
   - Using previously-installed hashicorp/random v3.0.1

   HCP Terraform has been successfully initialized!

   You may now begin working with HCP Terraform. Try running "terraform plan"
   to see any changes that are required for your infrastructure.

   If you ever set or change modules or Terraform Settings,
   run "terraform init" again to reinitialize your working directory.
   ```

### Implicit Workspace Creation

If you configure the `cloud` block to use a workspace that doesn't yet exist in your organization, HCP Terraform will create a new workspace with that name when you run `terraform init`. The output of `terraform init` will inform you when this happens.

Automatically created workspaces might not be immediately ready to use, so use HCP Terraform's UI to check a workspace's settings and data before performing any runs. In particular, note that:

- No Terraform variables or environment variables are created by default, unless your organization has configured one or more [global variable sets](/terraform/cloud-docs/workspaces/variables#scope). HCP Terraform will use `*.auto.tfvars` files if they are present, but you will usually still need to set some workspace-specific variables.
- The execution mode defaults to "Remote," so that runs occur within HCP Terraform's infrastructure instead of on your workstation.
- New workspaces are not automatically connected to a VCS repository and do not have a working directory specified.
- A new workspace's Terraform version defaults to the most recent release of Terraform at the time the workspace was created.

### Implicit Project Creation

If you configure the [`workspaces` block](/terraform/cli/cloud/settings#workspaces) to use a [project](/terraform/cli/cloud/settings#project) that does not yet exist in your organization, HCP Terraform will attempt to create a new project with that name when you run `terraform init` and notify you in the command output.

If you specify both the `project` argument and [`TF_CLOUD_PROJECT`](/terraform/cli/cloud/settings#tf_cloud_project) environment variable, the `project` argument takes precedence.

## Variables in CLI-Driven Runs

Remote runs in HCP Terraform use:

- Run-specific variables set through the command line or in your local environment. Terraform can use shell environment variables prefixed with `TF_VAR_` as input variables for the run, but you must still set all required environment variables, like provider credentials, inside the workspace.
- Workspace-specific Terraform and environment variables set in the workspace.
- Any variable sets applied globally, on the project containing the workspace, or on the workspace itself.
- Terraform variables from any `*.auto.tfvars` files included in the configuration.

Refer to [Variables](/terraform/cloud-docs/workspaces/variables) for more details about variable types, variable scopes, variable precedence, and how to set run-specific variables through the command line.

## Remote Working Directories

If you manage your Terraform configurations in self-contained repositories, the remote working directory always has the same content as the local working directory.

If you use a combined repository and [specify a working directory on workspaces](/terraform/cloud-docs/workspaces/settings#terraform-working-directory), you can run Terraform from either the real working directory or from the root of the combined configuration directory. In both cases, Terraform will upload the entire combined configuration directory.

## Excluding Files from Upload

-> **Version note:** `.terraformignore` support was added in Terraform 0.12.11.

CLI-driven runs upload an archive of your configuration directory
to HCP Terraform. If the directory contains files you want to exclude from upload,
you can do so by defining a [`.terraformignore` file in your configuration directory](/terraform/cli/cloud/settings).

## Remote Speculative Plans

You can run speculative plans in any workspace where you have [permission to queue plans](/terraform/cloud-docs/users-teams-organizations/permissions). Speculative plans use the configuration code from the local working directory, but will use variable values from the specified workspace.

To run a [speculative plan][] on your configuration, use the `terraform plan` command. The plan will run in HCP Terraform, and the logs will stream back to the command line along with a URL to view the plan in the HCP Terraform UI.

```
$ terraform plan

Running plan in HCP Terraform. Output will stream here. Pressing Ctrl-C
will stop streaming the logs, but will not stop the plan running remotely.

Preparing the remote plan...

To view this run in a browser, visit:
https://app.terraform.io/app/hashicorp-learn/docs-workspace/runs/run-cfh2trDbvMU2Rkf1

Waiting for the plan to start...

[...]

Plan: 1 to add, 0 to change, 0 to destroy.

Changes to Outputs:
  + pet_name = (known after apply)
```

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

## Remote Applies

In workspaces that are not connected to a VCS repository, users with [permission to apply runs](/terraform/cloud-docs/users-teams-organizations/permissions#general-workspace-permissions) can use the CLI to trigger remote applies. Remote applies use the configuration code from the local working directory, but use the variable values from the specified workspace.

~> **Note:** You cannot run remote applies in workspaces that are linked to a VCS repository, since the repository serves as the workspace’s source of truth. To apply changes in a VCS-linked workspace, merge your changes to the designated branch.

When you are ready to apply configuration changes, use the `terraform apply` command. HCP Terraform will plan your changes, and the command line will prompt you for approval before applying them.

```
$ terraform apply

Running apply in HCP Terraform. Output will stream here. Pressing Ctrl-C
will cancel the remote apply if it's still pending. If the apply started it
will stop streaming the logs, but will not stop the apply running remotely.

Preparing the remote apply...

To view this run in a browser, visit:
https://app.terraform.io/app/hashicorp-learn/docs-workspace/runs/run-Rcc12TkNW1PDa7GH

Waiting for the plan to start...

[...]

Plan: 1 to add, 0 to change, 0 to destroy.

Changes to Outputs:
  + pet_name = (known after apply)

Do you want to perform these actions in workspace "docs-workspace"?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

[...]

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

### Non-Interactive Workflows

> **Hands On:** Try the [Deploy Infrastructure with HCP Terraform and CircleCI](/terraform/tutorials/automation/circle-ci) tutorial.

External systems cannot run the traditional apply workflow because Terraform requires console input from the user to approve plans. We recommend using the [API-driven Run Workflow](/terraform/cloud-docs/run/api) for non-interactive workflows when possible.

If you prefer to use the CLI in a non-interactive environment, we recommend first running a [speculative plan](/terraform/cloud-docs/run/remote-operations#speculative-plans) to preview the changes Terraform will make to your infrastructure. Then, use one of the following approaches with the `-auto-approve` flag based on the [execution mode](/terraform/cloud-docs/workspaces/settings#execution-mode) of your workspace. The [`-auto-approve`](/terraform/cli/commands/apply#auto-approve) flag skips prompting you to approve the plan.

- **Local Execution:**  Save the approved speculative plan and then run `terraform apply -auto-approve` with the saved plan.
- **Remote Execution:** HCP Terraform does not support uploading saved plans for remote execution, so we recommend running `terraform apply -auto-approve` immediately after approving the speculative plan to prevent the plan from becoming stale.

  !> **Warning:** Remote execution with non-interactive workflows requires auto-approved deployments. Minimize the risk of unpredictable infrastructure changes and configuration drift by making sure that no one can change your infrastructure outside of your automated build pipeline.

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

## Remote Saved Plans

-> **Version note:** Saved plans require at least Terraform CLI v1.6.0.

In workspaces that support `terraform apply`, you also have the option of performing the plan and apply as separate steps, using the standard variations of the relevant Terraform commands:

- `terraform plan -out <FILE>` performs and saves a plan.
- `terraform apply <FILE>` applies a previously saved plan.
- `terraform show <FILE>` (and `terraform show -json <FILE>`) inspect a plan you previously saved.

Saved plan runs are halfway between [speculative plans](#remote-speculative-plans) and standard [plan and apply runs](#remote-applies). They allow you to:

- Perform cheap exploratory plans while retaining the option of applying a specific plan you are satisfied with.
- Perform other tasks in your terminal between the plan and apply stages.
- Perform the plan and apply operations on separate machines (as is common in continuous integration workflows).

Saved plans become _stale_ once the state Terraform planned them against is no longer valid (usually due to someone applying a different run). In HCP Terraform, stale saved plan runs are automatically detected and discarded. When examining a remote saved plan, the `terraform show` command (without the `-json` option) informs you if a plan has been discarded or is otherwise unable to be applied.

### File Contents and Permissions

You can only apply remote saved plans in the same remote HCP Terraform workspace that performed the plan. Additionally, you can not apply locally executed saved plans in a remote workspace.

In order to abide by HCP Terraform's permissions model, remote saved plans do not use the same local file format as locally executed saved plans. Instead, remote saved plans are a thin reference to a remote run, and the Terraform CLI relies on authenticated network requests to inspect and apply remote plans. This helps avoid the accidental exposure of credentials or other sensitive information.

The `terraform show -json` command requires [workspace admin permissions](/terraform/cloud-docs/users-teams-organizations/permissions#workspace-admins) to inspect a remote saved plan; this is because the [machine-readable JSON plan format](/terraform/internals/json-format) contains unredacted sensitive information (alongside redaction hints for use by systems that consume the format). The human-readable version of `terraform show` only requires the read runs permission, because it uses pre-redacted information.

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

## Policy Enforcement

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

Policies are rules that HCP Terraform enforces on Terraform runs. You can use two policy-as-code frameworks to define fine-grained, logic-based policies: Sentinel and Open Policy Agent (OPA).

If the specified workspace uses policies, HCP Terraform runs those policies against all speculative plans and remote applies in that workspace. Failed policies can pause or prevent an apply, depending on the enforcement level. Refer to [Policy Enforcement](/terraform/cloud-docs/policy-enforcement) for details.

For Sentinel, the Terraform CLI prints policy results for CLI-driven runs. CLI support for policy results is not available for OPA.

The following example shows Sentinel policy output in the terminal.

```
$ terraform apply

[...]

Plan: 1 to add, 0 to change, 1 to destroy.

------------------------------------------------------------------------

Organization policy check:

Sentinel Result: false

Sentinel evaluated to false because one or more Sentinel policies evaluated
to false. This false was not due to an undefined value or runtime error.

1 policies evaluated.
## Policy 1: my-policy.sentinel (soft-mandatory)

Result: false

FALSE - my-policy.sentinel:1:1 - Rule "main"

Do you want to override the soft failed policy check?
  Only 'override' will be accepted to override.

  Enter a value: override
```

## Options for Plans and Applies

[Run Modes and Options](/terraform/cloud-docs/run/modes-and-options) contains more details about the various options available for plans and applies when you use the CLI-driven workflow.

## Networking/Connection Issues

Sometimes during a CLI-driven run, errors relating to network connectivity issues arise. Examples of these kinds of errors include:

* `Client.Timeout exceeded while awaiting headers`
* `context deadline exceeded`
* `TLS handshake timeout`

Sometimes there are network problems beyond our control. If you have network errors, verify your network connection is operational. Then, check the following common configuration settings:

* Determine if any firewall software on your system blocks the `terraform` command and explicitly approve it.
* Verify that you have a valid DNS server IP address.
* Remove any expired TLS certificates for your system.

page title  CLI driven Runs   Runs   HCP Terraform description       Trigger runs from your terminal using the Terraform CLI  Learn the required   configuration for remote CLI runs        private    terraform cloud docs registry   speculative plan    terraform cloud docs run remote operations speculative plans   tfe provider   https   registry terraform io providers hashicorp tfe latest docs    The CLI driven Run Workflow      Hands on    Try the  Log in to HCP Terraform from the CLI   terraform tutorials 0 13 cloud login  tutorial   HCP Terraform has three workflows for managing Terraform runs     The  UI VCS driven run workflow   terraform cloud docs run ui   which is the primary mode of operation    The  API driven run workflow   terraform cloud docs run api   which is more flexible but requires you to create some tooling    The CLI driven run workflow described below  which uses Terraform s standard CLI tools to execute runs in HCP Terraform      Summary  The  CLI integration   terraform cli cloud  brings HCP Terraform s collaboration features into the familiar Terraform CLI workflow  It offers the best of both worlds to developers who are already comfortable with using the Terraform CLI  and it can work with existing CI CD pipelines   You can start runs with the standard  terraform plan  and  terraform apply  commands and then watch the progress of the run from your terminal  These runs execute remotely in HCP Terraform  use variables from the appropriate workspace  enforce any applicable  Sentinel or OPA policies   terraform cloud docs policy enforcement   and can access HCP Terraform s  private registry  private  and remote state inputs   HCP Terraform offers a few types of CLI driven runs  to support different stages of your workflow      terraform plan  starts a  speculative plan    in an HCP Terraform workspace  using configuration files from a local directory  You can quickly check the results of edits  including compliance with Sentinel policies  without needing to copy sensitive variables to your local machine     Speculative plans work with all workspaces  and can co exist with the  VCS driven workflow   terraform cloud docs run ui       terraform apply  starts a standard plan and apply in an HCP Terraform workspace  using configuration files from a local directory     Remote  terraform apply  is for workspaces without a linked VCS repository  It replaces the VCS driven workflow with a more traditional CLI workflow      terraform plan  out  FILE   and  terraform apply  FILE   perform a two part  saved plan run   terraform cloud docs run modes and options  saved plans  in an HCP Terraform workspace  using configuration files from a local directory  The first command performs and saves the plan  and the second command applies it  You can use  terraform show  FILE   to inspect a saved plan       Like remote  terraform apply   remote saved plans are for workspaces without a linked VCS repository       Saved plans require at least Terraform CLI v1 6 0   To supplement these remote operations  you can also use the optional  Terraform Enterprise Provider  tfe provider   which interacts with the HCP Terraform supported resources  This provider is useful for editing variables and workspace settings through the Terraform CLI      Configuration  To enable the CLI driven workflow  you must   1  Run  terraform login  to authenticate with HCP Terraform  Alternatively  you can manually configure credentials in the CLI config file or through environment variables  Refer to  CLI Configuration   terraform cli config config file environment variable credentials  for details   1  Add the  cloud  block to your Terraform configuration  You can define its arguments directly in your configuration file or supply them through environment variables  which can be useful for  non interactive workflows   non interactive workflows   Refer to  Using HCP Terraform   terraform cli cloud  for configuration details      The following example shows how to map CLI workspaces to HCP Terraform workspaces with a specific tag             terraform        cloud          organization    my org         workspaces            tags     networking                                        Note    The  cloud  block is available in Terraform v1 1 and later  Previous versions can use the   remote  backend   terraform language settings backends remote  to configure the CLI workflow and migrate state   1  Run  terraform init                terraform init     Initializing HCP Terraform        Initializing provider plugins         Reusing previous version of hashicorp random from the dependency lock file      Using previously installed hashicorp random v3 0 1     HCP Terraform has been successfully initialized      You may now begin working with HCP Terraform  Try running  terraform plan     to see any changes that are required for your infrastructure      If you ever set or change modules or Terraform Settings     run  terraform init  again to reinitialize your working directory              Implicit Workspace Creation  If you configure the  cloud  block to use a workspace that doesn t yet exist in your organization  HCP Terraform will create a new workspace with that name when you run  terraform init   The output of  terraform init  will inform you when this happens   Automatically created workspaces might not be immediately ready to use  so use HCP Terraform s UI to check a workspace s settings and data before performing any runs  In particular  note that     No Terraform variables or environment variables are created by default  unless your organization has configured one or more  global variable sets   terraform cloud docs workspaces variables scope   HCP Terraform will use    auto tfvars  files if they are present  but you will usually still need to set some workspace specific variables    The execution mode defaults to  Remote   so that runs occur within HCP Terraform s infrastructure instead of on your workstation    New workspaces are not automatically connected to a VCS repository and do not have a working directory specified    A new workspace s Terraform version defaults to the most recent release of Terraform at the time the workspace was created       Implicit Project Creation  If you configure the   workspaces  block   terraform cli cloud settings workspaces  to use a  project   terraform cli cloud settings project  that does not yet exist in your organization  HCP Terraform will attempt to create a new project with that name when you run  terraform init  and notify you in the command output   If you specify both the  project  argument and   TF CLOUD PROJECT    terraform cli cloud settings tf cloud project  environment variable  the  project  argument takes precedence      Variables in CLI Driven Runs  Remote runs in HCP Terraform use     Run specific variables set through the command line or in your local environment  Terraform can use shell environment variables prefixed with  TF VAR   as input variables for the run  but you must still set all required environment variables  like provider credentials  inside the workspace    Workspace specific Terraform and environment variables set in the workspace    Any variable sets applied globally  on the project containing the workspace  or on the workspace itself    Terraform variables from any    auto tfvars  files included in the configuration   Refer to  Variables   terraform cloud docs workspaces variables  for more details about variable types  variable scopes  variable precedence  and how to set run specific variables through the command line      Remote Working Directories  If you manage your Terraform configurations in self contained repositories  the remote working directory always has the same content as the local working directory   If you use a combined repository and  specify a working directory on workspaces   terraform cloud docs workspaces settings terraform working directory   you can run Terraform from either the real working directory or from the root of the combined configuration directory  In both cases  Terraform will upload the entire combined configuration directory      Excluding Files from Upload       Version note      terraformignore  support was added in Terraform 0 12 11   CLI driven runs upload an archive of your configuration directory to HCP Terraform  If the directory contains files you want to exclude from upload  you can do so by defining a    terraformignore  file in your configuration directory   terraform cli cloud settings       Remote Speculative Plans  You can run speculative plans in any workspace where you have  permission to queue plans   terraform cloud docs users teams organizations permissions   Speculative plans use the configuration code from the local working directory  but will use variable values from the specified workspace   To run a  speculative plan    on your configuration  use the  terraform plan  command  The plan will run in HCP Terraform  and the logs will stream back to the command line along with a URL to view the plan in the HCP Terraform UI         terraform plan  Running plan in HCP Terraform  Output will stream here  Pressing Ctrl C will stop streaming the logs  but will not stop the plan running remotely   Preparing the remote plan     To view this run in a browser  visit  https   app terraform io app hashicorp learn docs workspace runs run cfh2trDbvMU2Rkf1  Waiting for the plan to start            Plan  1 to add  0 to change  0 to destroy   Changes to Outputs      pet name    known after apply        permissions citation    intentionally unused   keep for maintainers      Remote Applies  In workspaces that are not connected to a VCS repository  users with  permission to apply runs   terraform cloud docs users teams organizations permissions general workspace permissions  can use the CLI to trigger remote applies  Remote applies use the configuration code from the local working directory  but use the variable values from the specified workspace        Note    You cannot run remote applies in workspaces that are linked to a VCS repository  since the repository serves as the workspace s source of truth  To apply changes in a VCS linked workspace  merge your changes to the designated branch   When you are ready to apply configuration changes  use the  terraform apply  command  HCP Terraform will plan your changes  and the command line will prompt you for approval before applying them         terraform apply  Running apply in HCP Terraform  Output will stream here  Pressing Ctrl C will cancel the remote apply if it s still pending  If the apply started it will stop streaming the logs  but will not stop the apply running remotely   Preparing the remote apply     To view this run in a browser  visit  https   app terraform io app hashicorp learn docs workspace runs run Rcc12TkNW1PDa7GH  Waiting for the plan to start            Plan  1 to add  0 to change  0 to destroy   Changes to Outputs      pet name    known after apply   Do you want to perform these actions in workspace  docs workspace     Terraform will perform the actions described above    Only  yes  will be accepted to approve     Enter a value  yes         Apply complete  Resources  1 added  0 changed  0 destroyed           Non Interactive Workflows      Hands On    Try the  Deploy Infrastructure with HCP Terraform and CircleCI   terraform tutorials automation circle ci  tutorial   External systems cannot run the traditional apply workflow because Terraform requires console input from the user to approve plans  We recommend using the  API driven Run Workflow   terraform cloud docs run api  for non interactive workflows when possible   If you prefer to use the CLI in a non interactive environment  we recommend first running a  speculative plan   terraform cloud docs run remote operations speculative plans  to preview the changes Terraform will make to your infrastructure  Then  use one of the following approaches with the   auto approve  flag based on the  execution mode   terraform cloud docs workspaces settings execution mode  of your workspace  The    auto approve    terraform cli commands apply auto approve  flag skips prompting you to approve the plan       Local Execution     Save the approved speculative plan and then run  terraform apply  auto approve  with the saved plan      Remote Execution    HCP Terraform does not support uploading saved plans for remote execution  so we recommend running  terraform apply  auto approve  immediately after approving the speculative plan to prevent the plan from becoming stale          Warning    Remote execution with non interactive workflows requires auto approved deployments  Minimize the risk of unpredictable infrastructure changes and configuration drift by making sure that no one can change your infrastructure outside of your automated build pipeline    permissions citation    intentionally unused   keep for maintainers     Remote Saved Plans       Version note    Saved plans require at least Terraform CLI v1 6 0   In workspaces that support  terraform apply   you also have the option of performing the plan and apply as separate steps  using the standard variations of the relevant Terraform commands      terraform plan  out  FILE   performs and saves a plan     terraform apply  FILE   applies a previously saved plan     terraform show  FILE    and  terraform show  json  FILE    inspect a plan you previously saved   Saved plan runs are halfway between  speculative plans   remote speculative plans  and standard  plan and apply runs   remote applies   They allow you to     Perform cheap exploratory plans while retaining the option of applying a specific plan you are satisfied with    Perform other tasks in your terminal between the plan and apply stages    Perform the plan and apply operations on separate machines  as is common in continuous integration workflows    Saved plans become  stale  once the state Terraform planned them against is no longer valid  usually due to someone applying a different run   In HCP Terraform  stale saved plan runs are automatically detected and discarded  When examining a remote saved plan  the  terraform show  command  without the   json  option  informs you if a plan has been discarded or is otherwise unable to be applied       File Contents and Permissions  You can only apply remote saved plans in the same remote HCP Terraform workspace that performed the plan  Additionally  you can not apply locally executed saved plans in a remote workspace   In order to abide by HCP Terraform s permissions model  remote saved plans do not use the same local file format as locally executed saved plans  Instead  remote saved plans are a thin reference to a remote run  and the Terraform CLI relies on authenticated network requests to inspect and apply remote plans  This helps avoid the accidental exposure of credentials or other sensitive information   The  terraform show  json  command requires  workspace admin permissions   terraform cloud docs users teams organizations permissions workspace admins  to inspect a remote saved plan  this is because the  machine readable JSON plan format   terraform internals json format  contains unredacted sensitive information  alongside redaction hints for use by systems that consume the format   The human readable version of  terraform show  only requires the read runs permission  because it uses pre redacted information    permissions citation    intentionally unused   keep for maintainers     Policy Enforcement       BEGIN  TFC only name pnp callout      include  tfc package callouts policies mdx       END  TFC only name pnp callout      Policies are rules that HCP Terraform enforces on Terraform runs  You can use two policy as code frameworks to define fine grained  logic based policies  Sentinel and Open Policy Agent  OPA    If the specified workspace uses policies  HCP Terraform runs those policies against all speculative plans and remote applies in that workspace  Failed policies can pause or prevent an apply  depending on the enforcement level  Refer to  Policy Enforcement   terraform cloud docs policy enforcement  for details   For Sentinel  the Terraform CLI prints policy results for CLI driven runs  CLI support for policy results is not available for OPA   The following example shows Sentinel policy output in the terminal         terraform apply         Plan  1 to add  0 to change  1 to destroy                                                                             Organization policy check   Sentinel Result  false  Sentinel evaluated to false because one or more Sentinel policies evaluated to false  This false was not due to an undefined value or runtime error   1 policies evaluated     Policy 1  my policy sentinel  soft mandatory   Result  false  FALSE   my policy sentinel 1 1   Rule  main   Do you want to override the soft failed policy check    Only  override  will be accepted to override     Enter a value  override         Options for Plans and Applies   Run Modes and Options   terraform cloud docs run modes and options  contains more details about the various options available for plans and applies when you use the CLI driven workflow      Networking Connection Issues  Sometimes during a CLI driven run  errors relating to network connectivity issues arise  Examples of these kinds of errors include      Client Timeout exceeded while awaiting headers     context deadline exceeded     TLS handshake timeout   Sometimes there are network problems beyond our control  If you have network errors  verify your network connection is operational  Then  check the following common configuration settings     Determine if any firewall software on your system blocks the  terraform  command and explicitly approve it    Verify that you have a valid DNS server IP address    Remove any expired TLS certificates for your system


terraform HCP Terraform is designed as an execution platform for Terraform and most of its features are based around its ability to perform Terraform runs in a fleet of disposable worker VMs This page describes some features of the run environment for Terraform runs managed by HCP Terraform page title HCP Terraform s Run Environment Runs HCP Terraform Learn about worker virtual machines network access concurrency for run HCP Terraform s Run Environment queueing state access authentication and environment variables

Answer:
---
page_title: HCP Terraform's Run Environment - Runs - HCP Terraform
description: >-
  Learn about worker virtual machines, network access, concurrency for run
  queueing, state access authentication, and environment variables.
---

# HCP Terraform's Run Environment

HCP Terraform is designed as an execution platform for Terraform, and most of its features are based around its ability to perform Terraform runs in a fleet of disposable worker VMs. This page describes some features of the run environment for Terraform runs managed by HCP Terraform.

## The Terraform Worker VMs

HCP Terraform performs Terraform runs in single-use Linux virtual machines, running on an x86_64 architecture.

The operating system and other software installed on the worker VMs is an internal implementation detail of HCP Terraform. It is not part of a stable public interface, and is subject to change at any time.

Before Terraform is executed, the worker VM's shell environment is populated with environment variables from the workspace, the selected version of Terraform is installed, and the run's Terraform configuration version is made available.

Changes made to the worker during a run are not persisted to subsequent runs, since the VM is destroyed after the run is completed. Notably, this requires some additional care when installing additional software with a `local-exec` provisioner; see [Installing Additional Tools](/terraform/cloud-docs/run/install-software#installing-additional-tools) for more details.

> **Hands-on:** Try the [Upgrade Terraform Version in HCP Terraform](/terraform/tutorials/cloud/cloud-versions) tutorial.

## Network Access to VCS and Infrastructure Providers

In order to perform Terraform runs, HCP Terraform needs network access to all of the resources being managed by Terraform.

If you are using the SaaS version of HCP Terraform, this means your VCS provider and any private infrastructure providers you manage with Terraform (including VMware vSphere, OpenStack, other private clouds, and more) _must be internet accessible._

Terraform Enterprise instances must have network connectivity to any connected VCS providers or managed infrastructure providers.

## Concurrency and Run Queuing

HCP Terraform uses multiple concurrent worker VMs, which take jobs from a global queue of runs that are ready for processing. (This includes confirmed applies, and plans that have just become the current run on their workspace.)

If the global queue has more runs than the workers can handle at once, some of them must wait until a worker becomes available. When the queue is backed up, HCP Terraform gives different priorities to different kinds of runs:

- Applies that will make changes to infrastructure have the highest priority.
- Normal plans have the next highest priority.
- Speculative plans have the lowest priority.

HCP Terraform can also delay some runs in order to make performance more consistent across organizations. If an organization requests a large number of runs at once, HCP Terraform queues some of them immediately, and delays the rest until some of the initial batch have finished; this allows every organization to continue performing runs even during periods of especially heavy load.

## State Access and Authentication

[CLI config file]: /terraform/cli/config/config-file

[cloud]: /terraform/cli/cloud

HCP Terraform stores state for its workspaces.

When you trigger runs via the [CLI workflow](/terraform/cloud-docs/run/cli), Terraform reads from and writes to HCP Terraform's stored state. HCP Terraform uses [the `cloud` block][cloud] for runs, overriding any existing [backend](/terraform/language/settings/backends/configuration) in the configuration.

-> **Note:** The `cloud` block is available in Terraform v1.1 and later. Previous versions can use the [`remote` backend](/terraform/language/settings/backends/remote) to configure the CLI workflow and migrate state.

### Autogenerated API Token

Instead of using existing user credentials, HCP Terraform generates a unique per-run API token and provides it to the Terraform worker in the [CLI config file][]. When you run Terraform on the command line against a workspace configured for remote operations, you must have [the `cloud` block][cloud] in your configuration and have a user or team API token with the appropriate permissions specified in your [CLI config file][]. However, the run itself occurs within one of HCP Terraform's worker VMs and uses the per-run token for state access.

The per-run token can read and write state data for the workspace associated with the run, can download modules from the [private registry](/terraform/cloud-docs/registry), and may be granted access to read state from other workspaces in the organization. (Refer to [cross-workspace state access](/terraform/cloud-docs/workspaces/state#accessing-state-from-other-workspaces) for more details.) Per-run tokens cannot make any other calls to the HCP Terraform API and are not considered to be user, team, or organization tokens. They become invalid after the run is completed.

### User Token

HCP Terraform uses the user token to access a workspace's state when you:

- Run Terraform on the command line against a workspace that is _not_ configured for remote operations. The user must have permission to read and write state versions for the workspace.

- Run Terraform's state manipulation commands against an HCP Terraform workspace. The user must have permission to read and write state versions for the workspace.

Refer to [Permissions](/terraform/cloud-docs/users-teams-organizations/permissions#workspace-permissions) for more details about workspace permissions.

### Provider Authentication

Runs in HCP Terraform typically require some form of credentials to authenticate with infrastructure providers. Credentials can be provided statically through Environment or Terraform [variables](/terraform/cloud-docs/workspaces/variables), or can be generated on a per-run basis through [dynamic credentials](/terraform/cloud-docs/workspaces/dynamic-provider-credentials) for certain providers. Below are pros and cons to each approach.

#### Static Credentials

##### Pros

- Simple to setup
- Broad support across providers

##### Cons

- Requires regular manual rotation for enhanced security posture
- Large blast radius if a credential is exposed and needs to be revoked

#### Dynamic Credentials

##### Pros

- Eliminates the need for manual rotation of credentials on HCP Terraform
- HCP Terraform metadata - including the run's project, workspace, and run-phase - is encoded into every token to allow for granular permission scoping on the target cloud platform
- Credentials are short-lived, which reduces blast radius of potential credential exposure

##### Cons

- More complicated initial setup compared to using static credentials
- Not supported for all providers

The full list of supported providers and setup instructions can be found in the [dynamic credentials](/terraform/cloud-docs/workspaces/dynamic-provider-credentials) documentation.

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

### Environment Variables

HCP Terraform automatically injects the following environment variables for each run:

| Variable Name                              | Description                                                                                | Example                         |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------- |
| `TFC_RUN_ID`                               | A unique identifier for this run.                                                                                | `run-CKuwsxMGgMd4W7Ui`          |
| `TFC_WORKSPACE_NAME`                       | The name of the workspace used in this run.                                                                                | `prod-load-balancers`           |
| `TFC_WORKSPACE_SLUG`                       | The full slug of the configuration used in this run. This consists of the organization name and workspace name, joined with a slash. | `acme-corp/prod-load-balancers` |
| `TFC_CONFIGURATION_VERSION_GIT_BRANCH`     | The name of the branch that the associated Terraform configuration version was ingressed from.                                       | `main`                          |
| `TFC_CONFIGURATION_VERSION_GIT_COMMIT_SHA` | The full commit hash of the commit that the associated Terraform configuration version was ingressed from.                           | `abcd1234...`                   |
| `TFC_CONFIGURATION_VERSION_GIT_TAG`        | The name of the tag that the associated Terraform configuration version was ingressed from.                                          | `v0.1.0`                        |
| `TFC_PROJECT_NAME`                         | The name of the project used in this run.                                                                                | `proj-name`                     |

They are also available as Terraform input variables by defining a variable with the same name. For example:

```terraform
variable "TFC_RUN_ID" {}
```

page title  HCP Terraform s Run Environment   Runs   HCP Terraform description       Learn about worker virtual machines  network access  concurrency for run   queueing  state access authentication  and environment variables         HCP Terraform s Run Environment  HCP Terraform is designed as an execution platform for Terraform  and most of its features are based around its ability to perform Terraform runs in a fleet of disposable worker VMs  This page describes some features of the run environment for Terraform runs managed by HCP Terraform      The Terraform Worker VMs  HCP Terraform performs Terraform runs in single use Linux virtual machines  running on an x86 64 architecture   The operating system and other software installed on the worker VMs is an internal implementation detail of HCP Terraform  It is not part of a stable public interface  and is subject to change at any time   Before Terraform is executed  the worker VM s shell environment is populated with environment variables from the workspace  the selected version of Terraform is installed  and the run s Terraform configuration version is made available   Changes made to the worker during a run are not persisted to subsequent runs  since the VM is destroyed after the run is completed  Notably  this requires some additional care when installing additional software with a  local exec  provisioner  see  Installing Additional Tools   terraform cloud docs run install software installing additional tools  for more details       Hands on    Try the  Upgrade Terraform Version in HCP Terraform   terraform tutorials cloud cloud versions  tutorial      Network Access to VCS and Infrastructure Providers  In order to perform Terraform runs  HCP Terraform needs network access to all of the resources being managed by Terraform   If you are using the SaaS version of HCP Terraform  this means your VCS provider and any private infrastructure providers you manage with Terraform  including VMware vSphere  OpenStack  other private clouds  and more   must be internet accessible    Terraform Enterprise instances must have network connectivity to any connected VCS providers or managed infrastructure providers      Concurrency and Run Queuing  HCP Terraform uses multiple concurrent worker VMs  which take jobs from a global queue of runs that are ready for processing   This includes confirmed applies  and plans that have just become the current run on their workspace    If the global queue has more runs than the workers can handle at once  some of them must wait until a worker becomes available  When the queue is backed up  HCP Terraform gives different priorities to different kinds of runs     Applies that will make changes to infrastructure have the highest priority    Normal plans have the next highest priority    Speculative plans have the lowest priority   HCP Terraform can also delay some runs in order to make performance more consistent across organizations  If an organization requests a large number of runs at once  HCP Terraform queues some of them immediately  and delays the rest until some of the initial batch have finished  this allows every organization to continue performing runs even during periods of especially heavy load      State Access and Authentication   CLI config file    terraform cli config config file   cloud    terraform cli cloud  HCP Terraform stores state for its workspaces   When you trigger runs via the  CLI workflow   terraform cloud docs run cli   Terraform reads from and writes to HCP Terraform s stored state  HCP Terraform uses  the  cloud  block  cloud  for runs  overriding any existing  backend   terraform language settings backends configuration  in the configuration        Note    The  cloud  block is available in Terraform v1 1 and later  Previous versions can use the   remote  backend   terraform language settings backends remote  to configure the CLI workflow and migrate state       Autogenerated API Token  Instead of using existing user credentials  HCP Terraform generates a unique per run API token and provides it to the Terraform worker in the  CLI config file     When you run Terraform on the command line against a workspace configured for remote operations  you must have  the  cloud  block  cloud  in your configuration and have a user or team API token with the appropriate permissions specified in your  CLI config file     However  the run itself occurs within one of HCP Terraform s worker VMs and uses the per run token for state access   The per run token can read and write state data for the workspace associated with the run  can download modules from the  private registry   terraform cloud docs registry   and may be granted access to read state from other workspaces in the organization   Refer to  cross workspace state access   terraform cloud docs workspaces state accessing state from other workspaces  for more details   Per run tokens cannot make any other calls to the HCP Terraform API and are not considered to be user  team  or organization tokens  They become invalid after the run is completed       User Token  HCP Terraform uses the user token to access a workspace s state when you     Run Terraform on the command line against a workspace that is  not  configured for remote operations  The user must have permission to read and write state versions for the workspace     Run Terraform s state manipulation commands against an HCP Terraform workspace  The user must have permission to read and write state versions for the workspace   Refer to  Permissions   terraform cloud docs users teams organizations permissions workspace permissions  for more details about workspace permissions       Provider Authentication  Runs in HCP Terraform typically require some form of credentials to authenticate with infrastructure providers  Credentials can be provided statically through Environment or Terraform  variables   terraform cloud docs workspaces variables   or can be generated on a per run basis through  dynamic credentials   terraform cloud docs workspaces dynamic provider credentials  for certain providers  Below are pros and cons to each approach        Static Credentials        Pros    Simple to setup   Broad support across providers        Cons    Requires regular manual rotation for enhanced security posture   Large blast radius if a credential is exposed and needs to be revoked       Dynamic Credentials        Pros    Eliminates the need for manual rotation of credentials on HCP Terraform   HCP Terraform metadata   including the run s project  workspace  and run phase   is encoded into every token to allow for granular permission scoping on the target cloud platform   Credentials are short lived  which reduces blast radius of potential credential exposure        Cons    More complicated initial setup compared to using static credentials   Not supported for all providers  The full list of supported providers and setup instructions can be found in the  dynamic credentials   terraform cloud docs workspaces dynamic provider credentials  documentation    permissions citation    intentionally unused   keep for maintainers      Environment Variables  HCP Terraform automatically injects the following environment variables for each run     Variable Name                                Description                                                                                Example                                                                                TFC RUN ID                                  A unique identifier for this run                                                                                run CKuwsxMGgMd4W7Ui                TFC WORKSPACE NAME                          The name of the workspace used in this run                                                                                prod load balancers                 TFC WORKSPACE SLUG                          The full slug of the configuration used in this run  This consists of the organization name and workspace name  joined with a slash     acme corp prod load balancers       TFC CONFIGURATION VERSION GIT BRANCH        The name of the branch that the associated Terraform configuration version was ingressed from                                           main                                TFC CONFIGURATION VERSION GIT COMMIT SHA    The full commit hash of the commit that the associated Terraform configuration version was ingressed from                               abcd1234                            TFC CONFIGURATION VERSION GIT TAG           The name of the tag that the associated Terraform configuration version was ingressed from                                              v0 1 0                              TFC PROJECT NAME                            The name of the project used in this run                                                                                proj name                         They are also available as Terraform input variables by defining a variable with the same name  For example      terraform variable  TFC RUN ID