questions
stringlengths
4
1.65k
answers
stringlengths
1.73k
353k
site
stringclasses
24 values
answers_cleaned
stringlengths
1.73k
353k
terraform HCP Vault Secrets Backed Dynamic Credentials with the GCP Provider your HCP Terraform runs page title HCP Vault Secrets Backed Dynamic Credentials with the GCP Provider Workspaces HCP Terraform Important If you are self hosting HCP Terraform agents terraform cloud docs agents ensure your agents use v1 16 0 terraform cloud docs agents changelog 1 16 0 10 02 2024 or above To use the latest dynamic credentials features upgrade your agents to the latest version terraform cloud docs agents changelog Use OpenID Connect and HCP Vault Secrets to get short term credentials for the GCP Terraform provider in
--- page_title: HCP Vault Secrets-Backed Dynamic Credentials with the GCP Provider - Workspaces - HCP Terraform description: >- Use OpenID Connect and HCP Vault Secrets to get short-term credentials for the GCP Terraform provider in your HCP Terraform runs. --- # HCP Vault Secrets-Backed Dynamic Credentials with the GCP Provider ~> **Important:** If you are self-hosting [HCP Terraform agents](/terraform/cloud-docs/agents), ensure your agents use [v1.16.0](/terraform/cloud-docs/agents/changelog#1-16-0-10-02-2024) or above. To use the latest dynamic credentials features, [upgrade your agents to the latest version](/terraform/cloud-docs/agents/changelog). You can use HCP Terraform’s native OpenID Connect integration with HCP to use [HCP Vault Secrets-backed dynamic credentials](/terraform/cloud-docs/workspaces/dynamic-provider-credentials/hcp-vault-secrets-backed) with the GCP provider in your HCP Terraform runs. Configuring the integration requires the following steps: 1. **[Configure HCP Provider Credentials](#configure-hcp-provider-credentials)**: Set up a trust configuration between HCP Vault Secrets and HCP Terraform, create HCP Vault Secrets roles and policies for your HCP Terraform workspaces, and add environment variables to those workspaces. 2. **[Configure HCP Vault Secrets](#configure-hcp-vault-secrets-gcp-secrets-engine)**: Set up your HCP project's GCP integration and dynamic secret. 3. **[Configure HCP Terraform](#configure-hcp-terraform)**: Add additional environment variables to the HCP Terraform workspaces where you want to use HCP Vault Secrets-backed dynamic credentials. 4. **[Configure Terraform Providers](#configure-terraform-providers)**: Configure your Terraform providers to work with HCP Vault Secrets-backed dynamic credentials. Once you complete this setup, HCP Terraform automatically authenticates with GCP via HCP Vault Secrets-generated credentials during the plan and apply phase of each run. The GCP provider's authentication is only valid for the length of the plan or apply phase. ## Configure HCP Provider Credentials You must first set up HCP dynamic provider credentials before you can use HCP Vault Secrets-backed dynamic credentials. This includes creating a service principal, configuring trust between HCP and HCP Terraform, and populating the required environment variables in your HCP Terraform workspace. [See the setup instructions for HCP dynamic provider credentials](/terraform/cloud-docs/workspaces/dynamic-provider-credentials/hcp-configuration). ## Configure HCP Vault Secrets GCP Secrets Engine Follow the instructions in the HCP Vault Secrets documentation for [setting up the GCP integration in your HCP project](/hcp/docs/vault-secrets/dynamic-secrets/gcp). ## Configure HCP Terraform Next, you need to set certain environment variables in your HCP Terraform workspace to authenticate HCP Terraform with GCP using HCP Vault Secrets-backed dynamic credentials. These variables are in addition to those you previously set while configuring [HCP provider credentials](#configure-hcp-provider-credentials). You can add these as workspace variables or as a [variable set](/terraform/cloud-docs/workspaces/variables/managing-variables#variable-sets). ### Required Common Environment Variables | Variable | Value | Notes | |---------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------| | `TFC_HVS_BACKED_GCP_AUTH`<br />`TFC_HVS_BACKED_GCP_AUTH[_TAG]`<br />_(Default variable not supported)_ | `true` | Requires **v1.16.0** or later if self-managing agents. Must be present and set to `true`, or HCP Terraform will not attempt to authenticate with GCP. | | `TFC_HVS_BACKED_GCP_RUN_SECRET_RESOURCE_NAME` | The name of the HCP Vault Secrets dynamic secret resource to read. | Requires **v1.16.0** or later if self-managing agents. Must be present. | ### Optional Common Environment Variables You may need to set these variables, depending on your use case. | Variable | Value | Notes | |-----------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------| | `TFC_HVS_BACKED_GCP_HCP_CONFIG`<br />`TFC_HVS_BACKED_GCP_HCP_CONFIG[_TAG]`<br />`TFC_DEFAULT_HVS_BACKED_GCP_HCP_CONFIG` | The name of the non-default HCP configuration for workspaces using [multiple HCP configurations](/terraform/cloud-docs/workspaces/dynamic-provider-credentials/specifying-multiple-configurations). | Requires **v1.16.0** or later if self-managing agents. Will fall back to using the default HCP Vault Secrets configuration if not provided. | | `TFC_HVS_BACKED_GCP_PLAN_SECRET_RESOURCE_NAME` | The name of the HCP Vault Secrets dynamic secret resource to read for the plan phase. | Requires **v1.16.0** or later if self-managing agents. Must be present. | | `TFC_HVS_BACKED_GCP_APPLY_SECRET_RESOURCE_NAME` | The name of the HCP Vault Secrets dynamic secret resource to read for the apply phase. | Requires **v1.16.0** or later if self-managing agents. Must be present. | ## Configure Terraform Providers The final step is to directly configure your GCP and HCP Vault Secrets providers. ### Configure the GCP Provider Ensure you pass values for the `project` and `region` arguments into the provider configuration block. Ensure you are not setting values or environment variables for `GOOGLE_CREDENTIALS` or `GOOGLE_APPLICATION_CREDENTIALS`. Otherwise, these values may interfere with dynamic provider credentials. ### Specifying Multiple Configurations ~> **Important:** If you are self-hosting [HCP Terraform agents](/terraform/cloud-docs/agents), ensure your agents use [v1.16.0](/terraform/cloud-docs/agents/changelog#1-16-0-10-02-2024) or above. To use the latest dynamic credentials features, [upgrade your agents to the latest version](/terraform/cloud-docs/agents/changelog). You can add additional variables to handle multiple distinct HCP Vault Secrets-backed GCP setups, enabling you to use multiple [provider aliases](/terraform/language/providers/configuration#alias-multiple-provider-configurations) within the same workspace. You can configure each set of credentials independently, or use default values by configuring the variables prefixed with `TFC_DEFAULT_`. For more details, see [Specifying Multiple Configurations](/terraform/cloud-docs/workspaces/dynamic-provider-credentials/specifying-multiple-configurations). #### Required Terraform Variable To use additional configurations, add the following code to your Terraform configuration. This lets HCP Terraform supply variable values that you can then use to map authentication and configuration details to the correct provider blocks. ```hcl variable "tfc_hvs_backed_gcp_dynamic_credentials" { description = "Object containing HCP Vault Secrets-backed GCP dynamic credentials configuration" type = object({ default = object({ credentials = string access_token = string }) aliases = map(object({ credentials = string access_token = string })) }) } ``` #### Example Usage ##### Access Token ```hcl provider "google" { access_token = var.tfc_hvs_backed_gcp_dynamic_credentials.default.access_token } provider "google" { alias = "ALIAS1" access_token = var.tfc_hvs_backed_gcp_dynamic_credentials.aliases["ALIAS1"].access_token } ``` ##### Credentials ```hcl provider "google" { credentials = var.tfc_hvs_backed_gcp_dynamic_credentials.default.credentials } provider "google" { alias = "ALIAS1" credentials = var.tfc_hvs_backed_gcp_dynamic_credentials.aliases["ALIAS1"].credentials } ```
terraform
page title HCP Vault Secrets Backed Dynamic Credentials with the GCP Provider Workspaces HCP Terraform description Use OpenID Connect and HCP Vault Secrets to get short term credentials for the GCP Terraform provider in your HCP Terraform runs HCP Vault Secrets Backed Dynamic Credentials with the GCP Provider Important If you are self hosting HCP Terraform agents terraform cloud docs agents ensure your agents use v1 16 0 terraform cloud docs agents changelog 1 16 0 10 02 2024 or above To use the latest dynamic credentials features upgrade your agents to the latest version terraform cloud docs agents changelog You can use HCP Terraform s native OpenID Connect integration with HCP to use HCP Vault Secrets backed dynamic credentials terraform cloud docs workspaces dynamic provider credentials hcp vault secrets backed with the GCP provider in your HCP Terraform runs Configuring the integration requires the following steps 1 Configure HCP Provider Credentials configure hcp provider credentials Set up a trust configuration between HCP Vault Secrets and HCP Terraform create HCP Vault Secrets roles and policies for your HCP Terraform workspaces and add environment variables to those workspaces 2 Configure HCP Vault Secrets configure hcp vault secrets gcp secrets engine Set up your HCP project s GCP integration and dynamic secret 3 Configure HCP Terraform configure hcp terraform Add additional environment variables to the HCP Terraform workspaces where you want to use HCP Vault Secrets backed dynamic credentials 4 Configure Terraform Providers configure terraform providers Configure your Terraform providers to work with HCP Vault Secrets backed dynamic credentials Once you complete this setup HCP Terraform automatically authenticates with GCP via HCP Vault Secrets generated credentials during the plan and apply phase of each run The GCP provider s authentication is only valid for the length of the plan or apply phase Configure HCP Provider Credentials You must first set up HCP dynamic provider credentials before you can use HCP Vault Secrets backed dynamic credentials This includes creating a service principal configuring trust between HCP and HCP Terraform and populating the required environment variables in your HCP Terraform workspace See the setup instructions for HCP dynamic provider credentials terraform cloud docs workspaces dynamic provider credentials hcp configuration Configure HCP Vault Secrets GCP Secrets Engine Follow the instructions in the HCP Vault Secrets documentation for setting up the GCP integration in your HCP project hcp docs vault secrets dynamic secrets gcp Configure HCP Terraform Next you need to set certain environment variables in your HCP Terraform workspace to authenticate HCP Terraform with GCP using HCP Vault Secrets backed dynamic credentials These variables are in addition to those you previously set while configuring HCP provider credentials configure hcp provider credentials You can add these as workspace variables or as a variable set terraform cloud docs workspaces variables managing variables variable sets Required Common Environment Variables Variable Value Notes TFC HVS BACKED GCP AUTH br TFC HVS BACKED GCP AUTH TAG br Default variable not supported true Requires v1 16 0 or later if self managing agents Must be present and set to true or HCP Terraform will not attempt to authenticate with GCP TFC HVS BACKED GCP RUN SECRET RESOURCE NAME The name of the HCP Vault Secrets dynamic secret resource to read Requires v1 16 0 or later if self managing agents Must be present Optional Common Environment Variables You may need to set these variables depending on your use case Variable Value Notes TFC HVS BACKED GCP HCP CONFIG br TFC HVS BACKED GCP HCP CONFIG TAG br TFC DEFAULT HVS BACKED GCP HCP CONFIG The name of the non default HCP configuration for workspaces using multiple HCP configurations terraform cloud docs workspaces dynamic provider credentials specifying multiple configurations Requires v1 16 0 or later if self managing agents Will fall back to using the default HCP Vault Secrets configuration if not provided TFC HVS BACKED GCP PLAN SECRET RESOURCE NAME The name of the HCP Vault Secrets dynamic secret resource to read for the plan phase Requires v1 16 0 or later if self managing agents Must be present TFC HVS BACKED GCP APPLY SECRET RESOURCE NAME The name of the HCP Vault Secrets dynamic secret resource to read for the apply phase Requires v1 16 0 or later if self managing agents Must be present Configure Terraform Providers The final step is to directly configure your GCP and HCP Vault Secrets providers Configure the GCP Provider Ensure you pass values for the project and region arguments into the provider configuration block Ensure you are not setting values or environment variables for GOOGLE CREDENTIALS or GOOGLE APPLICATION CREDENTIALS Otherwise these values may interfere with dynamic provider credentials Specifying Multiple Configurations Important If you are self hosting HCP Terraform agents terraform cloud docs agents ensure your agents use v1 16 0 terraform cloud docs agents changelog 1 16 0 10 02 2024 or above To use the latest dynamic credentials features upgrade your agents to the latest version terraform cloud docs agents changelog You can add additional variables to handle multiple distinct HCP Vault Secrets backed GCP setups enabling you to use multiple provider aliases terraform language providers configuration alias multiple provider configurations within the same workspace You can configure each set of credentials independently or use default values by configuring the variables prefixed with TFC DEFAULT For more details see Specifying Multiple Configurations terraform cloud docs workspaces dynamic provider credentials specifying multiple configurations Required Terraform Variable To use additional configurations add the following code to your Terraform configuration This lets HCP Terraform supply variable values that you can then use to map authentication and configuration details to the correct provider blocks hcl variable tfc hvs backed gcp dynamic credentials description Object containing HCP Vault Secrets backed GCP dynamic credentials configuration type object default object credentials string access token string aliases map object credentials string access token string Example Usage Access Token hcl provider google access token var tfc hvs backed gcp dynamic credentials default access token provider google alias ALIAS1 access token var tfc hvs backed gcp dynamic credentials aliases ALIAS1 access token Credentials hcl provider google credentials var tfc hvs backed gcp dynamic credentials default credentials provider google alias ALIAS1 credentials var tfc hvs backed gcp dynamic credentials aliases ALIAS1 credentials
terraform your HCP Terraform runs page title Vault Backed Dynamic Credentials with the AWS Provider Workspaces HCP Terraform Vault Backed Dynamic Credentials with the AWS Provider Use OpenID Connect and Vault to get short term credentials for the AWS Terraform provider in Important If you are self hosting HCP Terraform agents terraform cloud docs agents ensure your agents use v1 8 0 terraform cloud docs agents changelog 1 8 0 04 18 2023 or above To use the latest dynamic credentials features upgrade your agents to the latest version terraform cloud docs agents changelog
--- page_title: Vault-Backed Dynamic Credentials with the AWS Provider - Workspaces - HCP Terraform description: >- Use OpenID Connect and Vault to get short-term credentials for the AWS Terraform provider in your HCP Terraform runs. --- # Vault-Backed Dynamic Credentials with the AWS Provider ~> **Important:** If you are self-hosting [HCP Terraform agents](/terraform/cloud-docs/agents), ensure your agents use [v1.8.0](/terraform/cloud-docs/agents/changelog#1-8-0-04-18-2023) or above. To use the latest dynamic credentials features, [upgrade your agents to the latest version](/terraform/cloud-docs/agents/changelog). You can use HCP Terraform’s native OpenID Connect integration with Vault to use [Vault-backed dynamic credentials](/terraform/cloud-docs/workspaces/dynamic-provider-credentials/vault-backed) with the AWS provider in your HCP Terraform runs. Configuring the integration requires the following steps: 1. **[Configure Vault Dynamic Provider Credentials](#configure-vault-dynamic-provider-credentials)**: Set up a trust configuration between Vault and HCP Terraform, create Vault roles and policies for your HCP Terraform workspaces, and add environment variables to those workspaces. 2. **[Configure the Vault AWS Secrets Engine](#configure-vault-aws-secrets-engine)**: Set up the AWS secrets engine in your Vault instance. 3. **[Configure HCP Terraform](#configure-hcp-terraform)**: Add additional environment variables to the HCP Terraform workspaces where you want to use Vault-Backed Dynamic Credentials. 4. **[Configure Terraform Providers](#configure-terraform-providers)**: Configure your Terraform providers to work with Vault-backed dynamic credentials. Once you complete this setup, HCP Terraform automatically authenticates with AWS via Vault-generated credentials during the plan and apply phase of each run. The AWS provider's authentication is only valid for the length of the plan or apply phase. ## Configure Vault Dynamic Provider Credentials You must first set up Vault dynamic provider credentials before you can use Vault-backed dynamic credentials. This includes setting up the JWT auth backend in Vault, configuring trust between HCP Terraform and Vault, and populating the required environment variables in your HCP Terraform workspace. [See the setup instructions for Vault dynamic provider credentials](/terraform/cloud-docs/workspaces/dynamic-provider-credentials/vault-configuration). # Configure Vault AWS Secrets Engine Follow the instructions in the Vault documentation for [setting up the AWS secrets engine in your Vault instance](/vault/docs/secrets/aws). You can also do this configuration through Terraform. Refer to our [example Terraform configuration](https://github.com/hashicorp/terraform-dynamic-credentials-setup-examples/tree/main/vault-backed/aws). ~> **Important**: carefully consider the limitations and differences between each supported credential type in the AWS secrets engine. These limitations carry over to HCP Terraform’s usage of these credentials for authenticating the AWS provider. ## Configure HCP Terraform Next, you need to set certain environment variables in your HCP Terraform workspace to authenticate HCP Terraform with AWS using Vault-backed dynamic credentials. These variables are in addition to those you previously set while configuring [Vault dynamic provider credentials](#configure-vault-dynamic-provider-credentials). You can add these as workspace variables or as a [variable set](/terraform/cloud-docs/workspaces/variables/managing-variables#variable-sets). When you configure dynamic provider credentials with multiple provider configurations of the same type, use either a default variable or a tagged alias variable name for each provider configuration. Refer to [Specifying Multiple Configurations](#specifying-multiple-configurations) for more details. ### Common Environment Variables The below variables apply to all AWS auth types. #### Required Common Environment Variables | Variable | Value | Notes | |-------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `TFC_VAULT_BACKED_AWS_AUTH`<br />`TFC_VAULT_BACKED_AWS_AUTH[_TAG]`<br />_(Default variable not supported)_ | `true` | Requires **v1.8.0** or later if self-managing agents. Must be present and set to `true`, or HCP Terraform will not attempt to authenticate with AWS. | | `TFC_VAULT_BACKED_AWS_AUTH_TYPE`<br />`TFC_VAULT_BACKED_AWS_AUTH_TYPE[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_AWS_AUTH_TYPE` | Specifies the type of authentication to perform with AWS. Must be one of the following: `iam_user`, `assumed_role`, or `federation_token`. | Requires **v1.8.0** or later if self-managing agents. | | `TFC_VAULT_BACKED_AWS_RUN_VAULT_ROLE`<br />`TFC_VAULT_BACKED_AWS_RUN_VAULT_ROLE[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_AWS_RUN_VAULT_ROLE` | The role to use in Vault. | Requires **v1.8.0** or later if self-managing agents. Optional if `TFC_VAULT_BACKED_AWS_PLAN_VAULT_ROLE` and `TFC_VAULT_BACKED_AWS_APPLY_VAULT_ROLE` are both provided. These variables are described [below](#optional-common-environment-variables). | #### Optional Common Environment Variables You may need to set these variables, depending on your use case. | Variable | Value | Notes | |-------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------| | `TFC_VAULT_BACKED_AWS_MOUNT_PATH`<br />`TFC_VAULT_BACKED_AWS_MOUNT_PATH[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_AWS_MOUNT_PATH` | The mount path of the AWS secrets engine in Vault. | Requires **v1.8.0** or later if self-managing agents. Defaults to `aws`. | | `TFC_VAULT_BACKED_AWS_PLAN_VAULT_ROLE`<br />`TFC_VAULT_BACKED_AWS_PLAN_VAULT_ROLE[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_AWS_PLAN_VAULT_ROLE` | The Vault role to use the plan phase of a run. | Requires **v1.8.0** or later if self-managing agents. Will fall back to the value of `TFC_VAULT_BACKED_AWS_RUN_VAULT_ROLE` if not provided. | | `TFC_VAULT_BACKED_AWS_APPLY_VAULT_ROLE`<br />`TFC_VAULT_BACKED_AWS_APPLY_VAULT_ROLE[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_AWS_APPLY_VAULT_ROLE` | The Vault role to use for the apply phase of a run. | Requires **v1.8.0** or later if self-managing agents. Will fall back to the value of `TFC_VAULT_BACKED_AWS_RUN_VAULT_ROLE` if not provided. | | `TFC_VAULT_BACKED_AWS_SLEEP_SECONDS`<br />`TFC_VAULT_BACKED_AWS_SLEEP_SECONDS[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_AWS_SLEEP_SECONDS` | The amount of time to wait, in seconds, after obtaining temporary credentials from Vault. e.g., `30` for 30 seconds. Must be 1500 seconds (25 minutes) or less. | Requires **v1.12.0** or later if self-managing agents. Can be used to mitigate eventual consistency issues in AWS when using the `iam_user` auth type. | | `TFC_VAULT_BACKED_AWS_VAULT_CONFIG`<br />`TFC_VAULT_BACKED_AWS_VAULT_CONFIG[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_AWS_VAULT_CONFIG` | The name of the non-default Vault configuration for workspaces using [multiple Vault configurations](/terraform/cloud-docs/workspaces/dynamic-provider-credentials/specifying-multiple-configurations). | Requires **v1.12.0** or later if self-managing agents. Will fall back to using the default Vault configuration if not provided. | ### Assumed Role Specific Environment Variables These environment variables are only valid if the `TFC_VAULT_BACKED_AWS_AUTH_TYPE` is `assumed_role`. #### Required Assumed Role Specific Environment Variables | Variable | Value | Notes | |-------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `TFC_VAULT_BACKED_AWS_RUN_ROLE_ARN`<br />`TFC_VAULT_BACKED_AWS_RUN_ROLE_ARN[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_AWS_RUN_ROLE_ARN` | The ARN of the role to assume in AWS. | Requires **v1.8.0** or later if self-managing agents. Optional if `TFC_VAULT_BACKED_AWS_PLAN_ROLE_ARN` and `TFC_VAULT_BACKED_AWS_APPLY_ROLE_ARN` are both provided. These variables are described [below](#optional-assume-role-specific-environment-variables). | #### Optional Assumed Role Specific Environment Variables You may need to set these variables, depending on your use case. | Variable | Value | Notes | |-------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------| | `TFC_VAULT_BACKED_AWS_PLAN_ROLE_ARN`<br />`TFC_VAULT_BACKED_AWS_PLAN_ROLE_ARN[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_AWS_PLAN_ROLE_ARN` | The ARN of the role to use for the plan phase of a run. | Requires **v1.8.0** or later if self-managing agents. Will fall back to the value of `TFC_VAULT_BACKED_AWS_RUN_ROLE_ARN` if not provided. | | `TFC_VAULT_BACKED_AWS_APPLY_ROLE_ARN`<br />`TFC_VAULT_BACKED_AWS_APPLY_ROLE_ARN[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_AWS_APPLY_ROLE_ARN` | The ARN of the role to use for the apply phase of a run. | Requires **v1.8.0** or later if self-managing agents. Will fall back to the value of `TFC_VAULT_BACKED_AWS_RUN_ROLE_ARN` if not provided. | ## Configure Terraform Providers The final step is to directly configure your AWS and Vault providers. ### Configure the AWS Provider Ensure you pass a value for the `region` argument in your AWS provider configuration block or set the `AWS_REGION` variable in your workspace. Ensure you are not using any of the arguments or methods mentioned in the [authentication and configuration](https://registry.terraform.io/providers/hashicorp/aws/latest/docs#authentication-and-configuration) section of the provider documentation. Otherwise, these settings may interfere with dynamic provider credentials. ### Configure the Vault Provider If you were previously using the Vault provider to authenticate the AWS provider, remove any existing usage of the AWS secrets engine from your Terraform Code. This includes the [`vault_aws_access_credentials`](https://registry.terraform.io/providers/hashicorp/vault/latest/docs/data-sources/aws_access_credentials) data source and any instances of [`vault_generic_secret`](https://registry.terraform.io/providers/hashicorp/vault/latest/docs/data-sources/generic_secret) you previously used to generate AWS credentials. ### Specifying Multiple Configurations ~> **Important:** If you are self-hosting [HCP Terraform agents](/terraform/cloud-docs/agents), ensure your agents use [v1.12.0](/terraform/cloud-docs/agents/changelog#1-12-0-07-26-2023) or above. To use the latest dynamic credentials features, [upgrade your agents to the latest version](/terraform/cloud-docs/agents/changelog). You can add additional variables to handle multiple distinct Vault-backed AWS setups, enabling you to use multiple [provider aliases](/terraform/language/providers/configuration#alias-multiple-provider-configurations) within the same workspace. You can configure each set of credentials independently, or use default values by configuring the variables prefixed with `TFC_DEFAULT_`. For more details, see [Specifying Multiple Configurations](/terraform/cloud-docs/workspaces/dynamic-provider-credentials/specifying-multiple-configurations). #### Required Terraform Variable To use additional configurations, add the following code to your Terraform configuration. This lets HCP Terraform supply variable values that you can then use to map authentication and configuration details to the correct provider blocks. ```hcl variable "tfc_vault_backed_aws_dynamic_credentials" { description = "Object containing Vault-backed AWS dynamic credentials configuration" type = object({ default = object({ shared_credentials_file = string }) aliases = map(object({ shared_credentials_file = string })) }) } ``` #### Example Usage ```hcl provider "aws" { shared_credentials_files = [var.tfc_vault_backed_aws_dynamic_credentials.default.shared_credentials_file] } provider "aws" { alias = "ALIAS1" shared_credentials_files = [var.tfc_vault_backed_aws_dynamic_credentials.aliases["ALIAS1"].shared_credentials_file] } ```
terraform
page title Vault Backed Dynamic Credentials with the AWS Provider Workspaces HCP Terraform description Use OpenID Connect and Vault to get short term credentials for the AWS Terraform provider in your HCP Terraform runs Vault Backed Dynamic Credentials with the AWS Provider Important If you are self hosting HCP Terraform agents terraform cloud docs agents ensure your agents use v1 8 0 terraform cloud docs agents changelog 1 8 0 04 18 2023 or above To use the latest dynamic credentials features upgrade your agents to the latest version terraform cloud docs agents changelog You can use HCP Terraform s native OpenID Connect integration with Vault to use Vault backed dynamic credentials terraform cloud docs workspaces dynamic provider credentials vault backed with the AWS provider in your HCP Terraform runs Configuring the integration requires the following steps 1 Configure Vault Dynamic Provider Credentials configure vault dynamic provider credentials Set up a trust configuration between Vault and HCP Terraform create Vault roles and policies for your HCP Terraform workspaces and add environment variables to those workspaces 2 Configure the Vault AWS Secrets Engine configure vault aws secrets engine Set up the AWS secrets engine in your Vault instance 3 Configure HCP Terraform configure hcp terraform Add additional environment variables to the HCP Terraform workspaces where you want to use Vault Backed Dynamic Credentials 4 Configure Terraform Providers configure terraform providers Configure your Terraform providers to work with Vault backed dynamic credentials Once you complete this setup HCP Terraform automatically authenticates with AWS via Vault generated credentials during the plan and apply phase of each run The AWS provider s authentication is only valid for the length of the plan or apply phase Configure Vault Dynamic Provider Credentials You must first set up Vault dynamic provider credentials before you can use Vault backed dynamic credentials This includes setting up the JWT auth backend in Vault configuring trust between HCP Terraform and Vault and populating the required environment variables in your HCP Terraform workspace See the setup instructions for Vault dynamic provider credentials terraform cloud docs workspaces dynamic provider credentials vault configuration Configure Vault AWS Secrets Engine Follow the instructions in the Vault documentation for setting up the AWS secrets engine in your Vault instance vault docs secrets aws You can also do this configuration through Terraform Refer to our example Terraform configuration https github com hashicorp terraform dynamic credentials setup examples tree main vault backed aws Important carefully consider the limitations and differences between each supported credential type in the AWS secrets engine These limitations carry over to HCP Terraform s usage of these credentials for authenticating the AWS provider Configure HCP Terraform Next you need to set certain environment variables in your HCP Terraform workspace to authenticate HCP Terraform with AWS using Vault backed dynamic credentials These variables are in addition to those you previously set while configuring Vault dynamic provider credentials configure vault dynamic provider credentials You can add these as workspace variables or as a variable set terraform cloud docs workspaces variables managing variables variable sets When you configure dynamic provider credentials with multiple provider configurations of the same type use either a default variable or a tagged alias variable name for each provider configuration Refer to Specifying Multiple Configurations specifying multiple configurations for more details Common Environment Variables The below variables apply to all AWS auth types Required Common Environment Variables Variable Value Notes TFC VAULT BACKED AWS AUTH br TFC VAULT BACKED AWS AUTH TAG br Default variable not supported true Requires v1 8 0 or later if self managing agents Must be present and set to true or HCP Terraform will not attempt to authenticate with AWS TFC VAULT BACKED AWS AUTH TYPE br TFC VAULT BACKED AWS AUTH TYPE TAG br TFC DEFAULT VAULT BACKED AWS AUTH TYPE Specifies the type of authentication to perform with AWS Must be one of the following iam user assumed role or federation token Requires v1 8 0 or later if self managing agents TFC VAULT BACKED AWS RUN VAULT ROLE br TFC VAULT BACKED AWS RUN VAULT ROLE TAG br TFC DEFAULT VAULT BACKED AWS RUN VAULT ROLE The role to use in Vault Requires v1 8 0 or later if self managing agents Optional if TFC VAULT BACKED AWS PLAN VAULT ROLE and TFC VAULT BACKED AWS APPLY VAULT ROLE are both provided These variables are described below optional common environment variables Optional Common Environment Variables You may need to set these variables depending on your use case Variable Value Notes TFC VAULT BACKED AWS MOUNT PATH br TFC VAULT BACKED AWS MOUNT PATH TAG br TFC DEFAULT VAULT BACKED AWS MOUNT PATH The mount path of the AWS secrets engine in Vault Requires v1 8 0 or later if self managing agents Defaults to aws TFC VAULT BACKED AWS PLAN VAULT ROLE br TFC VAULT BACKED AWS PLAN VAULT ROLE TAG br TFC DEFAULT VAULT BACKED AWS PLAN VAULT ROLE The Vault role to use the plan phase of a run Requires v1 8 0 or later if self managing agents Will fall back to the value of TFC VAULT BACKED AWS RUN VAULT ROLE if not provided TFC VAULT BACKED AWS APPLY VAULT ROLE br TFC VAULT BACKED AWS APPLY VAULT ROLE TAG br TFC DEFAULT VAULT BACKED AWS APPLY VAULT ROLE The Vault role to use for the apply phase of a run Requires v1 8 0 or later if self managing agents Will fall back to the value of TFC VAULT BACKED AWS RUN VAULT ROLE if not provided TFC VAULT BACKED AWS SLEEP SECONDS br TFC VAULT BACKED AWS SLEEP SECONDS TAG br TFC DEFAULT VAULT BACKED AWS SLEEP SECONDS The amount of time to wait in seconds after obtaining temporary credentials from Vault e g 30 for 30 seconds Must be 1500 seconds 25 minutes or less Requires v1 12 0 or later if self managing agents Can be used to mitigate eventual consistency issues in AWS when using the iam user auth type TFC VAULT BACKED AWS VAULT CONFIG br TFC VAULT BACKED AWS VAULT CONFIG TAG br TFC DEFAULT VAULT BACKED AWS VAULT CONFIG The name of the non default Vault configuration for workspaces using multiple Vault configurations terraform cloud docs workspaces dynamic provider credentials specifying multiple configurations Requires v1 12 0 or later if self managing agents Will fall back to using the default Vault configuration if not provided Assumed Role Specific Environment Variables These environment variables are only valid if the TFC VAULT BACKED AWS AUTH TYPE is assumed role Required Assumed Role Specific Environment Variables Variable Value Notes TFC VAULT BACKED AWS RUN ROLE ARN br TFC VAULT BACKED AWS RUN ROLE ARN TAG br TFC DEFAULT VAULT BACKED AWS RUN ROLE ARN The ARN of the role to assume in AWS Requires v1 8 0 or later if self managing agents Optional if TFC VAULT BACKED AWS PLAN ROLE ARN and TFC VAULT BACKED AWS APPLY ROLE ARN are both provided These variables are described below optional assume role specific environment variables Optional Assumed Role Specific Environment Variables You may need to set these variables depending on your use case Variable Value Notes TFC VAULT BACKED AWS PLAN ROLE ARN br TFC VAULT BACKED AWS PLAN ROLE ARN TAG br TFC DEFAULT VAULT BACKED AWS PLAN ROLE ARN The ARN of the role to use for the plan phase of a run Requires v1 8 0 or later if self managing agents Will fall back to the value of TFC VAULT BACKED AWS RUN ROLE ARN if not provided TFC VAULT BACKED AWS APPLY ROLE ARN br TFC VAULT BACKED AWS APPLY ROLE ARN TAG br TFC DEFAULT VAULT BACKED AWS APPLY ROLE ARN The ARN of the role to use for the apply phase of a run Requires v1 8 0 or later if self managing agents Will fall back to the value of TFC VAULT BACKED AWS RUN ROLE ARN if not provided Configure Terraform Providers The final step is to directly configure your AWS and Vault providers Configure the AWS Provider Ensure you pass a value for the region argument in your AWS provider configuration block or set the AWS REGION variable in your workspace Ensure you are not using any of the arguments or methods mentioned in the authentication and configuration https registry terraform io providers hashicorp aws latest docs authentication and configuration section of the provider documentation Otherwise these settings may interfere with dynamic provider credentials Configure the Vault Provider If you were previously using the Vault provider to authenticate the AWS provider remove any existing usage of the AWS secrets engine from your Terraform Code This includes the vault aws access credentials https registry terraform io providers hashicorp vault latest docs data sources aws access credentials data source and any instances of vault generic secret https registry terraform io providers hashicorp vault latest docs data sources generic secret you previously used to generate AWS credentials Specifying Multiple Configurations Important If you are self hosting HCP Terraform agents terraform cloud docs agents ensure your agents use v1 12 0 terraform cloud docs agents changelog 1 12 0 07 26 2023 or above To use the latest dynamic credentials features upgrade your agents to the latest version terraform cloud docs agents changelog You can add additional variables to handle multiple distinct Vault backed AWS setups enabling you to use multiple provider aliases terraform language providers configuration alias multiple provider configurations within the same workspace You can configure each set of credentials independently or use default values by configuring the variables prefixed with TFC DEFAULT For more details see Specifying Multiple Configurations terraform cloud docs workspaces dynamic provider credentials specifying multiple configurations Required Terraform Variable To use additional configurations add the following code to your Terraform configuration This lets HCP Terraform supply variable values that you can then use to map authentication and configuration details to the correct provider blocks hcl variable tfc vault backed aws dynamic credentials description Object containing Vault backed AWS dynamic credentials configuration type object default object shared credentials file string aliases map object shared credentials file string Example Usage hcl provider aws shared credentials files var tfc vault backed aws dynamic credentials default shared credentials file provider aws alias ALIAS1 shared credentials files var tfc vault backed aws dynamic credentials aliases ALIAS1 shared credentials file
terraform Use OpenID Connect and Vault to get short term credentials for the Azure Terraform providers in page title Vault Backed Dynamic Credentials with the Azure Providers HCP Terraform your HCP Terraform runs Vault Backed Dynamic Credentials with the Azure Provider Important If you are self hosting HCP Terraform agents terraform cloud docs agents ensure your agents use v1 8 0 terraform cloud docs agents changelog 1 8 0 04 18 2023 or above To use the latest dynamic credentials features upgrade your agents to the latest version terraform cloud docs agents changelog
--- page_title: Vault-Backed Dynamic Credentials with the Azure Providers - HCP Terraform description: >- Use OpenID Connect and Vault to get short-term credentials for the Azure Terraform providers in your HCP Terraform runs. --- # Vault-Backed Dynamic Credentials with the Azure Provider ~> **Important:** If you are self-hosting [HCP Terraform agents](/terraform/cloud-docs/agents), ensure your agents use [v1.8.0](/terraform/cloud-docs/agents/changelog#1-8-0-04-18-2023) or above. To use the latest dynamic credentials features, [upgrade your agents to the latest version](/terraform/cloud-docs/agents/changelog). You can use HCP Terraform’s native OpenID Connect integration with Vault to use [Vault-backed dynamic credentials](/terraform/cloud-docs/workspaces/dynamic-provider-credentials/vault-backed) with the Azure provider in your HCP Terraform runs. Configuring the integration requires the following steps: 1. **[Configure Vault Dynamic Provider Credentials](#configure-vault-dynamic-provider-credentials)**: Set up a trust configuration between Vault and HCP Terraform, create Vault roles and policies for your HCP Terraform workspaces, and add environment variables to those workspaces. 2. **[Configure the Vault Azure Secrets Engine](#configure-vault-azure-secrets-engine)**: Set up the Azure secrets engine in your Vault instance. 3. **[Configure HCP Terraform](#configure-hcp-terraform)**: Add additional environment variables to the HCP Terraform workspaces where you want to use Vault-Backed Dynamic Credentials. 4. **[Configure Terraform Providers](#configure-terraform-providers)**: Configure your Terraform providers to work with Vault-backed Dynamic Credentials. Once you complete this setup, HCP Terraform automatically authenticates with Azure via Vault-generated credentials during the plan and apply phase of each run. The Azure provider's authentication is only valid for the length of the plan or apply phase. ## Configure Vault Dynamic Provider Credentials You must first set up Vault dynamic provider credentials before you can use Vault-backed dynamic credentials. This includes setting up the JWT auth backend in Vault, configuring trust between HCP Terraform and Vault, and populating the required environment variables in your HCP Terraform workspace. [See the setup instructions for Vault dynamic provider credentials](/terraform/cloud-docs/workspaces/dynamic-provider-credentials/vault-configuration). # Configure Vault Azure Secrets Engine Follow the instructions in the Vault documentation for [setting up the Azure secrets engine in your Vault instance](/vault/docs/secrets/azure). You can also do this configuration through Terraform. Refer to our [example Terraform configuration](https://github.com/hashicorp/terraform-dynamic-credentials-setup-examples/tree/main/vault-backed/azure). ## Configure HCP Terraform Next, you need to set certain environment variables in your HCP Terraform workspace to authenticate HCP Terraform with Azure using Vault-backed dynamic credentials. These variables are in addition to those you previously set while configuring [Vault dynamic provider credentials](#configure-vault-dynamic-provider-credentials). You can add these as workspace variables or as a [variable set](/terraform/cloud-docs/workspaces/variables/managing-variables#variable-sets). When you configure dynamic provider credentials with multiple provider configurations of the same type, use either a default variable or a tagged alias variable name for each provider configuration. Refer to [Specifying Multiple Configurations](#specifying-multiple-configurations) for more details. ### Required Environment Variables | Variable | Value | Notes | |-------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `TFC_VAULT_BACKED_AZURE_AUTH`<br />`TFC_VAULT_BACKED_AZURE_AUTH[_TAG]`<br />_(Default variable not supported)_ | `true` | Requires **v1.8.0** or later if self-managing agents. Must be present and set to `true`, or HCP Terraform will not attempt to authenticate with Azure. | | `TFC_VAULT_BACKED_AZURE_RUN_VAULT_ROLE`<br />`TFC_VAULT_BACKED_AZURE_RUN_VAULT_ROLE[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_AZURE_RUN_VAULT_ROLE` | The role to use in Vault. | Requires **v1.8.0** or later if self-managing agents. Optional if `TFC_VAULT_BACKED_AZURE_PLAN_VAULT_ROLE` and `TFC_VAULT_BACKED_AZURE_APPLY_VAULT_ROLE` are both provided. These variables are described [below](#optional-environment-variables). | ### Optional Environment Variables You may need to set these variables, depending on your use case. | Variable | Value | Notes | |-------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------| | `TFC_VAULT_BACKED_AZURE_MOUNT_PATH`<br />`TFC_VAULT_BACKED_AZURE_MOUNT_PATH[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_AZURE_MOUNT_PATH` | The mount path of the Azure secrets engine in Vault. | Requires **v1.8.0** or later if self-managing agents. Defaults to `azure`. | | `TFC_VAULT_BACKED_AZURE_PLAN_VAULT_ROLE`<br />`TFC_VAULT_BACKED_AZURE_PLAN_VAULT_ROLE[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_AZURE_PLAN_VAULT_ROLE` | The Vault role to use the plan phase of a run. | Requires **v1.8.0** or later if self-managing agents. Will fall back to the value of `TFC_VAULT_BACKED_AZURE_RUN_VAULT_ROLE` if not provided. | | `TFC_VAULT_BACKED_AZURE_APPLY_VAULT_ROLE`<br />`TFC_VAULT_BACKED_AZURE_APPLY_VAULT_ROLE[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_AZURE_APPLY_VAULT_ROLE` | The Vault role to use for the apply phase of a run. | Requires **v1.8.0** or later if self-managing agents. Will fall back to the value of `TFC_VAULT_BACKED_AZURE_RUN_VAULT_ROLE` if not provided. | | `TFC_VAULT_BACKED_AZURE_SLEEP_SECONDS`<br />`TFC_VAULT_BACKED_AZURE_SLEEP_SECONDS[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_AZURE_SLEEP_SECONDS` | The amount of time to wait, in seconds, after obtaining temporary credentials from Vault. e.g., `30` for 30 seconds. Must be 1500 seconds (25 minutes) or less. | Requires **v1.12.0** or later if self-managing agents. Can be used to mitigate eventual consistency issues in Azure. | | `TFC_VAULT_BACKED_AZURE_VAULT_CONFIG`<br />`TFC_VAULT_BACKED_AZURE_VAULT_CONFIG[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_AZURE_VAULT_CONFIG` | The name of the non-default Vault configuration for workspaces using [multiple Vault configurations](/terraform/cloud-docs/workspaces/dynamic-provider-credentials/specifying-multiple-configurations). | Requires **v1.12.0** or later if self-managing agents. Will fall back to using the default Vault configuration if not provided. | ## Configure Terraform Providers The final step is to directly configure your Azure and Vault providers. ### Configure the AzureRM or Microsoft Entra ID Ensure you pass a value for the `subscription_id` and `tenant_id` arguments in your provider configuration block or set the `ARM_SUBSCRIPTION_ID` and `ARM_TENANT_ID` variables in your workspace. Do not set values for `client_id`, `use_oidc`, or `oidc_token` in your provider configuration block. Additionally, do not set variable values for `ARM_CLIENT_ID`, `ARM_USE_OIDC`, or `ARM_OIDC_TOKEN`. ### Configure the Vault Provider If you were previously using the Vault provider to authenticate the Azure provider, remove any existing usage of the Azure secrets engine from your Terraform Code. This includes the [`vault_azure_access_credentials`](https://registry.terraform.io/providers/hashicorp/vault/latest/docs/data-sources/azure_access_credentials) data source and any instances of [`vault_generic_secret`](https://registry.terraform.io/providers/hashicorp/vault/latest/docs/data-sources/generic_secret) you previously used to generate Azure credentials. ### Specifying Multiple Configurations ~> **Important:** Ensure you are using version **3.60.0** or later of the **AzureRM provider** and version **2.43.0** or later of the **Microsoft Entra ID provider** (previously Azure Active Directory) as required functionality was introduced in these provider versions. ~> **Important:** If you are self-hosting [HCP Terraform agents](/terraform/cloud-docs/agents), ensure your agents use [v1.12.0](/terraform/cloud-docs/agents/changelog#1-12-0-07-26-2023) or above. To use the latest dynamic credentials features, [upgrade your agents to the latest version](/terraform/cloud-docs/agents/changelog). You can add additional variables to handle multiple distinct Vault-backed Azure setups, enabling you to use multiple [provider aliases](/terraform/language/providers/configuration#alias-multiple-provider-configurations) within the same workspace. You can configure each set of credentials independently, or use default values by configuring the variables prefixed with `TFC_DEFAULT_`. For more details, see [Specifying Multiple Configurations](/terraform/cloud-docs/workspaces/dynamic-provider-credentials/specifying-multiple-configurations). #### Required Terraform Variable To use additional configurations, add the following code to your Terraform configuration. This lets HCP Terraform supply variable values that you can then use to map authentication and configuration details to the correct provider blocks. ```hcl variable "tfc_vault_backed_azure_dynamic_credentials" { description = "Object containing Vault-backed Azure dynamic credentials configuration" type = object({ default = object({ client_id_file_path = string client_secret_file_path = string }) aliases = map(object({ client_id_file_path = string client_secret_file_path = string })) }) } ``` #### Example Usage ##### AzureRM Provider ```hcl provider "azurerm" { features {} // use_cli should be set to false to yield more accurate error messages on auth failure. use_cli = false client_id_file_path = var.tfc_vault_backed_azure_dynamic_credentials.default.client_id_file_path client_secret_file_path = var.tfc_vault_backed_azure_dynamic_credentials.default.client_secret_file_path subscription_id = "00000000-0000-0000-0000-000000000000" tenant_id = "10000000-0000-0000-0000-000000000000" } provider "azurerm" { features {} // use_cli should be set to false to yield more accurate error messages on auth failure. use_cli = false alias = "ALIAS1" client_id_file_path = var.tfc_vault_backed_azure_dynamic_credentials.aliases["ALIAS1"].client_id_file_path client_secret_file_path = var.tfc_vault_backed_azure_dynamic_credentials.aliases["ALIAS1"].client_secret_file_path subscription_id = "00000000-0000-0000-0000-000000000000" tenant_id = "20000000-0000-0000-0000-000000000000" } ``` ##### Microsoft Entra ID Provider (previously AzureAD) ```hcl provider "azuread" { features {} // use_cli should be set to false to yield more accurate error messages on auth failure. use_cli = false client_id_file_path = var.tfc_vault_backed_azure_dynamic_credentials.default.client_id_file_path client_secret_file_path = var.tfc_vault_backed_azure_dynamic_credentials.default.client_secret_file_path subscription_id = "00000000-0000-0000-0000-000000000000" tenant_id = "10000000-0000-0000-0000-000000000000" } provider "azuread" { features {} // use_cli should be set to false to yield more accurate error messages on auth failure. use_cli = false alias = "ALIAS1" client_id_file_path = var.tfc_vault_backed_azure_dynamic_credentials.aliases["ALIAS1"].client_id_file_path client_secret_file_path = var.tfc_vault_backed_azure_dynamic_credentials.aliases["ALIAS1"].client_secret_file_path subscription_id = "00000000-0000-0000-0000-000000000000" tenant_id = "20000000-0000-0000-0000-000000000000" } ```
terraform
page title Vault Backed Dynamic Credentials with the Azure Providers HCP Terraform description Use OpenID Connect and Vault to get short term credentials for the Azure Terraform providers in your HCP Terraform runs Vault Backed Dynamic Credentials with the Azure Provider Important If you are self hosting HCP Terraform agents terraform cloud docs agents ensure your agents use v1 8 0 terraform cloud docs agents changelog 1 8 0 04 18 2023 or above To use the latest dynamic credentials features upgrade your agents to the latest version terraform cloud docs agents changelog You can use HCP Terraform s native OpenID Connect integration with Vault to use Vault backed dynamic credentials terraform cloud docs workspaces dynamic provider credentials vault backed with the Azure provider in your HCP Terraform runs Configuring the integration requires the following steps 1 Configure Vault Dynamic Provider Credentials configure vault dynamic provider credentials Set up a trust configuration between Vault and HCP Terraform create Vault roles and policies for your HCP Terraform workspaces and add environment variables to those workspaces 2 Configure the Vault Azure Secrets Engine configure vault azure secrets engine Set up the Azure secrets engine in your Vault instance 3 Configure HCP Terraform configure hcp terraform Add additional environment variables to the HCP Terraform workspaces where you want to use Vault Backed Dynamic Credentials 4 Configure Terraform Providers configure terraform providers Configure your Terraform providers to work with Vault backed Dynamic Credentials Once you complete this setup HCP Terraform automatically authenticates with Azure via Vault generated credentials during the plan and apply phase of each run The Azure provider s authentication is only valid for the length of the plan or apply phase Configure Vault Dynamic Provider Credentials You must first set up Vault dynamic provider credentials before you can use Vault backed dynamic credentials This includes setting up the JWT auth backend in Vault configuring trust between HCP Terraform and Vault and populating the required environment variables in your HCP Terraform workspace See the setup instructions for Vault dynamic provider credentials terraform cloud docs workspaces dynamic provider credentials vault configuration Configure Vault Azure Secrets Engine Follow the instructions in the Vault documentation for setting up the Azure secrets engine in your Vault instance vault docs secrets azure You can also do this configuration through Terraform Refer to our example Terraform configuration https github com hashicorp terraform dynamic credentials setup examples tree main vault backed azure Configure HCP Terraform Next you need to set certain environment variables in your HCP Terraform workspace to authenticate HCP Terraform with Azure using Vault backed dynamic credentials These variables are in addition to those you previously set while configuring Vault dynamic provider credentials configure vault dynamic provider credentials You can add these as workspace variables or as a variable set terraform cloud docs workspaces variables managing variables variable sets When you configure dynamic provider credentials with multiple provider configurations of the same type use either a default variable or a tagged alias variable name for each provider configuration Refer to Specifying Multiple Configurations specifying multiple configurations for more details Required Environment Variables Variable Value Notes TFC VAULT BACKED AZURE AUTH br TFC VAULT BACKED AZURE AUTH TAG br Default variable not supported true Requires v1 8 0 or later if self managing agents Must be present and set to true or HCP Terraform will not attempt to authenticate with Azure TFC VAULT BACKED AZURE RUN VAULT ROLE br TFC VAULT BACKED AZURE RUN VAULT ROLE TAG br TFC DEFAULT VAULT BACKED AZURE RUN VAULT ROLE The role to use in Vault Requires v1 8 0 or later if self managing agents Optional if TFC VAULT BACKED AZURE PLAN VAULT ROLE and TFC VAULT BACKED AZURE APPLY VAULT ROLE are both provided These variables are described below optional environment variables Optional Environment Variables You may need to set these variables depending on your use case Variable Value Notes TFC VAULT BACKED AZURE MOUNT PATH br TFC VAULT BACKED AZURE MOUNT PATH TAG br TFC DEFAULT VAULT BACKED AZURE MOUNT PATH The mount path of the Azure secrets engine in Vault Requires v1 8 0 or later if self managing agents Defaults to azure TFC VAULT BACKED AZURE PLAN VAULT ROLE br TFC VAULT BACKED AZURE PLAN VAULT ROLE TAG br TFC DEFAULT VAULT BACKED AZURE PLAN VAULT ROLE The Vault role to use the plan phase of a run Requires v1 8 0 or later if self managing agents Will fall back to the value of TFC VAULT BACKED AZURE RUN VAULT ROLE if not provided TFC VAULT BACKED AZURE APPLY VAULT ROLE br TFC VAULT BACKED AZURE APPLY VAULT ROLE TAG br TFC DEFAULT VAULT BACKED AZURE APPLY VAULT ROLE The Vault role to use for the apply phase of a run Requires v1 8 0 or later if self managing agents Will fall back to the value of TFC VAULT BACKED AZURE RUN VAULT ROLE if not provided TFC VAULT BACKED AZURE SLEEP SECONDS br TFC VAULT BACKED AZURE SLEEP SECONDS TAG br TFC DEFAULT VAULT BACKED AZURE SLEEP SECONDS The amount of time to wait in seconds after obtaining temporary credentials from Vault e g 30 for 30 seconds Must be 1500 seconds 25 minutes or less Requires v1 12 0 or later if self managing agents Can be used to mitigate eventual consistency issues in Azure TFC VAULT BACKED AZURE VAULT CONFIG br TFC VAULT BACKED AZURE VAULT CONFIG TAG br TFC DEFAULT VAULT BACKED AZURE VAULT CONFIG The name of the non default Vault configuration for workspaces using multiple Vault configurations terraform cloud docs workspaces dynamic provider credentials specifying multiple configurations Requires v1 12 0 or later if self managing agents Will fall back to using the default Vault configuration if not provided Configure Terraform Providers The final step is to directly configure your Azure and Vault providers Configure the AzureRM or Microsoft Entra ID Ensure you pass a value for the subscription id and tenant id arguments in your provider configuration block or set the ARM SUBSCRIPTION ID and ARM TENANT ID variables in your workspace Do not set values for client id use oidc or oidc token in your provider configuration block Additionally do not set variable values for ARM CLIENT ID ARM USE OIDC or ARM OIDC TOKEN Configure the Vault Provider If you were previously using the Vault provider to authenticate the Azure provider remove any existing usage of the Azure secrets engine from your Terraform Code This includes the vault azure access credentials https registry terraform io providers hashicorp vault latest docs data sources azure access credentials data source and any instances of vault generic secret https registry terraform io providers hashicorp vault latest docs data sources generic secret you previously used to generate Azure credentials Specifying Multiple Configurations Important Ensure you are using version 3 60 0 or later of the AzureRM provider and version 2 43 0 or later of the Microsoft Entra ID provider previously Azure Active Directory as required functionality was introduced in these provider versions Important If you are self hosting HCP Terraform agents terraform cloud docs agents ensure your agents use v1 12 0 terraform cloud docs agents changelog 1 12 0 07 26 2023 or above To use the latest dynamic credentials features upgrade your agents to the latest version terraform cloud docs agents changelog You can add additional variables to handle multiple distinct Vault backed Azure setups enabling you to use multiple provider aliases terraform language providers configuration alias multiple provider configurations within the same workspace You can configure each set of credentials independently or use default values by configuring the variables prefixed with TFC DEFAULT For more details see Specifying Multiple Configurations terraform cloud docs workspaces dynamic provider credentials specifying multiple configurations Required Terraform Variable To use additional configurations add the following code to your Terraform configuration This lets HCP Terraform supply variable values that you can then use to map authentication and configuration details to the correct provider blocks hcl variable tfc vault backed azure dynamic credentials description Object containing Vault backed Azure dynamic credentials configuration type object default object client id file path string client secret file path string aliases map object client id file path string client secret file path string Example Usage AzureRM Provider hcl provider azurerm features use cli should be set to false to yield more accurate error messages on auth failure use cli false client id file path var tfc vault backed azure dynamic credentials default client id file path client secret file path var tfc vault backed azure dynamic credentials default client secret file path subscription id 00000000 0000 0000 0000 000000000000 tenant id 10000000 0000 0000 0000 000000000000 provider azurerm features use cli should be set to false to yield more accurate error messages on auth failure use cli false alias ALIAS1 client id file path var tfc vault backed azure dynamic credentials aliases ALIAS1 client id file path client secret file path var tfc vault backed azure dynamic credentials aliases ALIAS1 client secret file path subscription id 00000000 0000 0000 0000 000000000000 tenant id 20000000 0000 0000 0000 000000000000 Microsoft Entra ID Provider previously AzureAD hcl provider azuread features use cli should be set to false to yield more accurate error messages on auth failure use cli false client id file path var tfc vault backed azure dynamic credentials default client id file path client secret file path var tfc vault backed azure dynamic credentials default client secret file path subscription id 00000000 0000 0000 0000 000000000000 tenant id 10000000 0000 0000 0000 000000000000 provider azuread features use cli should be set to false to yield more accurate error messages on auth failure use cli false alias ALIAS1 client id file path var tfc vault backed azure dynamic credentials aliases ALIAS1 client id file path client secret file path var tfc vault backed azure dynamic credentials aliases ALIAS1 client secret file path subscription id 00000000 0000 0000 0000 000000000000 tenant id 20000000 0000 0000 0000 000000000000
terraform your HCP Terraform runs Use OpenID Connect and Vault to get short term credentials for the GCP Terraform provider in Vault Backed Dynamic Credentials with the GCP Provider page title Vault Backed Dynamic Credentials with the GCP Provider Workspaces HCP Terraform Important If you are self hosting HCP Terraform agents terraform cloud docs agents ensure your agents use v1 8 0 terraform cloud docs agents changelog 1 8 0 04 18 2023 or above To use the latest dynamic credentials features upgrade your agents to the latest version terraform cloud docs agents changelog
--- page_title: Vault-Backed Dynamic Credentials with the GCP Provider - Workspaces - HCP Terraform description: >- Use OpenID Connect and Vault to get short-term credentials for the GCP Terraform provider in your HCP Terraform runs. --- # Vault-Backed Dynamic Credentials with the GCP Provider ~> **Important:** If you are self-hosting [HCP Terraform agents](/terraform/cloud-docs/agents), ensure your agents use [v1.8.0](/terraform/cloud-docs/agents/changelog#1-8-0-04-18-2023) or above. To use the latest dynamic credentials features, [upgrade your agents to the latest version](/terraform/cloud-docs/agents/changelog). You can use HCP Terraform’s native OpenID Connect integration with Vault to use [Vault-backed dynamic credentials](/terraform/cloud-docs/workspaces/dynamic-provider-credentials/vault-backed) with the GCP provider in your HCP Terraform runs. Configuring the integration requires the following steps: 1. **[Configure Vault Dynamic Provider Credentials](#configure-vault-dynamic-provider-credentials)**: Set up a trust configuration between Vault and HCP Terraform, create Vault roles and policies for your HCP Terraform workspaces, and add environment variables to those workspaces. 2. **[Configure the Vault GCP Secrets Engine](#configure-vault-gcp-secrets-engine)**: Set up the GCP secrets engine in your Vault instance. 3. **[Configure HCP Terraform](#configure-hcp-terraform)**: Add additional environment variables to the HCP Terraform workspaces where you want to use Vault-Backed Dynamic Credentials. 4. **[Configure Terraform Providers](#configure-terraform-providers)**: Configure your Terraform providers to work with Vault-backed dynamic credentials. Once you complete this setup, HCP Terraform automatically authenticates with GCP via Vault-generated credentials during the plan and apply phase of each run. The GCP provider's authentication is only valid for the length of the plan or apply phase. ## Configure Vault Dynamic Provider Credentials You must first set up Vault dynamic provider credentials before you can use Vault-backed dynamic credentials. This includes setting up the JWT auth backend in Vault, configuring trust between HCP Terraform and Vault, and populating the required environment variables in your HCP Terraform workspace. [See the setup instructions for Vault dynamic provider credentials](/terraform/cloud-docs/workspaces/dynamic-provider-credentials/vault-configuration). # Configure Vault GCP Secrets Engine Follow the instructions in the Vault documentation for [setting up the GCP secrets engine in your Vault instance](/vault/docs/secrets/gcp). You can also do this configuration through Terraform. Refer to our [example Terraform configuration](https://github.com/hashicorp/terraform-dynamic-credentials-setup-examples/tree/main/vault-backed/gcp). ~> **Important**: carefully consider the limitations and differences between each supported credential type in the GCP secrets engine. These limitations carry over to HCP Terraform’s usage of these credentials for authenticating the GCP provider. ## Configure HCP Terraform Next, you need to set certain environment variables in your HCP Terraform workspace to authenticate HCP Terraform with GCP using Vault-backed dynamic credentials. These variables are in addition to those you previously set while configuring [Vault dynamic provider credentials](#configure-vault-dynamic-provider-credentials). You can add these as workspace variables or as a [variable set](/terraform/cloud-docs/workspaces/variables/managing-variables#variable-sets). When you configure dynamic provider credentials with multiple provider configurations of the same type, use either a default variable or a tagged alias variable name for each provider configuration. Refer to [Specifying Multiple Configurations](#specifying-multiple-configurations) for more details. ### Common Environment Variables The below variables apply to all GCP auth types. #### Required Common Environment Variables | Variable | Value | Notes | |----------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------| | `TFC_VAULT_BACKED_GCP_AUTH`<br />`TFC_VAULT_BACKED_GCP_AUTH[_TAG]`<br />_(Default variable not supported)_ | `true` | Requires **v1.8.0** or later if self-managing agents. Must be present and set to `true`, or HCP Terraform will not attempt to authenticate with GCP. | | `TFC_VAULT_BACKED_GCP_AUTH_TYPE`<br />`TFC_VAULT_BACKED_GCP_AUTH_TYPE[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_GCP_AUTH_TYPE` | Specifies the type of authentication to perform with GCP. Must be one of the following: `roleset/access_token`, `roleset/service_account_key`, `static_account/access_token`, or `static_account/service_account_key`. | Requires **v1.8.0** or later if self-managing agents. | #### Optional Common Environment Variables You may need to set these variables, depending on your use case. | Variable | Value | Notes | |-------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------| | `TFC_VAULT_BACKED_GCP_MOUNT_PATH`<br />`TFC_VAULT_BACKED_GCP_MOUNT_PATH[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_GCP_MOUNT_PATH` | The mount path of the GCP secrets engine in Vault. | Requires **v1.8.0** or later if self-managing agents. Defaults to `gcp`. | | `TFC_VAULT_BACKED_GCP_VAULT_CONFIG`<br />`TFC_VAULT_BACKED_GCP_VAULT_CONFIG[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_GCP_VAULT_CONFIG` | The name of the non-default Vault configuration for workspaces using [multiple Vault configurations](/terraform/cloud-docs/workspaces/dynamic-provider-credentials/specifying-multiple-configurations). | Requires **v1.12.0** or later if self-managing agents. Will fall back to using the default Vault configuration if not provided. | ### Roleset Specific Environment Variables These environment variables are only valid if the `TFC_VAULT_BACKED_GCP_AUTH_TYPE` is `roleset/access_token` or `roleset/service_account_key`. #### Required Roleset Specific Environment Variables | Variable | Value | Notes | |----------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `TFC_VAULT_BACKED_GCP_RUN_VAULT_ROLESET`<br />`TFC_VAULT_BACKED_GCP_RUN_VAULT_ROLESET[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_GCP_RUN_VAULT_ROLESET` | The roleset to use in Vault. | Requires **v1.8.0** or later if self-managing agents. Optional if `TFC_VAULT_BACKED_GCP_PLAN_VAULT_ROLESET` and `TFC_VAULT_BACKED_GCP_APPLY_VAULT_ROLESET` are both provided. These variables are described [below](#optional-roleset-specific-environment-variables). | #### Optional Roleset Specific Environment Variables You may need to set these variables, depending on your use case. | Variable | Value | Notes | |----------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------| | `TFC_VAULT_BACKED_GCP_PLAN_VAULT_ROLESET`<br />`TFC_VAULT_BACKED_GCP_PLAN_VAULT_ROLESET[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_GCP_PLAN_VAULT_ROLESET` | The roleset to use for the plan phase of a run. | Requires **v1.8.0** or later if self-managing agents. Will fall back to the value of `TFC_VAULT_BACKED_GCP_RUN_VAULT_ROLESET` if not provided. | | `TFC_VAULT_BACKED_GCP_APPLY_VAULT_ROLESET`<br />`TFC_VAULT_BACKED_GCP_APPLY_VAULT_ROLESET[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_GCP_APPLY_VAULT_ROLESET` | The roleset to use for the apply phase of a run. | Requires **v1.8.0** or later if self-managing agents. Will fall back to the value of `TFC_VAULT_BACKED_GCP_RUN_VAULT_ROLESET` if not provided. | ### Static Account Specific Environment Variables These environment variables are only valid if the `TFC_VAULT_BACKED_GCP_AUTH_TYPE` is `static_account/access_token` or `static_account/service_account_key`. #### Required Static Account Specific Environment Variables | Variable | Value | Notes | |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `TFC_VAULT_BACKED_GCP_RUN_VAULT_STATIC_ACCOUNT`<br />`TFC_VAULT_BACKED_GCP_RUN_VAULT_STATIC_ACCOUNT[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_GCP_RUN_VAULT_STATIC_ACCOUNT` | The static account to use in Vault. | Requires **v1.8.0** or later if self-managing agents. Optional if `TFC_VAULT_BACKED_GCP_PLAN_VAULT_STATIC_ACCOUNT` and `TFC_VAULT_BACKED_GCP_APPLY_VAULT_STATIC_ACCOUNT` are both provided. These variables are described [below](#optional-static-account-specific-environment-variables). | #### Optional Static Account Specific Environment Variables You may need to set these variables, depending on your use case. | Variable | Value | Notes | |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------| | `TFC_VAULT_BACKED_GCP_PLAN_VAULT_STATIC_ACCOUNT`<br />`TFC_VAULT_BACKED_GCP_PLAN_VAULT_STATIC_ACCOUNT[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_GCP_PLAN_VAULT_STATIC_ACCOUNT` | The static account to use for the plan phase of a run. | Requires **v1.8.0** or later if self-managing agents. Will fall back to the value of `TFC_VAULT_BACKED_GCP_RUN_VAULT_STATIC_ACCOUNT` if not provided. | | `TFC_VAULT_BACKED_GCP_APPLY_VAULT_STATIC_ACCOUNT`<br />`TFC_VAULT_BACKED_GCP_APPLY_VAULT_STATIC_ACCOUNT[_TAG]`<br />`TFC_DEFAULT_VAULT_BACKED_GCP_APPLY_VAULT_STATIC_ACCOUNT` | The static account to use for the apply phase of a run. | Requires **v1.8.0** or later if self-managing agents. Will fall back to the value of `TFC_VAULT_BACKED_GCP_RUN_VAULT_STATIC_ACCOUNT` if not provided. | ## Configure Terraform Providers The final step is to directly configure your GCP and Vault providers. ### Configure the GCP Provider Ensure you pass values for the `project` and `region` arguments into the provider configuration block. Ensure you are not setting values or environment variables for `GOOGLE_CREDENTIALS` or `GOOGLE_APPLICATION_CREDENTIALS`. Otherwise, these values may interfere with dynamic provider credentials. ### Configure the Vault Provider If you were previously using the Vault provider to authenticate the GCP provider, remove any existing usage of the GCP secrets engine from your Terraform Code. This includes instances of [`vault_generic_secret`](https://registry.terraform.io/providers/hashicorp/vault/latest/docs/data-sources/generic_secret) that you previously used to generate GCP credentials. ### Specifying Multiple Configurations ~> **Important:** If you are self-hosting [HCP Terraform agents](/terraform/cloud-docs/agents), ensure your agents use [v1.12.0](/terraform/cloud-docs/agents/changelog#1-12-0-07-26-2023) or above. To use the latest dynamic credentials features, [upgrade your agents to the latest version](/terraform/cloud-docs/agents/changelog). You can add additional variables to handle multiple distinct Vault-backed GCP setups, enabling you to use multiple [provider aliases](/terraform/language/providers/configuration#alias-multiple-provider-configurations) within the same workspace. You can configure each set of credentials independently, or use default values by configuring the variables prefixed with `TFC_DEFAULT_`. For more details, see [Specifying Multiple Configurations](/terraform/cloud-docs/workspaces/dynamic-provider-credentials/specifying-multiple-configurations). #### Required Terraform Variable To use additional configurations, add the following code to your Terraform configuration. This lets HCP Terraform supply variable values that you can then use to map authentication and configuration details to the correct provider blocks. ```hcl variable "tfc_vault_backed_gcp_dynamic_credentials" { description = "Object containing Vault-backed GCP dynamic credentials configuration" type = object({ default = object({ credentials = string access_token = string }) aliases = map(object({ credentials = string access_token = string })) }) } ``` #### Example Usage ##### Access Token ```hcl provider "google" { access_token = var.tfc_vault_backed_gcp_dynamic_credentials.default.access_token } provider "google" { alias = "ALIAS1" access_token = var.tfc_vault_backed_gcp_dynamic_credentials.aliases["ALIAS1"].access_token } ``` ##### Credentials ```hcl provider "google" { credentials = var.tfc_vault_backed_gcp_dynamic_credentials.default.credentials } provider "google" { alias = "ALIAS1" credentials = var.tfc_vault_backed_gcp_dynamic_credentials.aliases["ALIAS1"].credentials } ```
terraform
page title Vault Backed Dynamic Credentials with the GCP Provider Workspaces HCP Terraform description Use OpenID Connect and Vault to get short term credentials for the GCP Terraform provider in your HCP Terraform runs Vault Backed Dynamic Credentials with the GCP Provider Important If you are self hosting HCP Terraform agents terraform cloud docs agents ensure your agents use v1 8 0 terraform cloud docs agents changelog 1 8 0 04 18 2023 or above To use the latest dynamic credentials features upgrade your agents to the latest version terraform cloud docs agents changelog You can use HCP Terraform s native OpenID Connect integration with Vault to use Vault backed dynamic credentials terraform cloud docs workspaces dynamic provider credentials vault backed with the GCP provider in your HCP Terraform runs Configuring the integration requires the following steps 1 Configure Vault Dynamic Provider Credentials configure vault dynamic provider credentials Set up a trust configuration between Vault and HCP Terraform create Vault roles and policies for your HCP Terraform workspaces and add environment variables to those workspaces 2 Configure the Vault GCP Secrets Engine configure vault gcp secrets engine Set up the GCP secrets engine in your Vault instance 3 Configure HCP Terraform configure hcp terraform Add additional environment variables to the HCP Terraform workspaces where you want to use Vault Backed Dynamic Credentials 4 Configure Terraform Providers configure terraform providers Configure your Terraform providers to work with Vault backed dynamic credentials Once you complete this setup HCP Terraform automatically authenticates with GCP via Vault generated credentials during the plan and apply phase of each run The GCP provider s authentication is only valid for the length of the plan or apply phase Configure Vault Dynamic Provider Credentials You must first set up Vault dynamic provider credentials before you can use Vault backed dynamic credentials This includes setting up the JWT auth backend in Vault configuring trust between HCP Terraform and Vault and populating the required environment variables in your HCP Terraform workspace See the setup instructions for Vault dynamic provider credentials terraform cloud docs workspaces dynamic provider credentials vault configuration Configure Vault GCP Secrets Engine Follow the instructions in the Vault documentation for setting up the GCP secrets engine in your Vault instance vault docs secrets gcp You can also do this configuration through Terraform Refer to our example Terraform configuration https github com hashicorp terraform dynamic credentials setup examples tree main vault backed gcp Important carefully consider the limitations and differences between each supported credential type in the GCP secrets engine These limitations carry over to HCP Terraform s usage of these credentials for authenticating the GCP provider Configure HCP Terraform Next you need to set certain environment variables in your HCP Terraform workspace to authenticate HCP Terraform with GCP using Vault backed dynamic credentials These variables are in addition to those you previously set while configuring Vault dynamic provider credentials configure vault dynamic provider credentials You can add these as workspace variables or as a variable set terraform cloud docs workspaces variables managing variables variable sets When you configure dynamic provider credentials with multiple provider configurations of the same type use either a default variable or a tagged alias variable name for each provider configuration Refer to Specifying Multiple Configurations specifying multiple configurations for more details Common Environment Variables The below variables apply to all GCP auth types Required Common Environment Variables Variable Value Notes TFC VAULT BACKED GCP AUTH br TFC VAULT BACKED GCP AUTH TAG br Default variable not supported true Requires v1 8 0 or later if self managing agents Must be present and set to true or HCP Terraform will not attempt to authenticate with GCP TFC VAULT BACKED GCP AUTH TYPE br TFC VAULT BACKED GCP AUTH TYPE TAG br TFC DEFAULT VAULT BACKED GCP AUTH TYPE Specifies the type of authentication to perform with GCP Must be one of the following roleset access token roleset service account key static account access token or static account service account key Requires v1 8 0 or later if self managing agents Optional Common Environment Variables You may need to set these variables depending on your use case Variable Value Notes TFC VAULT BACKED GCP MOUNT PATH br TFC VAULT BACKED GCP MOUNT PATH TAG br TFC DEFAULT VAULT BACKED GCP MOUNT PATH The mount path of the GCP secrets engine in Vault Requires v1 8 0 or later if self managing agents Defaults to gcp TFC VAULT BACKED GCP VAULT CONFIG br TFC VAULT BACKED GCP VAULT CONFIG TAG br TFC DEFAULT VAULT BACKED GCP VAULT CONFIG The name of the non default Vault configuration for workspaces using multiple Vault configurations terraform cloud docs workspaces dynamic provider credentials specifying multiple configurations Requires v1 12 0 or later if self managing agents Will fall back to using the default Vault configuration if not provided Roleset Specific Environment Variables These environment variables are only valid if the TFC VAULT BACKED GCP AUTH TYPE is roleset access token or roleset service account key Required Roleset Specific Environment Variables Variable Value Notes TFC VAULT BACKED GCP RUN VAULT ROLESET br TFC VAULT BACKED GCP RUN VAULT ROLESET TAG br TFC DEFAULT VAULT BACKED GCP RUN VAULT ROLESET The roleset to use in Vault Requires v1 8 0 or later if self managing agents Optional if TFC VAULT BACKED GCP PLAN VAULT ROLESET and TFC VAULT BACKED GCP APPLY VAULT ROLESET are both provided These variables are described below optional roleset specific environment variables Optional Roleset Specific Environment Variables You may need to set these variables depending on your use case Variable Value Notes TFC VAULT BACKED GCP PLAN VAULT ROLESET br TFC VAULT BACKED GCP PLAN VAULT ROLESET TAG br TFC DEFAULT VAULT BACKED GCP PLAN VAULT ROLESET The roleset to use for the plan phase of a run Requires v1 8 0 or later if self managing agents Will fall back to the value of TFC VAULT BACKED GCP RUN VAULT ROLESET if not provided TFC VAULT BACKED GCP APPLY VAULT ROLESET br TFC VAULT BACKED GCP APPLY VAULT ROLESET TAG br TFC DEFAULT VAULT BACKED GCP APPLY VAULT ROLESET The roleset to use for the apply phase of a run Requires v1 8 0 or later if self managing agents Will fall back to the value of TFC VAULT BACKED GCP RUN VAULT ROLESET if not provided Static Account Specific Environment Variables These environment variables are only valid if the TFC VAULT BACKED GCP AUTH TYPE is static account access token or static account service account key Required Static Account Specific Environment Variables Variable Value Notes TFC VAULT BACKED GCP RUN VAULT STATIC ACCOUNT br TFC VAULT BACKED GCP RUN VAULT STATIC ACCOUNT TAG br TFC DEFAULT VAULT BACKED GCP RUN VAULT STATIC ACCOUNT The static account to use in Vault Requires v1 8 0 or later if self managing agents Optional if TFC VAULT BACKED GCP PLAN VAULT STATIC ACCOUNT and TFC VAULT BACKED GCP APPLY VAULT STATIC ACCOUNT are both provided These variables are described below optional static account specific environment variables Optional Static Account Specific Environment Variables You may need to set these variables depending on your use case Variable Value Notes TFC VAULT BACKED GCP PLAN VAULT STATIC ACCOUNT br TFC VAULT BACKED GCP PLAN VAULT STATIC ACCOUNT TAG br TFC DEFAULT VAULT BACKED GCP PLAN VAULT STATIC ACCOUNT The static account to use for the plan phase of a run Requires v1 8 0 or later if self managing agents Will fall back to the value of TFC VAULT BACKED GCP RUN VAULT STATIC ACCOUNT if not provided TFC VAULT BACKED GCP APPLY VAULT STATIC ACCOUNT br TFC VAULT BACKED GCP APPLY VAULT STATIC ACCOUNT TAG br TFC DEFAULT VAULT BACKED GCP APPLY VAULT STATIC ACCOUNT The static account to use for the apply phase of a run Requires v1 8 0 or later if self managing agents Will fall back to the value of TFC VAULT BACKED GCP RUN VAULT STATIC ACCOUNT if not provided Configure Terraform Providers The final step is to directly configure your GCP and Vault providers Configure the GCP Provider Ensure you pass values for the project and region arguments into the provider configuration block Ensure you are not setting values or environment variables for GOOGLE CREDENTIALS or GOOGLE APPLICATION CREDENTIALS Otherwise these values may interfere with dynamic provider credentials Configure the Vault Provider If you were previously using the Vault provider to authenticate the GCP provider remove any existing usage of the GCP secrets engine from your Terraform Code This includes instances of vault generic secret https registry terraform io providers hashicorp vault latest docs data sources generic secret that you previously used to generate GCP credentials Specifying Multiple Configurations Important If you are self hosting HCP Terraform agents terraform cloud docs agents ensure your agents use v1 12 0 terraform cloud docs agents changelog 1 12 0 07 26 2023 or above To use the latest dynamic credentials features upgrade your agents to the latest version terraform cloud docs agents changelog You can add additional variables to handle multiple distinct Vault backed GCP setups enabling you to use multiple provider aliases terraform language providers configuration alias multiple provider configurations within the same workspace You can configure each set of credentials independently or use default values by configuring the variables prefixed with TFC DEFAULT For more details see Specifying Multiple Configurations terraform cloud docs workspaces dynamic provider credentials specifying multiple configurations Required Terraform Variable To use additional configurations add the following code to your Terraform configuration This lets HCP Terraform supply variable values that you can then use to map authentication and configuration details to the correct provider blocks hcl variable tfc vault backed gcp dynamic credentials description Object containing Vault backed GCP dynamic credentials configuration type object default object credentials string access token string aliases map object credentials string access token string Example Usage Access Token hcl provider google access token var tfc vault backed gcp dynamic credentials default access token provider google alias ALIAS1 access token var tfc vault backed gcp dynamic credentials aliases ALIAS1 access token Credentials hcl provider google credentials var tfc vault backed gcp dynamic credentials default credentials provider google alias ALIAS1 credentials var tfc vault backed gcp dynamic credentials aliases ALIAS1 credentials
terraform HCP Terraform workspace variables let you customize configurations modify Variables HCP Terraform workspace variables let you customize configurations modify Terraform s behavior setup dynamic provider credentials terraform cloud docs workspaces dynamic provider credentials and store information like static provider credentials page title Workspace Variables HCP Terraform Terraform s behavior and store information like provider credentials
--- page_title: Workspace Variables - HCP Terraform description: >- HCP Terraform workspace variables let you customize configurations, modify Terraform's behavior, and store information like provider credentials. --- # Variables HCP Terraform workspace variables let you customize configurations, modify Terraform's behavior, setup [dynamic provider credentials](/terraform/cloud-docs/workspaces/dynamic-provider-credentials), and store information like static provider credentials. You can set variables specifically for each workspace or you can create variable sets to reuse the same variables across multiple workspaces. For example, you could define a variable set of provider credentials and automatically apply it to all of the workspaces using that provider. You can use the command line to specify variable values for each plan or apply. Otherwise, HCP Terraform applies workspace variables to all runs within that workspace. [permissions-citation]: #intentionally-unused---keep-for-maintainers ## Types You can create both environment variables and Terraform variables in HCP Terraform. > **Hands-on:** Try the [Create and Use a Variable Sets](/terraform/tutorials/cloud-get-started/cloud-create-variable-set) and [Create Infrastructure](/terraform/tutorials/cloud-get-started/cloud-workspace-configure) tutorials to set environment and Terraform variables in HCP Terraform. ### Environment Variables HCP Terraform performs Terraform runs on disposable Linux worker VMs using a POSIX-compatible shell. Before running Terraform operations, HCP Terraform uses the `export` command to populate the shell with environment variables. Environment variables can store provider credentials and other data. Refer to your provider's Terraform Registry documentation for a full list of supported shell environment variables (e.g., authentication variables for [AWS](https://registry.terraform.io/providers/hashicorp/aws/latest/docs#environment-variables), [Google Cloud Platform](https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/getting_started#adding-credentials), and [Azure](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs#argument-reference)). Environment variables can also [modify Terraform's behavior](/terraform/cli/config/environment-variables). For example, `TF_LOG` enables detailed logs for debugging. #### Parallelism You can use the `TFE_PARALLELISM` environment variable when your infrastructure providers produce errors on concurrent operations or use non-standard rate limiting. The `TFE_PARALLELISM` variable sets the `-parallelism=<N>` flag for `terraform plan` and `terraform apply` ([more about `parallelism`](/terraform/internals/graph#walking-the-graph)). Valid values are between 1 and 256, inclusive, and the default is `10`. HCP Terraform agents do not support `TFE_PARALLELISM`, but you can specify flags as environment variables directly via [`TF_CLI_ARGS_name`](/terraform/cli/config/environment-variables#tf-cli-args). In these cases, use `TF_CLI_ARGS_plan="-parallelism=<N>"` or `TF_CLI_ARGS_apply="-parallelism=<N>"` instead. !> **Warning:** We recommend reading and understanding [Terraform parallelism](https://support.hashicorp.com/hc/en-us/articles/10348130482451) prior to setting `TFE_PARALLELISM`. You can also contact HashiCorp support for direct advice. #### Dynamic Credentials You can configure [dynamic credentials](/terraform/cloud-docs/workspaces/dynamic-provider-credentials) for certain providers using environment variables [at the workspace level](/terraform/cloud-docs/workspaces/variables/managing-variables#workspace-specific-variables) or using [variable sets](/terraform/cloud-docs/workspaces/variables/managing-variables#variable-sets). Dynamic credentials allows for using temporary per-run credentials and eliminates the need to manually rotate secrets. ### Terraform Variables Terraform variables refer to [input variables](/terraform/language/values/variables) that define parameters without hardcoding them into the configuration. For example, you could create variables that let users specify the number and type of Amazon Web Services EC2 instances they want to provision with a Terraform module. ```hcl variable "instance_count" { description = "Number of instances to provision." type = number default = 2 } ``` You can then reference this variable in your configuration. ```hcl module "ec2_instances" { source = "./modules/aws-instance" instance_count = var.instance_count ## ... } ``` If a required input variable is missing, Terraform plans in the workspace will fail and print an explanation in the log. ## Scope Each environment and Terraform variable can have one of the following scopes: | Scope | Description | Resources | | ----------------------------- | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Run-Specific | Apply to a specific run within a single workspace. | [Specify Run-Specific Variables](/terraform/cloud-docs/workspaces/variables/managing-variables#run-specific-variables) | | Workspace-Specific | Apply to a single workspace. | [Create Workspace-Specific Variables](/terraform/cloud-docs/workspaces/variables/managing-variables#workspace-specific-variables), [Loading Variables from Files](/terraform/cloud-docs/workspaces/variables/managing-variables#loading-variables-from-files), [Workspace-Specific Variables API](/terraform/cloud-docs/api-docs/workspace-variables). | | Workspace-Scoped Variable Set | Apply to multiple workspaces within the same organization. | [Create Variable Sets](/terraform/cloud-docs/workspaces/variables/managing-variables#variable-sets) and [Variable Sets API](/terraform/cloud-docs/api-docs/variable-sets) | | Project-Scoped Variable Set | Automatically applied to all current and future workspaces within a project. | [Create Variable Sets](/terraform/cloud-docs/workspaces/variables/managing-variables#variable-sets) and [Variable Sets API](/terraform/cloud-docs/api-docs/variable-sets) | | Global Variable Set | Automatically applied to all current and future workspaces within an organization. | [Create Variable Sets](/terraform/cloud-docs/workspaces/variables/managing-variables#variable-sets) and [Variable Sets API](/terraform/cloud-docs/api-docs/variable-sets) | ## Precedence > **Hands On:** The [Manage Multiple Variable Sets in HCP Terraform](/terraform/tutorials/cloud/cloud-multiple-variable-sets) tutorial shows how to manage multiple variable sets and demonstrates variable precedence. There may be cases when a workspace contains conflicting variables of the same type with the same key. HCP Terraform marks overwritten variables in the UI. HCP Terraform prioritizes and overwrites conflicting variables according to the following precedence: ### 1. Priority global variable sets If [prioritized](/terraform/cloud-docs/workspaces/variables#precedence-with-priority-variable-sets), variables in a global variable set have precedence over all other variables with the same key. ### 2. Priority project-scoped variable sets If [prioritized](/terraform/cloud-docs/workspaces/variables#precedence-with-priority-variable-sets), variables in a priority project-scoped variable set have precedence over variables with the same key set at a more specific scope. ### 3. Priority workspace-scoped variable sets If [prioritized](/terraform/cloud-docs/workspaces/variables#precedence-with-priority-variable-sets), variables in a priority workspace-scoped variable set have precedence over variables with the same key set at a more specific scope. ### 4. Command line argument variables When using a CLI workflow, variables applied to a run with either `-var` or `-var-file` overwrite workspace-specific and variable set variables that have the same key. ### 5. Local environment variables prefixed with `TF_VAR_` When using a CLI workflow, local environment variables prefixed with `TF_VAR_` (e.g., `TF_VAR_replicas`) overwrite workspace-specific, variable set, and `.auto.tfvars` file variables that have the same key. ### 6. Workspace-specific variables Workspace-specific variables always overwrite variables from variable sets that have the same key. Refer to [overwrite variables from variable sets](/terraform/cloud-docs/workspaces/variables/managing-variables#overwrite-variable-sets) for details. ### 7. Workspace-scoped variable sets Variables in workspace-scoped variable sets are only applied to a subset of workspaces in an organization. When workspace-scoped variable sets have conflicting variables, HCP Terraform compares the variable set names and uses values from the variable set with lexical precedence. Terraform and HCP Terraform operate on UTF-8 strings, and HCP Terraform sorts variable set names based on the lexical order of Unicode code points. For example, if you apply `A_Variable_Set` and `B_Variable_Set` to the same workspace, HCP Terraform will use any conflicting variables from `A_Variable_Set`. This is the case regardless of which variable set has been edited most recently. HCP Terraform only considers the lexical ordering of variable set names when determining precedence. ### 8. Project-scoped variable sets Workspace-specific variables and workspace-scoped variable sets always take precedence over project-scoped variable sets that are applied to workspaces within a project. Variables in project-scoped variable sets are only applied to the workspaces within the specified projects. When project-scoped variable sets have conflicting variables, HCP Terraform compares the variable set names and uses values from the variable set with lexical precedence. Terraform and HCP Terraform operate on UTF-8 strings, and HCP Terraform sorts variable set names based the on lexical order of Unicode code points. For example, if you apply `A_Variable_Set` and `B_Variable_Set` to the same project, HCP Terraform uses any conflicting variables from `A_Variable_Set`. This is the case regardless of which variable set has been edited most recently. HCP Terraform only considers the lexical ordering of variable set names when determining precedence. ### 9. Global variable sets Workspace and project-scoped variable sets always take precedence over global variable sets that are applied to all workspaces within an organization. Terraform does not allow global variable sets to contain variables with the same key, so they cannot conflict. ### 10. `*.auto.tfvars` variable files Variables in the HCP Terraform workspace and variables provided through the command line always overwrite variables with the same key from files ending in `.auto.tfvars`. ### 11. `terraform.tfvars` variable file Variables in the `.auto.tfvars` files take precedence over variables in the `terraform.tfvars` file. <Note> Although Terraform Cloud uses variables from `terraform.tfvars`, Terraform Enterprise currently ignores this file. </Note> ## Precedence with priority variable sets You can select to prioritize all values of the variables in a variable set. When a variable set is priority, the values take precedence over any variables with the same key set at a more specific scope. For example, variables in a priority global variable set would take precedence over all variables with the same key. If two priority variable sets with the same scope include the same variable key, HCP Terraform will determine precedence by the alphabetical order of the variable sets' names. While a priority variable set can enforce that Terraform variables use designated values, it does not guarantee that the configuration uses the variable. A user can still directly modify the Terraform configuration to remove usage of a variable and replace it with a hard-coded value. For stricter enforcement, we recommend using policy checks or run tasks. ## Precedence example Consider an example workspace that has the following variables applied: | (**Scope**) Source | Region | Var1 | Replicas | | ------------------------------------------ | ----------- | ---- | --------- | | Priority **global** variable set | `us-east-1` | | | | Priority **project-scoped** variable set | `us-east-2` | | | | Priority **workspace-scoped** variable set | `us-west-1` | | | | Command line argument | `us-west-2` | | `9` | | Local environment variable | | | `8` | | **Workspace-specific** variable | | `h` | `1` | | **Workspace-scoped** variable set | | `y` | `2` | | **Project-scoped** variable set | | | `3` | | **Global** variable set | | | `4` | When you trigger a run through the command line, these are the final values Terraform Cloud assigns to each variable: | Variable | Value | | -------- | ------------ | | Region | ` us-east-1` | | Var1 | `h` | | Replicas | `9`
terraform
page title Workspace Variables HCP Terraform description HCP Terraform workspace variables let you customize configurations modify Terraform s behavior and store information like provider credentials Variables HCP Terraform workspace variables let you customize configurations modify Terraform s behavior setup dynamic provider credentials terraform cloud docs workspaces dynamic provider credentials and store information like static provider credentials You can set variables specifically for each workspace or you can create variable sets to reuse the same variables across multiple workspaces For example you could define a variable set of provider credentials and automatically apply it to all of the workspaces using that provider You can use the command line to specify variable values for each plan or apply Otherwise HCP Terraform applies workspace variables to all runs within that workspace permissions citation intentionally unused keep for maintainers Types You can create both environment variables and Terraform variables in HCP Terraform Hands on Try the Create and Use a Variable Sets terraform tutorials cloud get started cloud create variable set and Create Infrastructure terraform tutorials cloud get started cloud workspace configure tutorials to set environment and Terraform variables in HCP Terraform Environment Variables HCP Terraform performs Terraform runs on disposable Linux worker VMs using a POSIX compatible shell Before running Terraform operations HCP Terraform uses the export command to populate the shell with environment variables Environment variables can store provider credentials and other data Refer to your provider s Terraform Registry documentation for a full list of supported shell environment variables e g authentication variables for AWS https registry terraform io providers hashicorp aws latest docs environment variables Google Cloud Platform https registry terraform io providers hashicorp google latest docs guides getting started adding credentials and Azure https registry terraform io providers hashicorp azurerm latest docs argument reference Environment variables can also modify Terraform s behavior terraform cli config environment variables For example TF LOG enables detailed logs for debugging Parallelism You can use the TFE PARALLELISM environment variable when your infrastructure providers produce errors on concurrent operations or use non standard rate limiting The TFE PARALLELISM variable sets the parallelism N flag for terraform plan and terraform apply more about parallelism terraform internals graph walking the graph Valid values are between 1 and 256 inclusive and the default is 10 HCP Terraform agents do not support TFE PARALLELISM but you can specify flags as environment variables directly via TF CLI ARGS name terraform cli config environment variables tf cli args In these cases use TF CLI ARGS plan parallelism N or TF CLI ARGS apply parallelism N instead Warning We recommend reading and understanding Terraform parallelism https support hashicorp com hc en us articles 10348130482451 prior to setting TFE PARALLELISM You can also contact HashiCorp support for direct advice Dynamic Credentials You can configure dynamic credentials terraform cloud docs workspaces dynamic provider credentials for certain providers using environment variables at the workspace level terraform cloud docs workspaces variables managing variables workspace specific variables or using variable sets terraform cloud docs workspaces variables managing variables variable sets Dynamic credentials allows for using temporary per run credentials and eliminates the need to manually rotate secrets Terraform Variables Terraform variables refer to input variables terraform language values variables that define parameters without hardcoding them into the configuration For example you could create variables that let users specify the number and type of Amazon Web Services EC2 instances they want to provision with a Terraform module hcl variable instance count description Number of instances to provision type number default 2 You can then reference this variable in your configuration hcl module ec2 instances source modules aws instance instance count var instance count If a required input variable is missing Terraform plans in the workspace will fail and print an explanation in the log Scope Each environment and Terraform variable can have one of the following scopes Scope Description Resources Run Specific Apply to a specific run within a single workspace Specify Run Specific Variables terraform cloud docs workspaces variables managing variables run specific variables Workspace Specific Apply to a single workspace Create Workspace Specific Variables terraform cloud docs workspaces variables managing variables workspace specific variables Loading Variables from Files terraform cloud docs workspaces variables managing variables loading variables from files Workspace Specific Variables API terraform cloud docs api docs workspace variables Workspace Scoped Variable Set Apply to multiple workspaces within the same organization Create Variable Sets terraform cloud docs workspaces variables managing variables variable sets and Variable Sets API terraform cloud docs api docs variable sets Project Scoped Variable Set Automatically applied to all current and future workspaces within a project Create Variable Sets terraform cloud docs workspaces variables managing variables variable sets and Variable Sets API terraform cloud docs api docs variable sets Global Variable Set Automatically applied to all current and future workspaces within an organization Create Variable Sets terraform cloud docs workspaces variables managing variables variable sets and Variable Sets API terraform cloud docs api docs variable sets Precedence Hands On The Manage Multiple Variable Sets in HCP Terraform terraform tutorials cloud cloud multiple variable sets tutorial shows how to manage multiple variable sets and demonstrates variable precedence There may be cases when a workspace contains conflicting variables of the same type with the same key HCP Terraform marks overwritten variables in the UI HCP Terraform prioritizes and overwrites conflicting variables according to the following precedence 1 Priority global variable sets If prioritized terraform cloud docs workspaces variables precedence with priority variable sets variables in a global variable set have precedence over all other variables with the same key 2 Priority project scoped variable sets If prioritized terraform cloud docs workspaces variables precedence with priority variable sets variables in a priority project scoped variable set have precedence over variables with the same key set at a more specific scope 3 Priority workspace scoped variable sets If prioritized terraform cloud docs workspaces variables precedence with priority variable sets variables in a priority workspace scoped variable set have precedence over variables with the same key set at a more specific scope 4 Command line argument variables When using a CLI workflow variables applied to a run with either var or var file overwrite workspace specific and variable set variables that have the same key 5 Local environment variables prefixed with TF VAR When using a CLI workflow local environment variables prefixed with TF VAR e g TF VAR replicas overwrite workspace specific variable set and auto tfvars file variables that have the same key 6 Workspace specific variables Workspace specific variables always overwrite variables from variable sets that have the same key Refer to overwrite variables from variable sets terraform cloud docs workspaces variables managing variables overwrite variable sets for details 7 Workspace scoped variable sets Variables in workspace scoped variable sets are only applied to a subset of workspaces in an organization When workspace scoped variable sets have conflicting variables HCP Terraform compares the variable set names and uses values from the variable set with lexical precedence Terraform and HCP Terraform operate on UTF 8 strings and HCP Terraform sorts variable set names based on the lexical order of Unicode code points For example if you apply A Variable Set and B Variable Set to the same workspace HCP Terraform will use any conflicting variables from A Variable Set This is the case regardless of which variable set has been edited most recently HCP Terraform only considers the lexical ordering of variable set names when determining precedence 8 Project scoped variable sets Workspace specific variables and workspace scoped variable sets always take precedence over project scoped variable sets that are applied to workspaces within a project Variables in project scoped variable sets are only applied to the workspaces within the specified projects When project scoped variable sets have conflicting variables HCP Terraform compares the variable set names and uses values from the variable set with lexical precedence Terraform and HCP Terraform operate on UTF 8 strings and HCP Terraform sorts variable set names based the on lexical order of Unicode code points For example if you apply A Variable Set and B Variable Set to the same project HCP Terraform uses any conflicting variables from A Variable Set This is the case regardless of which variable set has been edited most recently HCP Terraform only considers the lexical ordering of variable set names when determining precedence 9 Global variable sets Workspace and project scoped variable sets always take precedence over global variable sets that are applied to all workspaces within an organization Terraform does not allow global variable sets to contain variables with the same key so they cannot conflict 10 auto tfvars variable files Variables in the HCP Terraform workspace and variables provided through the command line always overwrite variables with the same key from files ending in auto tfvars 11 terraform tfvars variable file Variables in the auto tfvars files take precedence over variables in the terraform tfvars file Note Although Terraform Cloud uses variables from terraform tfvars Terraform Enterprise currently ignores this file Note Precedence with priority variable sets You can select to prioritize all values of the variables in a variable set When a variable set is priority the values take precedence over any variables with the same key set at a more specific scope For example variables in a priority global variable set would take precedence over all variables with the same key If two priority variable sets with the same scope include the same variable key HCP Terraform will determine precedence by the alphabetical order of the variable sets names While a priority variable set can enforce that Terraform variables use designated values it does not guarantee that the configuration uses the variable A user can still directly modify the Terraform configuration to remove usage of a variable and replace it with a hard coded value For stricter enforcement we recommend using policy checks or run tasks Precedence example Consider an example workspace that has the following variables applied Scope Source Region Var1 Replicas Priority global variable set us east 1 Priority project scoped variable set us east 2 Priority workspace scoped variable set us west 1 Command line argument us west 2 9 Local environment variable 8 Workspace specific variable h 1 Workspace scoped variable set y 2 Project scoped variable set 3 Global variable set 4 When you trigger a run through the command line these are the final values Terraform Cloud assigns to each variable Variable Value Region us east 1 Var1 h Replicas 9
terraform reusable variable sets that apply to multiple workspaces You can set variables specifically for each workspace or you can create variable sets to reuse the same variables across multiple workspaces Refer to the variables overview terraform cloud docs workspaces variables documentation for more information about variable types scope and precedence You can also set variable values specifically for each run on the command line Configure Terraform input variables and environment variables and create page title Managing Variables HCP Terraform Managing Variables
--- page_title: Managing Variables - HCP Terraform description: >- Configure Terraform input variables and environment variables and create reusable variable sets that apply to multiple workspaces. --- # Managing Variables You can set variables specifically for each workspace or you can create variable sets to reuse the same variables across multiple workspaces. Refer to the [variables overview](/terraform/cloud-docs/workspaces/variables) documentation for more information about variable types, scope, and precedence. You can also set variable values specifically for each run on the command line. You can create and edit workspace-specific variables through: - The HCP Terraform UI, as detailed below. - The Variables API for [workspace-specific variables](/terraform/cloud-docs/api-docs/workspace-variables) and [variable sets](/terraform/cloud-docs/api-docs/variable-sets). - The `tfe` provider's [`tfe_variable`](https://registry.terraform.io/providers/hashicorp/tfe/latest/docs/resources/variable) resource, which can be more convenient for bulk management. ## Permissions You must have [`read variables` permission](/terraform/cloud-docs/users-teams-organizations/permissions#general-workspace-permissions) to view the variables for a particular workspace and to view the variable sets in your organization. To create new variable sets and apply them to workspaces, you must be part of a team with [manage workspaces](/terraform/cloud-docs/users-teams-organizations/permissions#organization-owners) permissions. To create and edit workspace-specific variables within a workspace, you must have [read and write variables](/terraform/cloud-docs/users-teams-organizations/permissions#general-workspace-permissions) for that workspace. ## Run-Specific Variables Terraform 1.1 and later lets you set [Terraform variable](/terraform/cloud-docs/workspaces/variables#terraform-variables) values for a particular plan or apply on the command line. These variable values will overwrite workspace-specific and variable set variables with the same key. Refer to the [variable precedence](/terraform/cloud-docs/workspaces/variables#precedence) documentation for more details. You can set run-specific Terraform variable values by: - Specifying `-var` and `-var-file` arguments. For example: ``` terraform apply -var="key=value" -var-file="testing.tfvars" ``` - Creating local environment variables prefixed with `TF_VAR_`. For example, if you declare a variable called `replicas` in your configuration, you could create a local environment variable called `TF_VAR_replicas` and set it to a particular value. When you use the [CLI Workflow](/terraform/cloud-docs/run/cli), Terraform automatically identifies these environment variables and applies their values to the run. Refer to the [variables on the command line](/terraform/language/values/variables#variables-on-the-command-line) documentation for more details and examples. ## Workspace-Specific Variables To view and manage a workspace's variables, go to the workspace and click the **Variables** tab. The **Variables** page appears, showing all workspace-specific variables and variable sets applied to the workspace. This is where you can add, edit, and delete workspace-specific variables. You can also apply and remove variable sets from the workspace. The **Variables** page is not available for workspaces configured with `Local` [execution mode](/terraform/cloud-docs/workspaces/settings#execution-mode). HCP Terraform does not evaluate workspace variables or variable sets in local execution mode. ### Add a Variable To add a variable: 1. Go to the workspace **Variables** page and click **+ Add variable** in the **Workspace Variables** section. 1. Choose a variable category (Terraform or environment), optionally mark the variable as [sensitive](#sensitive-values), and enter a variable key, value, and optional description. For Terraform variables only, you can check the **HCL** checkbox to enter a value in HashiCorp Configuration Language. Refer to [variable values and format](#variable-values-and-format) for variable limits, allowable values, and formatting. 1. Click **Save variable**. The variable now appears in the list of the workspace's variables and HCP Terraform will apply it to runs. ### Edit a Variable To edit a variable: 1. Click the ellipses next to the variable you want to edit and select **Edit**. 1. Make any desired changes and click **Save variable**. ### Delete a Variable To delete a variable: 1. Click the ellipses next to the variable you want to delete and select **Delete**. 1. Click **Yes, delete variable** to confirm your action. ## Loading Variables from Files You can set [Terraform variable](/terraform/cloud-docs/workspaces/variables#terraform-variables) values by providing any number of [files ending in `.auto.tfvars`](/terraform/language/values/variables#variable-files) to workspaces that use Terraform 0.10.0 or later. When you trigger a run, Terraform automatically loads and uses the variables defined in these files. If any variable from the workspace has the same key as a variable in the file, the workspace variable overwrites variable from the file. You can only do this with files ending in `auto.tfvars` or `terraform.tfvars`. You can apply other types of `.tfvars` files [using the command line](#run-specific-variables) for each run. ~> **Note:** HCP Terraform loads variables from files ending in `auto.tfvars` for each Terraform run, but does not automatically persist those variables to the HCP Terraform workspace or display them in the **Variables** section of the workspace UI. ## Variable Sets > **Hands On:** Try the [Manage Variable Sets in HCP Terraform tutorial](/terraform/tutorials/cloud/cloud-multiple-variable-sets) tutorial. Only members of the [Owners Team](/terraform/cloud-docs/users-teams-organizations/permissions#organization-owners) or members of a team with the [Manage all projects](/terraform/cloud-docs/users-teams-organizations/permissions#manage-all-projects) or [Manage all workspaces](/terraform/cloud-docs/users-teams-organizations/permissions#manage-all-workspaces) permission can create, update, and delete variable sets. HCP Terraform does not evaluate variable sets during Terraform runs for workspaces configured with `Local` [execution mode](/terraform/cloud-docs/workspaces/settings#execution-mode). To view variable sets for your organization, click **Settings**, then click **Variable sets**. The **Variable sets** page appears, listing all of the organization's variable sets. Click on a variable set to open it and review details about its variables and scoping. ### Create Variable Sets To create a variable set: 1. Go to the **Variable Sets** page for your organization and click **Create variable set**. The **Create a new variable set** page appears. 1. Choose a descriptive **Name** for the variable set. You can use any combination of numbers, letters, and characters. 1. Write an optional **Description** that tells other users about the purpose of the variable set and what it contains. 1. Choose a variable set scope: - **Apply globally:** HCP Terraform will automatically apply this global variable set to all existing and future workspaces. - **Apply to specific projects and workspaces:** Use the text fields to search for and select workspaces and/or projects to apply this variable set to. This affects all current and future workspaces for any selected projects. After creation, users can also [add this variable set to their workspaces](#apply-or-remove-variable-sets-from-inside-a-workspace). 1. Add one or more variables: Click **+ Add variable**, choose a variable type (Terraform or environment), optionally mark the variable as [sensitive](#sensitive-values), and enter a variable name, value, and optional description. Then, click **Save variable**. Refer to [variable values and format](#variable-values-and-format) for variable limits, allowable values, and formatting. ~> **Note:** HCP Terraform will error if you try to declare variables with the same key in multiple global variable sets. 1. Click **Create variable set.** HCP Terraform adds the new variable set to any specified workspaces and displays it on the **Variable Sets** page. ### Edit Variable Sets To edit or remove a variable set: 1. Go to the organization's settings and then click **Variable Sets**. The **Variable sets** page appears. 1. Click the variable set you want to edit. That specific variable set page appears, where you can change the variable set settings. Refer to [create variable sets](#create-variable-sets) for details. ### Delete Variable Sets Deleting a variable set can be a disruptive action, especially if the variables are required to execute runs. We recommend informing organization and workspace owners before removing a variable set. To delete a variable set: 1. Click **Settings**, then click **Variable Sets**. The **Variable sets** page appears. 1. Select **Delete variable set**. Enter the variable set name and click **Delete variable set** to confirm this action. HCP Terraform deletes the variable set and removes it from all workspaces. Runs within those workspaces will no longer use the variables from the variable set. ### Apply or Remove Variable Sets From Inside a Workspace To apply a variable set to a specific workspace: 1. Navigate to the workspace and click the **Variables** tab. The **Variables** page appears, showing all workspace-specific variables and variable sets applied to the workspace. 1. In the **Variable sets** section, click **Apply Variable Set**. Select the variable set you want to apply to your workspace, and click **Apply variable set**. The variable set appears in the workspace's variable sets list and HCP Terraform will now apply the variables to runs. To remove a variable set from within a workspace: 1. Navigate to the workspace and click the **Variables** tab. The **Variables** page appears, showing all workspace-specific variables and variable sets applied to the workspace. 1. Click the ellipses button next to the variable set and select **Remove variable set**. 1. Click **Remove variable set** in the dialog box. HCP Terraform removes the variable set from this workspace, but it remains available to other workspaces in the organization. ## Overwrite Variable Sets You can overwrite variables defined in variable sets within a workspace. For example, you may want to use a different set of provider credentials in a specific workspace. To overwrite a variable from a variable set, [create a new workspace-specific variable](#workspace-specific-variables) of the same type with the same key. HCP Terraform marks any variables that you overwrite with a yellow **OVERWRITTEN** flag. When you click the overwritten variable, HCP Terraform highlights the variable it will use during runs. Variables within a variable set can also automatically overwrite variables with the same key in other variable sets applied to the same workspace. Though variable sets are created for the organization, these overwrites occur within each workspace. Refer to [variable precedence](/terraform/cloud-docs/workspaces/variables#precedence) for more details. ## Priority Variable Sets The values in priority variable sets overwrite any variables with the same key set at more specific scopes. This includes variables set using command line flags, or through`.*auto.tfvars` and `terraform.tfvars` files. It is still possible for a user to directly modify the Terraform configuration and remove usage of a variable and replace it with a hard coded value. For stricter enforcement, we recommend using policy checks or run tasks. Refer to [variable precedence](/terraform/cloud-docs/workspaces/variables#precedence-with-priority-variable-sets) for more details. ## Variable Values and Format The limits, allowable values, and required format are the same for both workspace-specific variables and variable sets. ### Security HCP Terraform encrypts all variable values securely using [Vault's transit backend](/vault/docs/secrets/transit) prior to saving them. This ensures that no out-of-band party can read these values without proper authorization. However, HCP Terraform stores variable [descriptions](#variable-description) in plain text, so be careful with the information you save in a variable description. We also recommend passing credentials to Terraform as environment variables instead of Terraform variables when possible, since Terraform runs receive the full text of all Terraform variable values, including [sensitive](#sensitive-values) ones. It may print the values in logs and state files if the configuration sends the value to an output or a resource parameter. Sentinel mocks downloaded from runs will also contain the sensitive values of Terraform variables. Although HCP Terraform does not store environment variables in state, it can include them in log files if `TF_LOG` is set to `TRACE`. #### Dynamic Credentials An alternative to passing static credentials for some providers is to use [dynamic credentials](/terraform/cloud-docs/workspaces/dynamic-provider-credentials). Dynamic credentials allows for using temporary per-run credentials and eliminates the need to manually rotate secrets. ### Character Limits The following limits apply to variables: | Component | Limit | | ----------- | -------------- | | description | 512 characters | | key | 128 characters | | value | 256 kilobytes | ### Multi-Line Text You can type or paste multi-line text into variable value text fields. ### HashiCorp Configuration Language (HCL) You can use HCL for Terraform variables, but not for environment variables. The same Terraform version that performs runs in the workspace will interpret the HCL. Variable values are strings by default. To enter list or map values, click the variable’s **HCL** checkbox (visible when editing) and enter the value with the same HCL syntax you would use when writing Terraform code. For example: ```hcl { us-east-1 = "image-1234" us-west-2 = "image-4567" } ``` ### Sensitive Values !> **Warning:** There are some cases when even sensitive variables are included in logs and state files. Refer to [security](#security) for more information. Terraform often needs cloud provider credentials and other sensitive information that should not be widely available within your organization. To protect these secrets, you can mark any Terraform or environment variable as sensitive data by clicking its **Sensitive** checkbox that is visible during editing. Marking a variable as sensitive makes it write-only and prevents all users (including you) from viewing its value in the HCP Terraform UI or reading it through the Variables API endpoint. Users with permission to read and write variables can set new values for sensitive variables, but other attributes of a sensitive variable cannot be modified. To update other attributes, delete the variable and create a new variable to replace it. [permissions-citation]: #intentionally-unused---keep-for-maintainers ### Variable Description !> **Warning:** Variable descriptions are not encrypted, so do not include any sensitive information. Variable descriptions are optional, and help distinguish between similarly named variables. They are only shown on the **Variables** page and are completely independent from any variable descriptions declared in Terraform CLI.
terraform
page title Managing Variables HCP Terraform description Configure Terraform input variables and environment variables and create reusable variable sets that apply to multiple workspaces Managing Variables You can set variables specifically for each workspace or you can create variable sets to reuse the same variables across multiple workspaces Refer to the variables overview terraform cloud docs workspaces variables documentation for more information about variable types scope and precedence You can also set variable values specifically for each run on the command line You can create and edit workspace specific variables through The HCP Terraform UI as detailed below The Variables API for workspace specific variables terraform cloud docs api docs workspace variables and variable sets terraform cloud docs api docs variable sets The tfe provider s tfe variable https registry terraform io providers hashicorp tfe latest docs resources variable resource which can be more convenient for bulk management Permissions You must have read variables permission terraform cloud docs users teams organizations permissions general workspace permissions to view the variables for a particular workspace and to view the variable sets in your organization To create new variable sets and apply them to workspaces you must be part of a team with manage workspaces terraform cloud docs users teams organizations permissions organization owners permissions To create and edit workspace specific variables within a workspace you must have read and write variables terraform cloud docs users teams organizations permissions general workspace permissions for that workspace Run Specific Variables Terraform 1 1 and later lets you set Terraform variable terraform cloud docs workspaces variables terraform variables values for a particular plan or apply on the command line These variable values will overwrite workspace specific and variable set variables with the same key Refer to the variable precedence terraform cloud docs workspaces variables precedence documentation for more details You can set run specific Terraform variable values by Specifying var and var file arguments For example terraform apply var key value var file testing tfvars Creating local environment variables prefixed with TF VAR For example if you declare a variable called replicas in your configuration you could create a local environment variable called TF VAR replicas and set it to a particular value When you use the CLI Workflow terraform cloud docs run cli Terraform automatically identifies these environment variables and applies their values to the run Refer to the variables on the command line terraform language values variables variables on the command line documentation for more details and examples Workspace Specific Variables To view and manage a workspace s variables go to the workspace and click the Variables tab The Variables page appears showing all workspace specific variables and variable sets applied to the workspace This is where you can add edit and delete workspace specific variables You can also apply and remove variable sets from the workspace The Variables page is not available for workspaces configured with Local execution mode terraform cloud docs workspaces settings execution mode HCP Terraform does not evaluate workspace variables or variable sets in local execution mode Add a Variable To add a variable 1 Go to the workspace Variables page and click Add variable in the Workspace Variables section 1 Choose a variable category Terraform or environment optionally mark the variable as sensitive sensitive values and enter a variable key value and optional description For Terraform variables only you can check the HCL checkbox to enter a value in HashiCorp Configuration Language Refer to variable values and format variable values and format for variable limits allowable values and formatting 1 Click Save variable The variable now appears in the list of the workspace s variables and HCP Terraform will apply it to runs Edit a Variable To edit a variable 1 Click the ellipses next to the variable you want to edit and select Edit 1 Make any desired changes and click Save variable Delete a Variable To delete a variable 1 Click the ellipses next to the variable you want to delete and select Delete 1 Click Yes delete variable to confirm your action Loading Variables from Files You can set Terraform variable terraform cloud docs workspaces variables terraform variables values by providing any number of files ending in auto tfvars terraform language values variables variable files to workspaces that use Terraform 0 10 0 or later When you trigger a run Terraform automatically loads and uses the variables defined in these files If any variable from the workspace has the same key as a variable in the file the workspace variable overwrites variable from the file You can only do this with files ending in auto tfvars or terraform tfvars You can apply other types of tfvars files using the command line run specific variables for each run Note HCP Terraform loads variables from files ending in auto tfvars for each Terraform run but does not automatically persist those variables to the HCP Terraform workspace or display them in the Variables section of the workspace UI Variable Sets Hands On Try the Manage Variable Sets in HCP Terraform tutorial terraform tutorials cloud cloud multiple variable sets tutorial Only members of the Owners Team terraform cloud docs users teams organizations permissions organization owners or members of a team with the Manage all projects terraform cloud docs users teams organizations permissions manage all projects or Manage all workspaces terraform cloud docs users teams organizations permissions manage all workspaces permission can create update and delete variable sets HCP Terraform does not evaluate variable sets during Terraform runs for workspaces configured with Local execution mode terraform cloud docs workspaces settings execution mode To view variable sets for your organization click Settings then click Variable sets The Variable sets page appears listing all of the organization s variable sets Click on a variable set to open it and review details about its variables and scoping Create Variable Sets To create a variable set 1 Go to the Variable Sets page for your organization and click Create variable set The Create a new variable set page appears 1 Choose a descriptive Name for the variable set You can use any combination of numbers letters and characters 1 Write an optional Description that tells other users about the purpose of the variable set and what it contains 1 Choose a variable set scope Apply globally HCP Terraform will automatically apply this global variable set to all existing and future workspaces Apply to specific projects and workspaces Use the text fields to search for and select workspaces and or projects to apply this variable set to This affects all current and future workspaces for any selected projects After creation users can also add this variable set to their workspaces apply or remove variable sets from inside a workspace 1 Add one or more variables Click Add variable choose a variable type Terraform or environment optionally mark the variable as sensitive sensitive values and enter a variable name value and optional description Then click Save variable Refer to variable values and format variable values and format for variable limits allowable values and formatting Note HCP Terraform will error if you try to declare variables with the same key in multiple global variable sets 1 Click Create variable set HCP Terraform adds the new variable set to any specified workspaces and displays it on the Variable Sets page Edit Variable Sets To edit or remove a variable set 1 Go to the organization s settings and then click Variable Sets The Variable sets page appears 1 Click the variable set you want to edit That specific variable set page appears where you can change the variable set settings Refer to create variable sets create variable sets for details Delete Variable Sets Deleting a variable set can be a disruptive action especially if the variables are required to execute runs We recommend informing organization and workspace owners before removing a variable set To delete a variable set 1 Click Settings then click Variable Sets The Variable sets page appears 1 Select Delete variable set Enter the variable set name and click Delete variable set to confirm this action HCP Terraform deletes the variable set and removes it from all workspaces Runs within those workspaces will no longer use the variables from the variable set Apply or Remove Variable Sets From Inside a Workspace To apply a variable set to a specific workspace 1 Navigate to the workspace and click the Variables tab The Variables page appears showing all workspace specific variables and variable sets applied to the workspace 1 In the Variable sets section click Apply Variable Set Select the variable set you want to apply to your workspace and click Apply variable set The variable set appears in the workspace s variable sets list and HCP Terraform will now apply the variables to runs To remove a variable set from within a workspace 1 Navigate to the workspace and click the Variables tab The Variables page appears showing all workspace specific variables and variable sets applied to the workspace 1 Click the ellipses button next to the variable set and select Remove variable set 1 Click Remove variable set in the dialog box HCP Terraform removes the variable set from this workspace but it remains available to other workspaces in the organization Overwrite Variable Sets You can overwrite variables defined in variable sets within a workspace For example you may want to use a different set of provider credentials in a specific workspace To overwrite a variable from a variable set create a new workspace specific variable workspace specific variables of the same type with the same key HCP Terraform marks any variables that you overwrite with a yellow OVERWRITTEN flag When you click the overwritten variable HCP Terraform highlights the variable it will use during runs Variables within a variable set can also automatically overwrite variables with the same key in other variable sets applied to the same workspace Though variable sets are created for the organization these overwrites occur within each workspace Refer to variable precedence terraform cloud docs workspaces variables precedence for more details Priority Variable Sets The values in priority variable sets overwrite any variables with the same key set at more specific scopes This includes variables set using command line flags or through auto tfvars and terraform tfvars files It is still possible for a user to directly modify the Terraform configuration and remove usage of a variable and replace it with a hard coded value For stricter enforcement we recommend using policy checks or run tasks Refer to variable precedence terraform cloud docs workspaces variables precedence with priority variable sets for more details Variable Values and Format The limits allowable values and required format are the same for both workspace specific variables and variable sets Security HCP Terraform encrypts all variable values securely using Vault s transit backend vault docs secrets transit prior to saving them This ensures that no out of band party can read these values without proper authorization However HCP Terraform stores variable descriptions variable description in plain text so be careful with the information you save in a variable description We also recommend passing credentials to Terraform as environment variables instead of Terraform variables when possible since Terraform runs receive the full text of all Terraform variable values including sensitive sensitive values ones It may print the values in logs and state files if the configuration sends the value to an output or a resource parameter Sentinel mocks downloaded from runs will also contain the sensitive values of Terraform variables Although HCP Terraform does not store environment variables in state it can include them in log files if TF LOG is set to TRACE Dynamic Credentials An alternative to passing static credentials for some providers is to use dynamic credentials terraform cloud docs workspaces dynamic provider credentials Dynamic credentials allows for using temporary per run credentials and eliminates the need to manually rotate secrets Character Limits The following limits apply to variables Component Limit description 512 characters key 128 characters value 256 kilobytes Multi Line Text You can type or paste multi line text into variable value text fields HashiCorp Configuration Language HCL You can use HCL for Terraform variables but not for environment variables The same Terraform version that performs runs in the workspace will interpret the HCL Variable values are strings by default To enter list or map values click the variable s HCL checkbox visible when editing and enter the value with the same HCL syntax you would use when writing Terraform code For example hcl us east 1 image 1234 us west 2 image 4567 Sensitive Values Warning There are some cases when even sensitive variables are included in logs and state files Refer to security security for more information Terraform often needs cloud provider credentials and other sensitive information that should not be widely available within your organization To protect these secrets you can mark any Terraform or environment variable as sensitive data by clicking its Sensitive checkbox that is visible during editing Marking a variable as sensitive makes it write only and prevents all users including you from viewing its value in the HCP Terraform UI or reading it through the Variables API endpoint Users with permission to read and write variables can set new values for sensitive variables but other attributes of a sensitive variable cannot be modified To update other attributes delete the variable and create a new variable to replace it permissions citation intentionally unused keep for maintainers Variable Description Warning Variable descriptions are not encrypted so do not include any sensitive information Variable descriptions are optional and help distinguish between similarly named variables They are only shown on the Variables page and are completely independent from any variable descriptions declared in Terraform CLI
terraform page title Permissions HCP Terraform permissions and what permissions you can grant to users BEGIN TFC only name pnp callout Learn the difference between workspace level and organization level Permissions
--- page_title: Permissions - HCP Terraform description: >- Learn the difference between workspace-level and organization-level permissions and what permissions you can grant to users. --- # Permissions <!-- BEGIN: TFC:only name:pnp-callout --> -> **Note:** Team management is available in HCP Terraform **Standard** Edition. [Learn more about HCP Terraform pricing here](https://www.hashicorp.com/products/terraform/pricing). <!-- END: TFC:only name:pnp-callout --> [permissions-citation]: #intentionally-unused---keep-for-maintainers > **Hands-on:** Try the [Manage Permissions in HCP Terraform](/terraform/tutorials/cloud/cloud-permissions?utm_source=WEBSITE&utm_medium=WEB_IO&utm_offer=ARTICLE_PAGE&utm_content=DOCS) tutorial. HCP Terraform's access model is team-based. In order to perform an action within an HCP Terraform organization, users must belong to a team that has been granted the appropriate permissions. The permissions model is split into organization-level, project-level, and workspace-level permissions. Additionally, every organization has a special team named "owners", whose members have maximal permissions within the organization. ## Organization Owners Every organization has a special "owners" team. Members of this team are often referred to as "organization owners". Organization owners have every available permission within the organization. This includes all organization-level permissions, and the highest level of workspace permissions on every workspace. There are also some actions within an organization that are only available to owners. These are generally actions that affect the permissions and membership of other teams, or are otherwise fundamental to the organization's security and integrity. Permissions for the owners team include: - Manage workspaces (refer to [Organization Permissions][] below; equivalent to admin permissions on every workspace) - Manage projects (refer to [Organization Permissions][] below; equivalent to admin permissions on every project and workspace) - Manage policies (refer to [Organization Permissions][] below) - Manage policy overrides (refer to [Organization Permissions][] below) - Manage VCS settings (refer to [Organization Permissions][] below) - Manage the private registry (refer to [Organization Permissions][] below) - Manage Membership (refer to [Organization Permissions][] below; invite or remove users from the organization itself, and manage the membership of its teams) - View all secret teams (refer to [Organization Permissions][] below) - Manage agents (refer to [Organization Permissions][] below) - Manage organization permissions (refer to [Organization Permissions][] below) - Manage all organization settings (owners only) - Manage organization billing (owners only, not applicable to Terraform Enterprise) - Delete organization (owners only) This list is not necessarily exhaustive. [Organization Permissions]: #organization-permissions ## Workspace Permissions [workspace]: /terraform/cloud-docs/workspaces Most of HCP Terraform's permissions system is focused on workspaces. In general, administrators want to delegate access to specific collections of infrastructure; HCP Terraform implements this by granting permissions to teams on a per-workspace basis. There are two ways to choose which permissions a given team has on a workspace: fixed permission sets, and custom permissions. Additionally, there is a special "admin" permission set that grants the highest level of permissions on a workspace. ### Implied Permissions Some permissions imply other permissions; for example, the run access plan permission also grants permission to read runs. If documentation or UI text states that an action requires a specific permission, it is also available for any permission that implies that permission. ### General Workspace Permissions [General Workspace Permissions]: #general-workspace-permissions The following workspace permissions can be granted to teams on a per-workspace basis. They can be granted via either fixed permission sets or custom workspace permissions. -> **Note:** Throughout the documentation, we refer to the specific permission an action requires (like "requires permission to apply runs") rather than the fixed permission set that includes that permission (like "requires write access"). - **Run access:** - **Read:** — Allows users to view information about remote Terraform runs, including the run history, the status of runs, the log output of each stage of a run (plan, apply, cost estimation, policy check), and configuration versions associated with a run. - **Plan:** — _Implies permission to read._ Allows users to queue Terraform plans in a workspace, including both speculative plans and normal plans. Normal plans must be approved by a user with permission to apply runs. This also allows users to comment on runs. - **Apply:** — _Implies permission to plan._ Allows users to approve and apply Terraform plans, causing changes to real infrastructure. - **Variable access:** - **No access:** — No access is granted to the values of Terraform variables and environment variables for the workspace. - **Read:** — Allows users to view the values of Terraform variables and environment variables for the workspace. Note that variables marked as sensitive are write-only, and can't be viewed by any user. - **Read and write:** — _Implies permission to read._ Allows users to edit the values of variables in the workspace. - **State access:** - **No access:** — No access is granted to the state file from the workspace. - **Read outputs only:** — Allows users to access values in the workspace's most recent Terraform state that have been explicitly marked as public outputs. Output values are often used as an interface between separate workspaces that manage loosely coupled collections of infrastructure, so their contents can be relevant to people who have no direct responsibility for the managed infrastructure but still indirectly use some of its functions. This permission is required to access the [State Version Outputs](/terraform/cloud-docs/api-docs/state-version-outputs) API endpoint. -> **Note:** **Read state versions** permission is required to use the `terraform output` command or the `terraform_remote_state` data source against the workspace. - **Read:** — _Implies permission to read outputs only._ Allows users to read complete state files from the workspace. State files are useful for identifying infrastructure changes over time, but often contain sensitive information. - **Read and write:** — _Implies permission to read._ Allows users to directly create new state versions in the workspace. Applying a remote Terraform run creates new state versions without this permission, but if the workspace's execution mode is set to "local", this permission is required for performing local runs. This permission is also required to use any of the Terraform CLI's state manipulation and maintenance commands against this workspace, including `terraform import`, `terraform taint`, and the various `terraform state` subcommands. - **Other controls:** - **Download Sentinel mocks:** — Allows users to download data from runs in the workspace in a format that can be used for developing Sentinel policies. This run data is very detailed, and often contains unredacted sensitive information. - **Manage Workspace Run Tasks:** — Allows users to associate or dissociate run tasks with the workspace. HCP Terraform creates Run Tasks at the organization level, where you can manually associate or dissociate them with specific workspaces. - **Lock/unlock workspace:** — Allows users to manually lock the workspace to temporarily prevent runs. When a workspace's execution mode is set to "local", users must have this permission to perform local CLI runs using the workspace's state. ### Fixed Permission Sets Fixed permission sets are bundles of specific permissions for workspaces, which you can use to delegate access to workspaces easily. Each permissions set targets a level of authority and responsibility for a given workspace's infrastructure. A permission set can grant permissions that recipients do not require but offer a balance of simplicity and utility. #### Workspace Admins Much like the owners team has full control over an organization, each workspace has a special "admin" permissions level that grants full control over the workspace. Members of a team with admin permissions on a workspace are sometimes called "workspace admins" for that workspace. Admin permissions include the highest level of general permissions for the workspace. There are also some permissions that are only available to workspace admins, which generally involve changing the workspace's settings or setting access levels for other teams. Workspace admins have all [General Workspace Permissions](#general-workspace-permissions), as well as the ability to do the following tasks: - Read and write workspace settings. This includes general settings, notification configurations, run triggers, and more. - Set or remove workspace permissions for visible teams. Workspace admins cannot view or manage teams with the [**Secret**](/terraform/cloud-docs/users-teams-organizations/teams/manage#team-visibility) visibility option enabled unless they are also organization owners. - Delete the workspace - Depending on the [organization's settings](/terraform/cloud-docs/users-teams-organizations/organizations#general), workspace admins may only be able to delete the workspace if it is not actively managing infrastructure. Refer to [Deleting a Workspace With Resources Under Management](/terraform/cloud-docs/workspaces/settings#deleting-a-workspace-with-resources-under-management) for details. #### Write The "write" permission set is for people who do most of the day-to-day work of provisioning and modifying managed infrastructure. Write access grants the following workspace permissions: - Run access - Apply - Variable access - Read and write - State access - Read and write - Other access - Lock/unlock workspace - Other access - Download Sentinel mocks See [General Workspace Permissions][] above for details about specific permissions. #### Plan The "plan" permission set is for people who might propose changes to managed infrastructure, but whose proposed changes should be approved before they are applied. Plan access grants the following workspace permissions: - Run access - Plan - Variable access - Read - State access - Read See [General Workspace Permissions][] above for details about specific permissions. #### Read The "read" permission set is for people who need to view information about the status and configuration of managed infrastructure in order to do their jobs, but aren't responsible for maintaining that infrastructure. Read access grants the following workspace permissions: - Run access - Read - Variable access - Read - State access - Read See [General Workspace Permissions][] above for details about specific permissions. ### Custom Workspace Permissions Custom permissions let you assign specific, finer-grained permissions to a team than the broader fixed permission sets provide. This enables more task-focused permission sets and tighter control of sensitive information. You can use custom permissions to assign any of the permissions listed above under [General Workspace Permissions][], with the exception of admin-only permissions. The minimum custom permissions set for a workspace is the permission to read runs; the only way to grant a team lower access is to not add them to the workspace at all. Some permissions - such as the runs permission - are tiered: you can assign one permission per category, since higher permissions include all of the capabilities of the lower ones. ## Project Permissions You can assign project-specific permissions to teams. ### Implied Permissions Some permissions imply other permissions. For example, permission to update a project also grants permission to read a project. If an action states that it requires a specific permission level, you can perform that action if your permissions _imply_ the stated permission level. ### General Project Permissions [General Project Permissions]: #general-project-permissions You can grant the following project permissions to teams on a per-project basis. You can grant these with either fixed permission sets or custom project permissions. -> **Note:** Throughout the documentation, we refer to the specific permission an action requires (like "requires permission to apply runs") rather than the fixed permission set that includes that permission (like "requires write access"). - **Project access:** - **Read:** — Allows users to view information about the project including the name. - **Update:** — _Implies permission to read._ Allows users to update the project name. - **Delete:** — _Implies permission to update._ Allows users to delete the project. - **Create Workspaces:** — Allow users to create workspaces in the project. This grants read access to all workspaces in the project. - **Delete Workspaces:** — Allows users to delete workspaces in the project. - Depending on the [organization's settings](/terraform/cloud-docs/users-teams-organizations/organizations#general), workspace admins may only be able to delete the workspace if it is not actively managing infrastructure. Refer to [Deleting a Workspace With Resources Under Management](/terraform/cloud-docs/workspaces/settings#deleting-a-workspace-with-resources-under-management) for details. - **Move Workspaces:** — Allows users to move workspaces out of the project. A user _must_ have this permission on both the source _and_ destination project to successfully move a workspace from one project to another. - **Team management:** - **None:** — No access to view teams assigned to the project. - **Read:** — Allows users to see teams assigned to the project for visible teams. - **Manage:** — _Implies permission to read._ Allows users to set or remove project permissions for visible teams. Project admins can not view or manage [secret teams](/terraform/cloud-docs/users-teams-organizations/teams/manage#team-visibility) unless they are also organization owners. See [General Workspace Permissions](#general-workspace-permissions)for the complete list of available permissions for a project's workspaces. ### Fixed Permission Sets Fixed permission sets are bundles of specific permissions for projects, which you can use to delegate access to a project's workspaces easily. #### Project Admin Each project has an "admin" permissions level that grants permissions for both the project and the workspaces that belong to that project. Members with admin permissions on a project are dubbed that project's "project admins". Members of teams with "admin" permissions for a project have [General Workspace Permissions](#general-workspace-permissions) for every workspace in the project, and the ability to: - Read and update project settings. - Delete the project. - Create workspaces in the project. - Move workspaces into or out of the project. This also requires project admin permissions for the source or destination project. - Grant or revoke project permissions for visible teams. Project admins **cannot** view or manage access for teams that are are [Secret](/terraform/cloud-docs/users-teams-organizations/teams/manage#team-visibility), unless those admins are also organization owners. #### Maintain The "maintain" permission is for people who need to manage existing infrastructure in a single project, while also granting the ability to create new workspaces in that project. Maintain access grants full control of everything in the project, including the following permissions: - Admin access for all workspaces in this project. - Create workspaces in this project. - Read the project name. - Lock and unlock all workspaces in this project. - Read and write variables for all workspaces in this project. - Access state for all workspaces in this project. - Approve runs for all workspaces in this project. #### Write The "write" permission set is for people who do most of the day-to-day work of provisioning and modifying managed infrastructure. Write access grants the following workspace permissions: - Read the project name. - Lock and unlock all workspaces in this project. - Read and write variables for all workspaces in this project. - Access state for all workspaces in this project. - Approve runs for all workspaces in this project. #### Read The "read" permission set is for people who need to view information about the status and configuration of managed infrastructure for their job function, but are not responsible for maintaining that infrastructure. Read access grants the permissions to: - Read the project name. - Read the workspaces in the project. ### Custom Project Permissions Custom permissions enable you to assign specific and granular permissions to a team. You can use custom permission sets to create task-focused permission sets and control sensitive information. You can create a set of custom permissions using any of the permissions listed under [General Project Permissions](#general-project-permissions). Some permissions, such as the project access permission, are tiered. You can only assign one permission per category because higher-level permissions include the capabilities of lower levels. ## Organization Permissions Separate from project and workspace permissions, you can grant teams permissions to manage or view certain resources or settings across an organization. To set these permissions for a team, go to your organization's **Settings**. Then click **Teams**, and select the team name from the list. The following organization permissions are available: ### Project permissions You must select a level of access for projects. #### None Members do not have access to projects or workspaces. You can grant permissions to individual projects or workspaces through [Project Permissions](/terraform/cloud-docs/users-teams-organizations/permissions#project-permissions) or [Workspace Permissions](/terraform/cloud-docs/users-teams-organizations/permissions#workspace-permissions). #### View all projects Members can view all projects within the organization. This lets users: - View project names in a given organization. #### Manage all projects Members can create and manage all projects and workspaces within the organization. In addition to the permissions granted by [“Manage all workspaces”](/terraform/cloud-docs/users-teams-organizations/permissions#manage-all-workspaces), this also lets users: - Manage other teams' access to all projects. - Create, edit, and delete projects (otherwise only available to organization owners). - Move workspaces between projects. ### Workspace permissions You must select a level of access for workspaces. #### None Members do not have access to projects or workspaces. You can grant permissions to individual projects or workspaces through [Project Permissions](/terraform/cloud-docs/users-teams-organizations/permissions#project-permissions) or [Workspace Permissions](/terraform/cloud-docs/users-teams-organizations/permissions#workspace-permissions). #### View all workspaces Members can view all workspaces within the organization. This lets users: - View information and features relevant to each workspaces (e.g. runs, state versions, variables). #### Manage all workspaces Members can create and manage all workspaces within the organization. This lets users: - Perform any action that requires admin permissions in those workspaces. - Create new workspaces within the organization's **Default Project**, an action that is otherwise only available to organization owners. - Create, update, and delete [Variable Sets](/terraform/cloud-docs/workspaces/variables/managing-variables#variable-sets). ### Manage Policies Allows members to create, edit, read, list and delete the organization's Sentinel policies. This permission implicitly gives permission to read runs on all workspaces, which is necessary to set enforcement of [policy sets](/terraform/cloud-docs/policy-enforcement/manage-policy-sets). ### Manage Run Tasks Allows members to create, edit, and delete run tasks on the organization. ### Manage Policy Overrides Allows members to override soft-mandatory policy checks. This permission implicitly gives permission to read runs on all workspaces, which is necessary to override policy checks. ### Manage VCS Settings Allows members to manage the set of [VCS providers](/terraform/cloud-docs/vcs) and [SSH keys](/terraform/cloud-docs/vcs#ssh-keys) available within the organization. ### Manage Agent Pools Allows members to create, edit, and delete agent pools within their organization. This permission implicitly grants access to read all workspaces, which is necessary for agent pool management. ### Manage Private Registry Allows members to publish and delete providers, modules, or both providers and modules in the organization's [private registry](/terraform/cloud-docs/registry). These permissions are otherwise only available to organization owners. ### Team Management Permissions HCP Terraform has three levels of team management permissions: manage membership, manage teams, and manage organization access. Each permission level grants users the ability to perform specific actions and each progressively requires prerequisite permissions. For example, to grant a user the manage teams permission, that user must already have manage membership permissions. To grant a user the manage organization access permission, a user must have both manage teams and manage membership permissions. #### Manage Membership Allows members to invite users to the organization, remove users from the organization, and add or remove users from teams within the organization. This permission grants the ability to view the list of users within the organization, and to view the organization access of other visible teams. It does not permit the creation of teams, the ability to modify the settings of existing teams, or the ability to view secret teams. In order to modify the membership of a team, a user with Manage Membership permissions must have visibility into the team (i.e. the team must be ["Visible"](/terraform/cloud-docs/users-teams-organizations/teams/manage#team-visibility), or the user must be on the team). In order to remove a user from the organization, the holder of this permission must have visibility into all of the teams which the user is a member of. ~> This permission is intended to allow owners of large organizations to delegate membership management to another trusted team, and should be granted to only teams of trusted users. **Assign with caution:** Users with this permission are able to add themselves to any visible team, and inherit the permissions of any visible team. #### Manage Teams Allows members to create, update, and delete teams, and generate, regenerate, and revoke tokens. This permission grants the ability to update a team's names, SSO IDs, and token management permissions, but does not allow access to organization settings. On its own, this permission does not allow users to create, update, delete, or otherwise access secret teams. The manage teams permission confers all permissions granted by the manage membership permission. This permission allows owners of large organizations to delegate team management to another trusted team. You should only grant it to teams of trusted users. ~> **Assign with caution**: Users with this permission can update or delete any visible team. Because this permission also confers the manage membership permission, a user with the manage teams permission can add themselves to any visible team. #### Manage Organization Access Allows members to update a team's organization access settings. On its own, this permission does not allow users to create, update, delete, or otherwise access secret teams. This permission confers all of the permissions granted by the manage teams and manage membership permissions. This permission allows owners of large organizations to delegate team management to another trusted team. You should only grant it to teams of trusted users. ~> **Assign with caution:** Members with this permission can update all organization access settings for any team visible to them. ### Include Secret Teams Allows members access to secret teams at the level permitted by that user's team permissions setting. This permission acts as a modifier to existing team management permissions. Members with this permission can access secret teams up to the level permitted by other team management permissions. For example, if a user has permission to include secret teams and [manage teams](/terraform/cloud-docs/users-teams-organizations/permissions#manage-teams), that user can create secret teams. ### Allow Member Token Management Allows owners and members with [manage teams](/terraform/cloud-docs/users-teams-organizations/permissions#manage-teams) permissions to enable and disable team token management for team members. This permission defaults to `true`. When member token management is enabled, members will be able to perform actions on team tokens, including generating and revoking a team token. When member token management is disabled, members will be unable to perform actions on team tokens, including generating and revoking a team token. ## Permissions Outside HCP Terraform's Scope This documentation only refers to permissions that are managed by HCP Terraform itself. Since HCP Terraform integrates with other systems, the permissions models of those systems can also be relevant to the overall security model of your HCP Terraform organization. For example: - When a workspace is connected to a VCS repository, anyone who can merge changes to that repository's main branch can indirectly queue plans in that workspace, regardless of whether they have explicit permission to queue plans or are even a member of your HCP Terraform organization. (And when auto-apply is enabled, merging changes will indirectly apply runs.) - If you use HCP Terraform's API to create a Slack bot for provisioning infrastructure, anyone able to issue commands to that Slack bot can implicitly act with that bot's permissions, regardless of their own membership and permissions in the HCP Terraform organization. - When a run task sends a request to an integrator, it provides an access token that provides access depending on the run task stage: - For post-plan, it provides access to the runs plan json and the run task callback - All access tokens created for run tasks have a lifetime of 10 minutes When integrating HCP Terraform with other systems, you are responsible for understanding the effects on your organization's security. An integrated system is able to delegate any level of access that it has been granted, so carefully consider the conditions and events that will cause it to delegate that access.
terraform
page title Permissions HCP Terraform description Learn the difference between workspace level and organization level permissions and what permissions you can grant to users Permissions BEGIN TFC only name pnp callout Note Team management is available in HCP Terraform Standard Edition Learn more about HCP Terraform pricing here https www hashicorp com products terraform pricing END TFC only name pnp callout permissions citation intentionally unused keep for maintainers Hands on Try the Manage Permissions in HCP Terraform terraform tutorials cloud cloud permissions utm source WEBSITE utm medium WEB IO utm offer ARTICLE PAGE utm content DOCS tutorial HCP Terraform s access model is team based In order to perform an action within an HCP Terraform organization users must belong to a team that has been granted the appropriate permissions The permissions model is split into organization level project level and workspace level permissions Additionally every organization has a special team named owners whose members have maximal permissions within the organization Organization Owners Every organization has a special owners team Members of this team are often referred to as organization owners Organization owners have every available permission within the organization This includes all organization level permissions and the highest level of workspace permissions on every workspace There are also some actions within an organization that are only available to owners These are generally actions that affect the permissions and membership of other teams or are otherwise fundamental to the organization s security and integrity Permissions for the owners team include Manage workspaces refer to Organization Permissions below equivalent to admin permissions on every workspace Manage projects refer to Organization Permissions below equivalent to admin permissions on every project and workspace Manage policies refer to Organization Permissions below Manage policy overrides refer to Organization Permissions below Manage VCS settings refer to Organization Permissions below Manage the private registry refer to Organization Permissions below Manage Membership refer to Organization Permissions below invite or remove users from the organization itself and manage the membership of its teams View all secret teams refer to Organization Permissions below Manage agents refer to Organization Permissions below Manage organization permissions refer to Organization Permissions below Manage all organization settings owners only Manage organization billing owners only not applicable to Terraform Enterprise Delete organization owners only This list is not necessarily exhaustive Organization Permissions organization permissions Workspace Permissions workspace terraform cloud docs workspaces Most of HCP Terraform s permissions system is focused on workspaces In general administrators want to delegate access to specific collections of infrastructure HCP Terraform implements this by granting permissions to teams on a per workspace basis There are two ways to choose which permissions a given team has on a workspace fixed permission sets and custom permissions Additionally there is a special admin permission set that grants the highest level of permissions on a workspace Implied Permissions Some permissions imply other permissions for example the run access plan permission also grants permission to read runs If documentation or UI text states that an action requires a specific permission it is also available for any permission that implies that permission General Workspace Permissions General Workspace Permissions general workspace permissions The following workspace permissions can be granted to teams on a per workspace basis They can be granted via either fixed permission sets or custom workspace permissions Note Throughout the documentation we refer to the specific permission an action requires like requires permission to apply runs rather than the fixed permission set that includes that permission like requires write access Run access Read Allows users to view information about remote Terraform runs including the run history the status of runs the log output of each stage of a run plan apply cost estimation policy check and configuration versions associated with a run Plan Implies permission to read Allows users to queue Terraform plans in a workspace including both speculative plans and normal plans Normal plans must be approved by a user with permission to apply runs This also allows users to comment on runs Apply Implies permission to plan Allows users to approve and apply Terraform plans causing changes to real infrastructure Variable access No access No access is granted to the values of Terraform variables and environment variables for the workspace Read Allows users to view the values of Terraform variables and environment variables for the workspace Note that variables marked as sensitive are write only and can t be viewed by any user Read and write Implies permission to read Allows users to edit the values of variables in the workspace State access No access No access is granted to the state file from the workspace Read outputs only Allows users to access values in the workspace s most recent Terraform state that have been explicitly marked as public outputs Output values are often used as an interface between separate workspaces that manage loosely coupled collections of infrastructure so their contents can be relevant to people who have no direct responsibility for the managed infrastructure but still indirectly use some of its functions This permission is required to access the State Version Outputs terraform cloud docs api docs state version outputs API endpoint Note Read state versions permission is required to use the terraform output command or the terraform remote state data source against the workspace Read Implies permission to read outputs only Allows users to read complete state files from the workspace State files are useful for identifying infrastructure changes over time but often contain sensitive information Read and write Implies permission to read Allows users to directly create new state versions in the workspace Applying a remote Terraform run creates new state versions without this permission but if the workspace s execution mode is set to local this permission is required for performing local runs This permission is also required to use any of the Terraform CLI s state manipulation and maintenance commands against this workspace including terraform import terraform taint and the various terraform state subcommands Other controls Download Sentinel mocks Allows users to download data from runs in the workspace in a format that can be used for developing Sentinel policies This run data is very detailed and often contains unredacted sensitive information Manage Workspace Run Tasks Allows users to associate or dissociate run tasks with the workspace HCP Terraform creates Run Tasks at the organization level where you can manually associate or dissociate them with specific workspaces Lock unlock workspace Allows users to manually lock the workspace to temporarily prevent runs When a workspace s execution mode is set to local users must have this permission to perform local CLI runs using the workspace s state Fixed Permission Sets Fixed permission sets are bundles of specific permissions for workspaces which you can use to delegate access to workspaces easily Each permissions set targets a level of authority and responsibility for a given workspace s infrastructure A permission set can grant permissions that recipients do not require but offer a balance of simplicity and utility Workspace Admins Much like the owners team has full control over an organization each workspace has a special admin permissions level that grants full control over the workspace Members of a team with admin permissions on a workspace are sometimes called workspace admins for that workspace Admin permissions include the highest level of general permissions for the workspace There are also some permissions that are only available to workspace admins which generally involve changing the workspace s settings or setting access levels for other teams Workspace admins have all General Workspace Permissions general workspace permissions as well as the ability to do the following tasks Read and write workspace settings This includes general settings notification configurations run triggers and more Set or remove workspace permissions for visible teams Workspace admins cannot view or manage teams with the Secret terraform cloud docs users teams organizations teams manage team visibility visibility option enabled unless they are also organization owners Delete the workspace Depending on the organization s settings terraform cloud docs users teams organizations organizations general workspace admins may only be able to delete the workspace if it is not actively managing infrastructure Refer to Deleting a Workspace With Resources Under Management terraform cloud docs workspaces settings deleting a workspace with resources under management for details Write The write permission set is for people who do most of the day to day work of provisioning and modifying managed infrastructure Write access grants the following workspace permissions Run access Apply Variable access Read and write State access Read and write Other access Lock unlock workspace Other access Download Sentinel mocks See General Workspace Permissions above for details about specific permissions Plan The plan permission set is for people who might propose changes to managed infrastructure but whose proposed changes should be approved before they are applied Plan access grants the following workspace permissions Run access Plan Variable access Read State access Read See General Workspace Permissions above for details about specific permissions Read The read permission set is for people who need to view information about the status and configuration of managed infrastructure in order to do their jobs but aren t responsible for maintaining that infrastructure Read access grants the following workspace permissions Run access Read Variable access Read State access Read See General Workspace Permissions above for details about specific permissions Custom Workspace Permissions Custom permissions let you assign specific finer grained permissions to a team than the broader fixed permission sets provide This enables more task focused permission sets and tighter control of sensitive information You can use custom permissions to assign any of the permissions listed above under General Workspace Permissions with the exception of admin only permissions The minimum custom permissions set for a workspace is the permission to read runs the only way to grant a team lower access is to not add them to the workspace at all Some permissions such as the runs permission are tiered you can assign one permission per category since higher permissions include all of the capabilities of the lower ones Project Permissions You can assign project specific permissions to teams Implied Permissions Some permissions imply other permissions For example permission to update a project also grants permission to read a project If an action states that it requires a specific permission level you can perform that action if your permissions imply the stated permission level General Project Permissions General Project Permissions general project permissions You can grant the following project permissions to teams on a per project basis You can grant these with either fixed permission sets or custom project permissions Note Throughout the documentation we refer to the specific permission an action requires like requires permission to apply runs rather than the fixed permission set that includes that permission like requires write access Project access Read Allows users to view information about the project including the name Update Implies permission to read Allows users to update the project name Delete Implies permission to update Allows users to delete the project Create Workspaces Allow users to create workspaces in the project This grants read access to all workspaces in the project Delete Workspaces Allows users to delete workspaces in the project Depending on the organization s settings terraform cloud docs users teams organizations organizations general workspace admins may only be able to delete the workspace if it is not actively managing infrastructure Refer to Deleting a Workspace With Resources Under Management terraform cloud docs workspaces settings deleting a workspace with resources under management for details Move Workspaces Allows users to move workspaces out of the project A user must have this permission on both the source and destination project to successfully move a workspace from one project to another Team management None No access to view teams assigned to the project Read Allows users to see teams assigned to the project for visible teams Manage Implies permission to read Allows users to set or remove project permissions for visible teams Project admins can not view or manage secret teams terraform cloud docs users teams organizations teams manage team visibility unless they are also organization owners See General Workspace Permissions general workspace permissions for the complete list of available permissions for a project s workspaces Fixed Permission Sets Fixed permission sets are bundles of specific permissions for projects which you can use to delegate access to a project s workspaces easily Project Admin Each project has an admin permissions level that grants permissions for both the project and the workspaces that belong to that project Members with admin permissions on a project are dubbed that project s project admins Members of teams with admin permissions for a project have General Workspace Permissions general workspace permissions for every workspace in the project and the ability to Read and update project settings Delete the project Create workspaces in the project Move workspaces into or out of the project This also requires project admin permissions for the source or destination project Grant or revoke project permissions for visible teams Project admins cannot view or manage access for teams that are are Secret terraform cloud docs users teams organizations teams manage team visibility unless those admins are also organization owners Maintain The maintain permission is for people who need to manage existing infrastructure in a single project while also granting the ability to create new workspaces in that project Maintain access grants full control of everything in the project including the following permissions Admin access for all workspaces in this project Create workspaces in this project Read the project name Lock and unlock all workspaces in this project Read and write variables for all workspaces in this project Access state for all workspaces in this project Approve runs for all workspaces in this project Write The write permission set is for people who do most of the day to day work of provisioning and modifying managed infrastructure Write access grants the following workspace permissions Read the project name Lock and unlock all workspaces in this project Read and write variables for all workspaces in this project Access state for all workspaces in this project Approve runs for all workspaces in this project Read The read permission set is for people who need to view information about the status and configuration of managed infrastructure for their job function but are not responsible for maintaining that infrastructure Read access grants the permissions to Read the project name Read the workspaces in the project Custom Project Permissions Custom permissions enable you to assign specific and granular permissions to a team You can use custom permission sets to create task focused permission sets and control sensitive information You can create a set of custom permissions using any of the permissions listed under General Project Permissions general project permissions Some permissions such as the project access permission are tiered You can only assign one permission per category because higher level permissions include the capabilities of lower levels Organization Permissions Separate from project and workspace permissions you can grant teams permissions to manage or view certain resources or settings across an organization To set these permissions for a team go to your organization s Settings Then click Teams and select the team name from the list The following organization permissions are available Project permissions You must select a level of access for projects None Members do not have access to projects or workspaces You can grant permissions to individual projects or workspaces through Project Permissions terraform cloud docs users teams organizations permissions project permissions or Workspace Permissions terraform cloud docs users teams organizations permissions workspace permissions View all projects Members can view all projects within the organization This lets users View project names in a given organization Manage all projects Members can create and manage all projects and workspaces within the organization In addition to the permissions granted by Manage all workspaces terraform cloud docs users teams organizations permissions manage all workspaces this also lets users Manage other teams access to all projects Create edit and delete projects otherwise only available to organization owners Move workspaces between projects Workspace permissions You must select a level of access for workspaces None Members do not have access to projects or workspaces You can grant permissions to individual projects or workspaces through Project Permissions terraform cloud docs users teams organizations permissions project permissions or Workspace Permissions terraform cloud docs users teams organizations permissions workspace permissions View all workspaces Members can view all workspaces within the organization This lets users View information and features relevant to each workspaces e g runs state versions variables Manage all workspaces Members can create and manage all workspaces within the organization This lets users Perform any action that requires admin permissions in those workspaces Create new workspaces within the organization s Default Project an action that is otherwise only available to organization owners Create update and delete Variable Sets terraform cloud docs workspaces variables managing variables variable sets Manage Policies Allows members to create edit read list and delete the organization s Sentinel policies This permission implicitly gives permission to read runs on all workspaces which is necessary to set enforcement of policy sets terraform cloud docs policy enforcement manage policy sets Manage Run Tasks Allows members to create edit and delete run tasks on the organization Manage Policy Overrides Allows members to override soft mandatory policy checks This permission implicitly gives permission to read runs on all workspaces which is necessary to override policy checks Manage VCS Settings Allows members to manage the set of VCS providers terraform cloud docs vcs and SSH keys terraform cloud docs vcs ssh keys available within the organization Manage Agent Pools Allows members to create edit and delete agent pools within their organization This permission implicitly grants access to read all workspaces which is necessary for agent pool management Manage Private Registry Allows members to publish and delete providers modules or both providers and modules in the organization s private registry terraform cloud docs registry These permissions are otherwise only available to organization owners Team Management Permissions HCP Terraform has three levels of team management permissions manage membership manage teams and manage organization access Each permission level grants users the ability to perform specific actions and each progressively requires prerequisite permissions For example to grant a user the manage teams permission that user must already have manage membership permissions To grant a user the manage organization access permission a user must have both manage teams and manage membership permissions Manage Membership Allows members to invite users to the organization remove users from the organization and add or remove users from teams within the organization This permission grants the ability to view the list of users within the organization and to view the organization access of other visible teams It does not permit the creation of teams the ability to modify the settings of existing teams or the ability to view secret teams In order to modify the membership of a team a user with Manage Membership permissions must have visibility into the team i e the team must be Visible terraform cloud docs users teams organizations teams manage team visibility or the user must be on the team In order to remove a user from the organization the holder of this permission must have visibility into all of the teams which the user is a member of This permission is intended to allow owners of large organizations to delegate membership management to another trusted team and should be granted to only teams of trusted users Assign with caution Users with this permission are able to add themselves to any visible team and inherit the permissions of any visible team Manage Teams Allows members to create update and delete teams and generate regenerate and revoke tokens This permission grants the ability to update a team s names SSO IDs and token management permissions but does not allow access to organization settings On its own this permission does not allow users to create update delete or otherwise access secret teams The manage teams permission confers all permissions granted by the manage membership permission This permission allows owners of large organizations to delegate team management to another trusted team You should only grant it to teams of trusted users Assign with caution Users with this permission can update or delete any visible team Because this permission also confers the manage membership permission a user with the manage teams permission can add themselves to any visible team Manage Organization Access Allows members to update a team s organization access settings On its own this permission does not allow users to create update delete or otherwise access secret teams This permission confers all of the permissions granted by the manage teams and manage membership permissions This permission allows owners of large organizations to delegate team management to another trusted team You should only grant it to teams of trusted users Assign with caution Members with this permission can update all organization access settings for any team visible to them Include Secret Teams Allows members access to secret teams at the level permitted by that user s team permissions setting This permission acts as a modifier to existing team management permissions Members with this permission can access secret teams up to the level permitted by other team management permissions For example if a user has permission to include secret teams and manage teams terraform cloud docs users teams organizations permissions manage teams that user can create secret teams Allow Member Token Management Allows owners and members with manage teams terraform cloud docs users teams organizations permissions manage teams permissions to enable and disable team token management for team members This permission defaults to true When member token management is enabled members will be able to perform actions on team tokens including generating and revoking a team token When member token management is disabled members will be unable to perform actions on team tokens including generating and revoking a team token Permissions Outside HCP Terraform s Scope This documentation only refers to permissions that are managed by HCP Terraform itself Since HCP Terraform integrates with other systems the permissions models of those systems can also be relevant to the overall security model of your HCP Terraform organization For example When a workspace is connected to a VCS repository anyone who can merge changes to that repository s main branch can indirectly queue plans in that workspace regardless of whether they have explicit permission to queue plans or are even a member of your HCP Terraform organization And when auto apply is enabled merging changes will indirectly apply runs If you use HCP Terraform s API to create a Slack bot for provisioning infrastructure anyone able to issue commands to that Slack bot can implicitly act with that bot s permissions regardless of their own membership and permissions in the HCP Terraform organization When a run task sends a request to an integrator it provides an access token that provides access depending on the run task stage For post plan it provides access to the runs plan json and the run task callback All access tokens created for run tasks have a lifetime of 10 minutes When integrating HCP Terraform with other systems you are responsible for understanding the effects on your organization s security An integrated system is able to delegate any level of access that it has been granted so carefully consider the conditions and events that will cause it to delegate that access
terraform page title API Tokens HCP Terraform API Tokens Learn about the level of access granted by user team and organization API This topic describes the distinct types of API tokens you can use to authenticate with HCP Terraform tokens
--- page_title: API Tokens - HCP Terraform description: >- Learn about the level of access granted by user, team, and organization API tokens. --- # API Tokens This topic describes the distinct types of API tokens you can use to authenticate with HCP Terraform. Note that HCP Terraform only displays API tokens once when you initially create them and are obfuscated thereafter. If the token is lost, it must be regenerated. Refer to [Team Token API](/terraform/cloud-docs/api-docs/team-tokens) and [Organization Token API](/terraform/cloud-docs/api-docs/organization-tokens) for additional information about using the APIs. ## User API Tokens API tokens may belong directly to a user. User tokens are the most flexible token type because they inherit permissions from the user they are associated with. For more information on user tokens and how to generate them, see the [Users](/terraform/cloud-docs/users-teams-organizations/users#api-tokens) documentation. ## Team API Tokens API tokens may belong to a specific team. Team API tokens allow access to the workspaces that the team has access to, without being tied to any specific user. Navigate to the **Organization settings > API Tokens > Team Token** tab to manage API tokens for a team or create new team tokens. Each team can have **one** valid API token at a time. When a token is regenerated, the previous token immediately becomes invalid. Owners and users with [manage teams](/terraform/cloud-docs/users-teams-organizations/permissions#manage-teams) permissions have the ability to enable and disable team token management for a team, which limits the actions that team members can take on a team token. Refer to [Allow Member Token Management](/terraform/cloud-docs/users-teams-organizations/permissions#allow-member-token-management) for more information. Team API tokens are designed for performing API operations on workspaces. They have the same access level to the workspaces the team has access to. For example, if a team has permission to apply runs on a workspace, the team's token can create runs and configuration versions for that workspace via the API. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) [permissions-citation]: #intentionally-unused---keep-for-maintainers Note that the individual members of a team can usually perform actions the team itself cannot, since users can belong to multiple teams, can belong to multiple organizations, and can authenticate with Terraform's `atlas` backend for running Terraform locally. If an API token is generated for the "owners" team, then that API token will have all of the same permissions that an organization owner would. ## Organization API Tokens API tokens may be generated for a specific organization. Organization API tokens allow access to the organization-level settings and resources, without being tied to any specific team or user. To manage the API token for an organization, go to **Organization settings > API Token** and use the controls under the "Organization Tokens" header. Each organization can have **one** valid API token at a time. Only [organization owners](/terraform/cloud-docs/users-teams-organizations/teams#the-owners-team) can generate or revoke an organization's token. [permissions-citation]: #intentionally-unused---keep-for-maintainers Organization API tokens are designed for creating and configuring workspaces and teams. We don't recommend using them as an all-purpose interface to HCP Terraform; their purpose is to do some initial setup before delegating a workspace to a team. For more routine interactions with workspaces, use [team API tokens](#team-api-tokens). Organization API tokens have permissions across the entire organization. They can perform all CRUD operations on most resources, but have some limitations; most importantly, they cannot start runs or create configuration versions. Any API endpoints that can't be used with an organization API token include a note like the following: -> **Note:** This endpoint cannot be accessed with [organization tokens](#organization-api-tokens). You must access it with a [user token](/terraform/cloud-docs/users-teams-organizations/users#api-tokens) or [team token](#team-api-tokens). <!-- BEGIN: TFC:only --> ## Audit trail tokens You can generate an audit trails token to read an organization's [audit trails](/terraform/cloud-docs/api-docs/audit-trails). Use this token type to authenticate integrations pulling audit trail data, for example, using the [HCP Terraform for Splunk](/terraform/cloud-docs/integrations/splunk) app. To manage an organization's audit trails token, go to **Organization settings > API Token** and use the settings under the "Audit Token" header. Each organization can only have a _single_ valid audit trails token. Only [organization owners](/terraform/cloud-docs/users-teams-organizations/teams#the-owners-team) can generate or revoke an organization's audit trails token. [permissions-citation]: #intentionally-unused---keep-for-maintainers <!-- END: TFC:only --> ## Agent API Tokens [Agent pools](/terraform/cloud-docs/agents) have their own set of API tokens which allow agents to communicate with HCP Terraform, scoped to an organization. These tokens are not valid for direct usage in the HCP Terraform API and are only used by agents. ## Access Levels The following chart illustrates the various access levels for the supported API token types. Some permissions are implicit based on the token type, others are dependent on the permissions of the associated user, team, or organization. 🔵 = Implicit for token type 🔶 = Requires explicit permission | | User tokens | Team tokens | Organization tokens | | ---------------------------------- | :---------: | :---------: | :-----------------: | | **Users** | | | | | Manage account settings | 🔵 | | | | Manage user tokens | 🔵 | | | | **Workspaces** | | | | | Read workspace variables | 🔶 | 🔶 | 🔵 | | Write workspace variables | 🔶 | 🔶 | 🔵 | | Plan, apply, upload states | 🔶 | 🔶 | | | Force cancel runs | 🔶 | 🔶 | | | Create configuration versions | 🔶 | 🔶 | | | Create or modify workspaces | 🔶 | 🔶 | 🔵 | | Remote operations | 🔶 | 🔶 | | | Manage run triggers | 🔶 | 🔶 | 🔵 | | Manage notification configurations | 🔶 | 🔶 | | | Manage run tasks | 🔶 | 🔶 | 🔵 | | **Teams** | | | | | Create teams | 🔶 | 🔶 | 🔵 | | Modify team | 🔶 | 🔶 | 🔵 | | Read team | 🔶 | 🔶 | 🔵 | | Manage team tokens | 🔶 | 🔶 | 🔵 | | Manage team workspace access | 🔶 | 🔶 | 🔵 | | Manage team membership | 🔶 | 🔶 | 🔵 | | **Organizations** | | | | | Create organizations | 🔵 | | | | Modify organizations | 🔶 | | | | Manage organization tokens | 🔶 | | | | View audit trails | | | 🔵 | | Invite users to organization | 🔶 | 🔶 | 🔵 | | **Sentinel** | | | | | Manage Sentinel policies | 🔶 | 🔶 | 🔵 | | Manage policy sets | 🔶 | 🔶 | 🔵 | | Override policy checks | 🔶 | 🔶 | | | **Integrations** | | | | | Manage VCS connections | 🔶 | 🔶 | 🔵 | | Manage SSH keys | 🔶 | 🔶 | | | Manage run tasks | 🔶 | 🔶 | 🔵 | | **Modules** | | | | | Manage Terraform modules | 🔶 | 🔵 (owners) | | ## Token Expiration You can create user, team, and organization tokens with an expiration date and time. Once the expiration time has passed, the token is longer treated as valid and may not be used to authenticate to any API. Any API requests made with an expired token will fail. HashiCorp recommends setting an expiration on all new authentication tokens. Creating tokens with an expiration date helps reduce the risk of accidentally leaking valid tokens or forgetting to delete tokens meant for a delegated use once their intended purpose is complete. You can not modify the expiration of a token once you have created it. The HCP Terraform UI displays tokens relative to the current user's timezone, but all tokens are passed and displayed in UTC in ISO 8601 format through the HCP Terraform API.
terraform
page title API Tokens HCP Terraform description Learn about the level of access granted by user team and organization API tokens API Tokens This topic describes the distinct types of API tokens you can use to authenticate with HCP Terraform Note that HCP Terraform only displays API tokens once when you initially create them and are obfuscated thereafter If the token is lost it must be regenerated Refer to Team Token API terraform cloud docs api docs team tokens and Organization Token API terraform cloud docs api docs organization tokens for additional information about using the APIs User API Tokens API tokens may belong directly to a user User tokens are the most flexible token type because they inherit permissions from the user they are associated with For more information on user tokens and how to generate them see the Users terraform cloud docs users teams organizations users api tokens documentation Team API Tokens API tokens may belong to a specific team Team API tokens allow access to the workspaces that the team has access to without being tied to any specific user Navigate to the Organization settings API Tokens Team Token tab to manage API tokens for a team or create new team tokens Each team can have one valid API token at a time When a token is regenerated the previous token immediately becomes invalid Owners and users with manage teams terraform cloud docs users teams organizations permissions manage teams permissions have the ability to enable and disable team token management for a team which limits the actions that team members can take on a team token Refer to Allow Member Token Management terraform cloud docs users teams organizations permissions allow member token management for more information Team API tokens are designed for performing API operations on workspaces They have the same access level to the workspaces the team has access to For example if a team has permission to apply runs on a workspace the team s token can create runs and configuration versions for that workspace via the API More about permissions terraform cloud docs users teams organizations permissions permissions citation intentionally unused keep for maintainers Note that the individual members of a team can usually perform actions the team itself cannot since users can belong to multiple teams can belong to multiple organizations and can authenticate with Terraform s atlas backend for running Terraform locally If an API token is generated for the owners team then that API token will have all of the same permissions that an organization owner would Organization API Tokens API tokens may be generated for a specific organization Organization API tokens allow access to the organization level settings and resources without being tied to any specific team or user To manage the API token for an organization go to Organization settings API Token and use the controls under the Organization Tokens header Each organization can have one valid API token at a time Only organization owners terraform cloud docs users teams organizations teams the owners team can generate or revoke an organization s token permissions citation intentionally unused keep for maintainers Organization API tokens are designed for creating and configuring workspaces and teams We don t recommend using them as an all purpose interface to HCP Terraform their purpose is to do some initial setup before delegating a workspace to a team For more routine interactions with workspaces use team API tokens team api tokens Organization API tokens have permissions across the entire organization They can perform all CRUD operations on most resources but have some limitations most importantly they cannot start runs or create configuration versions Any API endpoints that can t be used with an organization API token include a note like the following Note This endpoint cannot be accessed with organization tokens organization api tokens You must access it with a user token terraform cloud docs users teams organizations users api tokens or team token team api tokens BEGIN TFC only Audit trail tokens You can generate an audit trails token to read an organization s audit trails terraform cloud docs api docs audit trails Use this token type to authenticate integrations pulling audit trail data for example using the HCP Terraform for Splunk terraform cloud docs integrations splunk app To manage an organization s audit trails token go to Organization settings API Token and use the settings under the Audit Token header Each organization can only have a single valid audit trails token Only organization owners terraform cloud docs users teams organizations teams the owners team can generate or revoke an organization s audit trails token permissions citation intentionally unused keep for maintainers END TFC only Agent API Tokens Agent pools terraform cloud docs agents have their own set of API tokens which allow agents to communicate with HCP Terraform scoped to an organization These tokens are not valid for direct usage in the HCP Terraform API and are only used by agents Access Levels The following chart illustrates the various access levels for the supported API token types Some permissions are implicit based on the token type others are dependent on the permissions of the associated user team or organization Implicit for token type Requires explicit permission User tokens Team tokens Organization tokens Users Manage account settings Manage user tokens Workspaces Read workspace variables Write workspace variables Plan apply upload states Force cancel runs Create configuration versions Create or modify workspaces Remote operations Manage run triggers Manage notification configurations Manage run tasks Teams Create teams Modify team Read team Manage team tokens Manage team workspace access Manage team membership Organizations Create organizations Modify organizations Manage organization tokens View audit trails Invite users to organization Sentinel Manage Sentinel policies Manage policy sets Override policy checks Integrations Manage VCS connections Manage SSH keys Manage run tasks Modules Manage Terraform modules owners Token Expiration You can create user team and organization tokens with an expiration date and time Once the expiration time has passed the token is longer treated as valid and may not be used to authenticate to any API Any API requests made with an expired token will fail HashiCorp recommends setting an expiration on all new authentication tokens Creating tokens with an expiration date helps reduce the risk of accidentally leaking valid tokens or forgetting to delete tokens meant for a delegated use once their intended purpose is complete You can not modify the expiration of a token once you have created it The HCP Terraform UI displays tokens relative to the current user s timezone but all tokens are passed and displayed in UTC in ISO 8601 format through the HCP Terraform API
terraform tokens and more invite terraform cloud docs users teams organizations organizations users organizations terraform cloud docs users teams organizations organizations page title Users HCP Terraform teams terraform cloud docs users teams organizations teams Create an account edit settings set up two factor authentication create API
--- page_title: Users - HCP Terraform description: >- Create an account, edit settings, set up two-factor authentication, create API tokens, and more. --- [organizations]: /terraform/cloud-docs/users-teams-organizations/organizations [teams]: /terraform/cloud-docs/users-teams-organizations/teams [invite]: /terraform/cloud-docs/users-teams-organizations/organizations#users [owners]: /terraform/cloud-docs/users-teams-organizations/teams#the-owners-team # Users User accounts belong to individual people. Each user can be part of one or more [teams](/terraform/cloud-docs/users-teams-organizations/teams), which are granted permissions on workspaces within an organization. A user can be a member of multiple [organizations][]. ## API Use the [Account API](/terraform/cloud-docs/api-docs/account) to get account details, update account information, and change your password. <!-- BEGIN: TFC:only --> ## Log in with a HashiCorp Cloud Platform account We recommend using a [HashiCorp Cloud Platform (HCP)](https://portal.cloud.hashicorp.com/sign-up) account to log in to HCP Terraform. Your HCP Account grants access to every HashiCorp product and the Terraform Registry. If you use an HCP Account, you manage account settings like multi-factor authentication and password resets from within HCP instead of the HCP Terraform UI. To log in with your HCP account, go to the [Sign In to HCP Terraform](https://app.terraform.io/) page and click **Continue with HCP account**. HCP Terraform may ask if you want to link your account. ### Linking HCP and HCP Terraform accounts The first time you log in with your HCP credentials, HCP Terraform searches for an existing HCP Terraform account with the same email address. If you have an unlinked account, HCP Terraform asks if you want to link it to your HCP account. Otherwise, if no account matches your HCP account's email address, HCP Terraform creates and automatically links a new HCP Terraform account to your HCP account. > **Note**: You can only log in with your HCP credentials after linking your HCP and HCP Terraform accounts. We do not recommend linking your account if you use an SSO provider to log in to HCP Terraform because linking your account may conflict with your existing SSO configuration. The only way to log in with your old HCP Terraform credentials is to unlink your HCP Terraform and HCP accounts. If HCP Terraform generated an account for you, you cannot unlink that account from your HCP account. You can unlink a pre-existing HCP Terraform account on the [HCP Account Linking page](#hcp-account-linking) in your **Account settings**. <!-- END: TFC:only --> ## Creating an account To use HCP Terraform or Enterprise, you must create an account through one of the following methods: - **Invitation Email:** When a user sends you an invitation to join an existing HCP Terraform organization, the email includes a sign-up link. After you create an account, you can automatically join that organization and can begin using HCP Terraform. - **Sign-Up Page:** Creating an account requires a username, an email address, and a password. For HCP Terraform, go to [`https://app.terraform.io/public/signup/account`](https://app.terraform.io/public/signup/account). For Terraform Enterprise, go to `https://<TFE HOSTNAME>/public/signup/account`. After you create an account, you do not belong to any organizations. To begin using HCP Terraform, you can either [create an organization](/terraform/cloud-docs/users-teams-organizations/organizations#creating-organizations) or ask an organization owner to send you an invitation email to join their organization. <!-- BEGIN: TFC:only --> We recommend logging into HCP Terraform [with your HCP account](#log-in-with-your-hashicorp-cloud-platform-account) instead of creating a separate HCP Terraform account. <!-- END: TFC:only --> ## Joining organizations and teams An organization owner or a user with [**Manage Membership**](/terraform/cloud-docs/users-teams-organizations/permissions#manage-membership) permissions enabled must [invite you to join their organization](/terraform/cloud-docs/users-teams-organizations/organizations#users) and [add you to one or more teams](/terraform/cloud-docs/users-teams-organizations/teams/manage#manage-team-membership). [permissions-citation]: #intentionally-unused---keep-for-maintainers HCP Terraform sends user invitations by email. If the invited email address matches an existing HCP Terraform account, the invitee can join the organization with that account. Otherwise, they must create a new account and then join the organization. ## Site admin permissions On Terraform Enterprise instances, some user accounts have a special site admin permission that allows them to administer the entire instance. Admin permissions are distinct from normal organization-level permissions, and they apply to a different set of UI controls and API endpoints. Admin users can administer any resource across the instance when using the site admin pages or the [admin API](/terraform/enterprise/api-docs/admin), but they have normal user permissions when using an organization's standard UI controls and API endpoints. These normal user permissions are determined by team membership. Refer to [Administering Terraform Enterprise](/terraform/enterprise/admin) for more details. ## Account settings To view your settings page, click your user icon and select **Account settings**. Your **Profile** page appears, showing your username, email address, and avatar. ### Profile Click **Profile** in the sidebar to view and edit the username and email address associated with your HCP Terraform account. ~> **Important:** HCP Terraform includes your username in URL paths to resources. If external systems make requests to these resources, you must update them before you change your username. HCP Terraform uses [Gravatar](http://en.gravatar.com) to display a user icon if you have associated one with your email address. Refer to the [Gravatar documentation](http://en.gravatar.com/support/) for details about changing your user icon. ### Sessions Click **Sessions** in the sidebar to view a list of sessions associated with your HCP Terraform account. You can revoke any sessions you do not recognize. <!-- BEGIN: TFC:only --> There are two types of Terraform accounts, standalone HCP Terraform accounts and HCP Terraform accounts linked to HCP accounts. ### Idle session timeout HCP Terraform automatically terminates user sessions if there has been no end-user activity for a certain time period: - Standalone HCP Terraform accounts can stay idle and valid for up to 14 days by default - HCP Terraform accounts linked to an HCP account follow the HCP defaults and can stay idle for 1 hour by default After HCP Terraform terminates a session, you can resume it by logging back in through the HCP Terraform portal. This is a security measure to prevent unauthorized access to unmonitored devices. -> **Note:** HCP Terraform organization owners can reduce the idle session timeout for an organization in the authentication settings for standalone HCP Terraform accounts, but cannot modify settings for HCP Terraform accounts linked to HCP accounts. ### Forced re-authentication Forced re-authentication (e.g., “remember for”) makes a user re-authenticate, regardless of activity. This is a security measure to force a new identity verification to access sensitive IT and data managed by HCP Terraform. In this case, the user must re-authenticate their credentials and may be asked to verify 2FA/MFA again. - By default, standalone HCP Terraform accounts are forced to re-authenticate every 14 days - By default, HCP Terraform accounts linked to an HCP account follow the HCP defaults and are forced to re-authenticate every 48 hours -> **Note:** HCP Terraform organization owners can reduce the idle session timeout for standalone HCP Terraform accounts, but cannot modify settings for HCP Terraform accounts linked to HCP accounts. ### Impact to user experience The default re-authentication defaults force users to re-authenticate at the beginning of each work week (Monday through Friday). Note that several actions immediately terminate active sessions, including: * Manually logging out of the HCP or HCP Terraform portals * Clearing browser session/cookies * Closing all active browser windows Any of these actions requires you to re-authenticate regardless of session timeout settings. <!-- END: TFC:only --> ### Organizations Click **Organizations** in the sidebar to view a list of the organizations where you are a member. If you are on the [owners team][owners], the organization is marked with an **OWNER** badge. To leave an organization, click the ellipses (**...**) next to the organization and select **Leave organization**. You do not need permission from the owners to leave an organization, but you cannot leave if you are the last member of the owners team. Either add a new owner and then leave, or [delete the organization](/terraform/cloud-docs/users-teams-organizations/organizations#general). ### Password Click **Password** in the sidebar to change your password. -> **Note:** Password management is not available if your Terraform Enterprise instance uses [SAML single sign on](/terraform/enterprise/saml/configuration). -> **Note:** Passwords must be at least 10 characters in length, and you can use any type of character. Password management is not available if your Terraform Enterprise instance uses [SAML single sign on](/terraform/enterprise/saml/configuration). ### Two-factor authentication Click **Two Factor Authentication** in the sidebar to enable two-factor authentication. Two-factor authentication requires a TOTP-compliant application or an SMS-capable phone number. An organization can set policies that require two-factor authentication. Refer to [Two-Factor Authentication](/terraform/cloud-docs/users-teams-organizations/2fa) for details. <!-- BEGIN: TFC:only --> ### HCP account linking Click **HCP Account Linking** in the sidebar to unlink your HCP Terraform from your HCP Account. You cannot unlink an account that HCP Terraform autogenerated during the linking process. Refer to [Linked HCP and HCP Terraform Accounts](#linked-hcp-and-hcp-terraform-accounts) for more details. After you unlink, you can begin using your HCP Terraform credentials to log in. You cannot log in with your HCP account again unless you re-link it to your HCP Terraform account. ### SSO identities Click **SSO Identities** in the sidebar to review and [remove SSO identity links](/terraform/cloud-docs/users-teams-organizations/single-sign-on/linking-user-account#remove-sso-identity-link) associated with your account. You have an SSO identity for every SSO-enabled HCP Terraform organization. HCP Terraform links each SSO identity to a single HCP Terraform user account. This link determines which account you can use to access each organization. <!-- END: TFC:only --> ### Tokens Click **Tokens** in the sidebar to create, manage, and revoke API tokens. HCP Terraform has three kinds of API tokens: user, team, and organization. Users can be members of multiple organizations, so user tokens work with any organization where the associated user is a member. Refer to [API Tokens](/terraform/cloud-docs/users-teams-organizations/api-tokens) for details. API tokens are required for the following tasks: - Authenticating with the [HCP Terraform API](/terraform/cloud-docs/api-docs). API calls require an `Authorization: Bearer <TOKEN>` HTTP header. - Authenticating with the [HCP Terraform CLI integration](/terraform/cli/cloud/settings) or the [`remote` backend](/terraform/language/settings/backends/remote). These require a token in the CLI configuration file or in the backend configuration. - Using [private modules](/terraform/cloud-docs/registry/using) in command-line runs on local machines. This requires [a token in the CLI configuration file](/terraform/cloud-docs/registry/using#authentication). Protect your tokens carefully because they contain the same permissions as your user account. For example, if you belong to a team with permission to read and write variables for a workspace, another user could use your API token to authenticate as your user account and also edit variables in that workspace. Refer to [permissions](/terraform/cloud-docs/users-teams-organizations/permissions) for more details. We recommend protecting your tokens by creating them with an expiration date and time. Refer to [API Token Expiration](/terraform/cloud-docs/users-teams-organizations/api-tokens#token-expiration) for details. #### Creating a token To create a new token: 1. Click **Create an API token**. The **Create API token** box appears. 1. Enter a **Description** that explains what the token is for and click **Create API token**. 1. You can optionally enter the token's expiration date or time, or create a token that never expires. The UI displays a token's expiration date and time in your current time zone. 1. Copy your token from the box and save it in a secure location. HCP Terraform only displays the token once, right after you create it. If you lose it, you must revoke the old token and create a new one. [permissions-citation]: #intentionally-unused---keep-for-maintainers #### Revoking a token To revoke a token, click the **trash can** next to it. That token will no longer be able to authenticate as your user account. ~> **Note**: HCP Terraform does not revoke a user API token's access to an organization when you remove the user from an SSO Identity Provider as the user may still be a member of the organization. To remove access to a user's API token, remove the user from the organization in the UI or with the [Terraform Enterprise provider](https://registry.terraform.io/providers/hashicorp/tfe/latest). ### GitHub app OAuth token Click **Tokens** in the sidebar to manage your GitHub App token. This token lets you connect a workspaces to an available GitHub App installation. ~> **Note:** Only an HCP Terraform user can own a GitHub App token. Team and Organization API tokens are not able to own a GitHub App token. A GitHub App token lets you: - Connect workspaces, policy sets, and registry modules to a GitHub App installation with the [HCP Terraform API](/terraform/cloud-docs/api-docs) and UI. - View available GitHub App installations with the [HCP Terraform API](/terraform/cloud-docs/api-docs) and UI. After generating this token, you can use it to view information about your available installations for the Terraform Cloud GitHub App. #### Creating a GitHub app token To create a GitHub App token, click **Create a GitHub App token**. The **GitHub App authorization pop-up window** appears requesting authorization of the Terraform Cloud GitHub App. ~> **Note:** This does not grant HCP Terraform access to repositories. #### Revoking a GitHub app token To revoke the GitHub App token, click the **ellipses button (...)**. The dropdown menu appears. Click the **Delete Token** option. This triggers a confirmation window to appear, which asks you to confirm that you want to revoke the token. Once confirmed, the token is revoked and you can no longer view GitHub App installations. #### Additional resources - [GitHub App permissions in HCP Terraform](/terraform/cloud-docs/vcs/github-app#github-permissions)
terraform
page title Users HCP Terraform description Create an account edit settings set up two factor authentication create API tokens and more organizations terraform cloud docs users teams organizations organizations teams terraform cloud docs users teams organizations teams invite terraform cloud docs users teams organizations organizations users owners terraform cloud docs users teams organizations teams the owners team Users User accounts belong to individual people Each user can be part of one or more teams terraform cloud docs users teams organizations teams which are granted permissions on workspaces within an organization A user can be a member of multiple organizations API Use the Account API terraform cloud docs api docs account to get account details update account information and change your password BEGIN TFC only Log in with a HashiCorp Cloud Platform account We recommend using a HashiCorp Cloud Platform HCP https portal cloud hashicorp com sign up account to log in to HCP Terraform Your HCP Account grants access to every HashiCorp product and the Terraform Registry If you use an HCP Account you manage account settings like multi factor authentication and password resets from within HCP instead of the HCP Terraform UI To log in with your HCP account go to the Sign In to HCP Terraform https app terraform io page and click Continue with HCP account HCP Terraform may ask if you want to link your account Linking HCP and HCP Terraform accounts The first time you log in with your HCP credentials HCP Terraform searches for an existing HCP Terraform account with the same email address If you have an unlinked account HCP Terraform asks if you want to link it to your HCP account Otherwise if no account matches your HCP account s email address HCP Terraform creates and automatically links a new HCP Terraform account to your HCP account Note You can only log in with your HCP credentials after linking your HCP and HCP Terraform accounts We do not recommend linking your account if you use an SSO provider to log in to HCP Terraform because linking your account may conflict with your existing SSO configuration The only way to log in with your old HCP Terraform credentials is to unlink your HCP Terraform and HCP accounts If HCP Terraform generated an account for you you cannot unlink that account from your HCP account You can unlink a pre existing HCP Terraform account on the HCP Account Linking page hcp account linking in your Account settings END TFC only Creating an account To use HCP Terraform or Enterprise you must create an account through one of the following methods Invitation Email When a user sends you an invitation to join an existing HCP Terraform organization the email includes a sign up link After you create an account you can automatically join that organization and can begin using HCP Terraform Sign Up Page Creating an account requires a username an email address and a password For HCP Terraform go to https app terraform io public signup account https app terraform io public signup account For Terraform Enterprise go to https TFE HOSTNAME public signup account After you create an account you do not belong to any organizations To begin using HCP Terraform you can either create an organization terraform cloud docs users teams organizations organizations creating organizations or ask an organization owner to send you an invitation email to join their organization BEGIN TFC only We recommend logging into HCP Terraform with your HCP account log in with your hashicorp cloud platform account instead of creating a separate HCP Terraform account END TFC only Joining organizations and teams An organization owner or a user with Manage Membership terraform cloud docs users teams organizations permissions manage membership permissions enabled must invite you to join their organization terraform cloud docs users teams organizations organizations users and add you to one or more teams terraform cloud docs users teams organizations teams manage manage team membership permissions citation intentionally unused keep for maintainers HCP Terraform sends user invitations by email If the invited email address matches an existing HCP Terraform account the invitee can join the organization with that account Otherwise they must create a new account and then join the organization Site admin permissions On Terraform Enterprise instances some user accounts have a special site admin permission that allows them to administer the entire instance Admin permissions are distinct from normal organization level permissions and they apply to a different set of UI controls and API endpoints Admin users can administer any resource across the instance when using the site admin pages or the admin API terraform enterprise api docs admin but they have normal user permissions when using an organization s standard UI controls and API endpoints These normal user permissions are determined by team membership Refer to Administering Terraform Enterprise terraform enterprise admin for more details Account settings To view your settings page click your user icon and select Account settings Your Profile page appears showing your username email address and avatar Profile Click Profile in the sidebar to view and edit the username and email address associated with your HCP Terraform account Important HCP Terraform includes your username in URL paths to resources If external systems make requests to these resources you must update them before you change your username HCP Terraform uses Gravatar http en gravatar com to display a user icon if you have associated one with your email address Refer to the Gravatar documentation http en gravatar com support for details about changing your user icon Sessions Click Sessions in the sidebar to view a list of sessions associated with your HCP Terraform account You can revoke any sessions you do not recognize BEGIN TFC only There are two types of Terraform accounts standalone HCP Terraform accounts and HCP Terraform accounts linked to HCP accounts Idle session timeout HCP Terraform automatically terminates user sessions if there has been no end user activity for a certain time period Standalone HCP Terraform accounts can stay idle and valid for up to 14 days by default HCP Terraform accounts linked to an HCP account follow the HCP defaults and can stay idle for 1 hour by default After HCP Terraform terminates a session you can resume it by logging back in through the HCP Terraform portal This is a security measure to prevent unauthorized access to unmonitored devices Note HCP Terraform organization owners can reduce the idle session timeout for an organization in the authentication settings for standalone HCP Terraform accounts but cannot modify settings for HCP Terraform accounts linked to HCP accounts Forced re authentication Forced re authentication e g remember for makes a user re authenticate regardless of activity This is a security measure to force a new identity verification to access sensitive IT and data managed by HCP Terraform In this case the user must re authenticate their credentials and may be asked to verify 2FA MFA again By default standalone HCP Terraform accounts are forced to re authenticate every 14 days By default HCP Terraform accounts linked to an HCP account follow the HCP defaults and are forced to re authenticate every 48 hours Note HCP Terraform organization owners can reduce the idle session timeout for standalone HCP Terraform accounts but cannot modify settings for HCP Terraform accounts linked to HCP accounts Impact to user experience The default re authentication defaults force users to re authenticate at the beginning of each work week Monday through Friday Note that several actions immediately terminate active sessions including Manually logging out of the HCP or HCP Terraform portals Clearing browser session cookies Closing all active browser windows Any of these actions requires you to re authenticate regardless of session timeout settings END TFC only Organizations Click Organizations in the sidebar to view a list of the organizations where you are a member If you are on the owners team owners the organization is marked with an OWNER badge To leave an organization click the ellipses next to the organization and select Leave organization You do not need permission from the owners to leave an organization but you cannot leave if you are the last member of the owners team Either add a new owner and then leave or delete the organization terraform cloud docs users teams organizations organizations general Password Click Password in the sidebar to change your password Note Password management is not available if your Terraform Enterprise instance uses SAML single sign on terraform enterprise saml configuration Note Passwords must be at least 10 characters in length and you can use any type of character Password management is not available if your Terraform Enterprise instance uses SAML single sign on terraform enterprise saml configuration Two factor authentication Click Two Factor Authentication in the sidebar to enable two factor authentication Two factor authentication requires a TOTP compliant application or an SMS capable phone number An organization can set policies that require two factor authentication Refer to Two Factor Authentication terraform cloud docs users teams organizations 2fa for details BEGIN TFC only HCP account linking Click HCP Account Linking in the sidebar to unlink your HCP Terraform from your HCP Account You cannot unlink an account that HCP Terraform autogenerated during the linking process Refer to Linked HCP and HCP Terraform Accounts linked hcp and hcp terraform accounts for more details After you unlink you can begin using your HCP Terraform credentials to log in You cannot log in with your HCP account again unless you re link it to your HCP Terraform account SSO identities Click SSO Identities in the sidebar to review and remove SSO identity links terraform cloud docs users teams organizations single sign on linking user account remove sso identity link associated with your account You have an SSO identity for every SSO enabled HCP Terraform organization HCP Terraform links each SSO identity to a single HCP Terraform user account This link determines which account you can use to access each organization END TFC only Tokens Click Tokens in the sidebar to create manage and revoke API tokens HCP Terraform has three kinds of API tokens user team and organization Users can be members of multiple organizations so user tokens work with any organization where the associated user is a member Refer to API Tokens terraform cloud docs users teams organizations api tokens for details API tokens are required for the following tasks Authenticating with the HCP Terraform API terraform cloud docs api docs API calls require an Authorization Bearer TOKEN HTTP header Authenticating with the HCP Terraform CLI integration terraform cli cloud settings or the remote backend terraform language settings backends remote These require a token in the CLI configuration file or in the backend configuration Using private modules terraform cloud docs registry using in command line runs on local machines This requires a token in the CLI configuration file terraform cloud docs registry using authentication Protect your tokens carefully because they contain the same permissions as your user account For example if you belong to a team with permission to read and write variables for a workspace another user could use your API token to authenticate as your user account and also edit variables in that workspace Refer to permissions terraform cloud docs users teams organizations permissions for more details We recommend protecting your tokens by creating them with an expiration date and time Refer to API Token Expiration terraform cloud docs users teams organizations api tokens token expiration for details Creating a token To create a new token 1 Click Create an API token The Create API token box appears 1 Enter a Description that explains what the token is for and click Create API token 1 You can optionally enter the token s expiration date or time or create a token that never expires The UI displays a token s expiration date and time in your current time zone 1 Copy your token from the box and save it in a secure location HCP Terraform only displays the token once right after you create it If you lose it you must revoke the old token and create a new one permissions citation intentionally unused keep for maintainers Revoking a token To revoke a token click the trash can next to it That token will no longer be able to authenticate as your user account Note HCP Terraform does not revoke a user API token s access to an organization when you remove the user from an SSO Identity Provider as the user may still be a member of the organization To remove access to a user s API token remove the user from the organization in the UI or with the Terraform Enterprise provider https registry terraform io providers hashicorp tfe latest GitHub app OAuth token Click Tokens in the sidebar to manage your GitHub App token This token lets you connect a workspaces to an available GitHub App installation Note Only an HCP Terraform user can own a GitHub App token Team and Organization API tokens are not able to own a GitHub App token A GitHub App token lets you Connect workspaces policy sets and registry modules to a GitHub App installation with the HCP Terraform API terraform cloud docs api docs and UI View available GitHub App installations with the HCP Terraform API terraform cloud docs api docs and UI After generating this token you can use it to view information about your available installations for the Terraform Cloud GitHub App Creating a GitHub app token To create a GitHub App token click Create a GitHub App token The GitHub App authorization pop up window appears requesting authorization of the Terraform Cloud GitHub App Note This does not grant HCP Terraform access to repositories Revoking a GitHub app token To revoke the GitHub App token click the ellipses button The dropdown menu appears Click the Delete Token option This triggers a confirmation window to appear which asks you to confirm that you want to revoke the token Once confirmed the token is revoked and you can no longer view GitHub App installations Additional resources GitHub App permissions in HCP Terraform terraform cloud docs vcs github app github permissions
terraform page title Organizations overview Organizations are partitions in HCP Terraform and Terraform Enterprise that let teams within a business unit collaborate on infrastructure as code projects Organizations contain one or more projects which contain one or more workspaces teams terraform cloud docs users teams organizations teams users terraform cloud docs users teams organizations users
--- page_title: Organizations overview description: >- Organizations are partitions in HCP Terraform and Terraform Enterprise that let teams within a business unit collaborate on infrastructure as code projects. Organizations contain one or more projects, which contain one or more workspaces. --- [teams]: /terraform/cloud-docs/users-teams-organizations/teams [users]: /terraform/cloud-docs/users-teams-organizations/users [owners]: /terraform/cloud-docs/users-teams-organizations/teams#the-owners-team # Organizations overview This topic provides overview information about how to create and manage organizations in HCP Terraform and Terraform Enterprise. An organization contains one or more projects. ## Requirements The **admin** permission preset must be enabled on your profile to create and manage organizations in the HCP Terraform UI. Refer to [Permissions](/terraform/cloud-docs/users-teams-organizations/permissions#organization-permissions) for additional information. ## API and Terraform Enterprise Provider In addition to the HCP Terraform UI, you can use the following methods to manage organizations: - [Organizations API](/terraform/cloud-docs/api-docs/organizations) - The `tfe` provider [`tfe_organization`](https://registry.terraform.io/providers/hashicorp/tfe/latest/docs/resources/organization) resource ## Selecting organizations HCP Terraform displays your current organization in the bottom left of the sidebar. To select an organization: 1. Click the current organization name to view a list of all the organizations where you are a member. 1. Click an organization to select it. HCP Terraform displays list of workspaces within that organization. ## Joining and leaving organizations To join an organization, the organization [owners][] or a user with specific [team management](/terraform/cloud-docs/users-teams-organizations/permissions#team-management-permissions) permissions must invite you, and you must accept the emailed invitation. [Learn more](#users). [permissions-citation]: #intentionally-unused---keep-for-maintainers To leave an organization: 1. Click the Terraform logo in the upper left corner to navigate to the **Organizations** page. 1. Click the ellipses (**...**) next to the organization and select **Leave organization**. You do not need permission from the owners to leave an organization, but you cannot leave if you are the last member of the owners team. Either add a new owner and then leave, or [delete the organization](/terraform/cloud-docs/users-teams-organizations/organizations#general). ## Creating organizations On Terraform Enterprise, administrators can restrict your ability to create organizations. Refer to [Administration: General Settings](/terraform/enterprise/admin/application/general#organization-creation) for details. On HCP Terraform, any user can create a new organization. If you do not belong to any organizations, HCP Terraform prompts you to create one the first time you log in. To create an organization: 1. Click the current organization name and select **Create new organization**. The **Create a new organization** page appears. 1. Enter a unique **Organization name** Organization names can include numbers, letters, underscores (`_`), and hyphens (`-`). 1. Provide an **Email address** to receive notifications about the organization. 1. Click **Create organization**. HCP Terraform shows the new organization and prompts you to create a new workspace. You can also [invite other users](#users) to join the organization. <!-- BEGIN: TFC:only name:managed-resources --> ## Managed resources Your organization’s managed resource count helps you understand the number of infrastructure resources that HCP Terraform manages across all your workspaces. HCP Terraform reads all the workspaces’ state files to determine the total number of managed resources. Each [resource](/terraform/language/resources/syntax) instance in the state equals one managed resource. HCP Terraform includes resources in modules and each resource created with the `count` or `for_each` meta-arguments. HCP Terraform does not include [data sources](/terraform/language/data-sources) in the count. Refer to [Managed Resources Count](/terraform/cloud-docs/workspaces/state#managed-resources-count) in the workspace state documentation for more details. You can view your organization's managed resource count on the **Usage** page. <!-- END: TFC:only name:managed-resources --> ## Create and manage reserved tags ~> **Reserved tags is in private beta and unavailable for some users.** Contact your HashiCorp representative for information about participating in the private beta. Tags are key-value pairs that you can apply to projects and workspaces. Tags help you organize your projects and resources, as well as track resource consumption. Refer to the following topics for information about creating and managing tags attached to projects and workspaces: - [Create a project](/terraform/cloud-docs/projects/manage#create-a-project) - [Create workspace tags](/terraform/cloud-docs/workspaces/tags) You can define reserved tag keys for your organization so that project and workspace managers can use consistent labels. 1. Click on **Tags** in the sidebar to view all tags in your organization. 1. Click on the **Reserved Keys** tab. You can perform the following actions: 1. Use the search bar to find a specific tag key. 1. Click on a column header to sort the table. 1. Click on the ellipses menu to open the management options for each tag key. 1. Click **New tag key** to define a new key. You can also view single-value tags that workspace managers added directly to their workspaces. Refer to [Tags](#tags) in the organization settings reference for additional information. ## Managing settings To view and manage an organization's settings, click **Settings**. The contents of the organization settings depends on your permissions within the organization. All users can review the organization's contact email, view the membership of any teams they belong to, and view the organization's authentication policy. [Organization owners][owners] can view and manage the entire list of organization settings. Refer to [Organization Permissions](/terraform/cloud-docs/users-teams-organizations/permissions#organization-permissions) for details. You may be able to manage the following organization settings. [permissions-citation]: #intentionally-unused---keep-for-maintainers ### Organization settings #### General Review the organization name and contact email. Organization owners can choose to change the organization name, contact email, and the default execution mode, or delete the organization. When an organization owner updates the default execution mode, all workspaces configured to [inherit this value](/terraform/cloud-docs/workspaces/settings#execution-mode) will be affected. Organization owners can also choose whether [workspace administrators](/terraform/cloud-docs/users-teams-organizations/permissions#workspace-admins) can delete workspaces that are managing resources. Deleting a workspace with resources under management introduces risk because Terraform can no longer track or manage the infrastructure. The workspace's users must manually delete any remaining resources or [import](/terraform/cli/commands/import) them into another Terraform workspace. <!-- BEGIN: TFC:only name:generated-tests --> Organization owners using HCP Terraform Plus edition can choose whether members with [module management permissions](/terraform/cloud-docs/users-teams-organizations/permissions#manage-private-registry) can [generate module tests](/terraform/cloud-docs/registry/test#generated-module-tests). <!-- END: TFC:only name:generated-tests --> ##### Renaming an organization !> **Warning:** Deleting or renaming an organization can be very disruptive. We strongly recommend against deleting or renaming organizations with active members. To rename an organization that manages infrastructure: 1. Alert all members of the organization about the name change. 1. Cancel in progress and pending runs or wait for them to finish. HCP Terraform cannot change the name of an organization with runs in progress. 1. Lock all workspaces to ensure that no new runs will start before you change the name. 1. Rename the organization. 1. Update all components using the HCP Terraform API to the new organization name. This includes Terraform's `cloud` block CLI integration, the `tfe` Terraform provider, and any external API integrations. 1. Unlock workspaces and resume normal operations. #### Plan & Billing Review the organization's plan and any invoices for previous plan payments. Organization owners can also upgrade to one of HCP Terraform's paid plans, downgrade to a free plan, or begin a free trial of paid features. #### Tags Click the **Tags** tab in the **Tags Management** screen to view single-value tags that workspace managers added directly to their workspaces. For information about key-value tag keys, refer to [Create and manage reserved tags](#create-and-manage-reserved-tags). You can perform the following actions in the **Tags** tab: 1. Search for a tag key or value. 1. Click on a column header to sort tags. #### Teams <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/team-management.mdx' <!-- END: TFC:only name:pnp-callout --> All users in an organization can access the **Teams** page, which displays a list of [teams][] within the organization. Organization owners and users with the [include secret teams permission](/terraform/cloud-docs/users-teams-organizations/permissions#include-secret-teams) can: * view all [secret teams](/terraform/cloud-docs/users-teams-organizations/teams/manage#team-visibility) * view each team's membership * manage team API tokens HCP Terraform restricts team creation, team deletion, and management of team API tokens to organization owners and users with the [manage teams](/terraform/cloud-docs/users-teams-organizations/permissions#manage-teams) permission. Organization owners and users with the [manage membership](/terraform/cloud-docs/users-teams-organizations/permissions#manage-membership) permission can manage team membership. Remember that users must accept their organization invitations before you can add them to a team. [permissions-citation]: #intentionally-unused---keep-for-maintainers #### Users Organization owners and users with [manage membership](/terraform/cloud-docs/users-teams-organizations/permissions#manage-membership) permissions can invite HCP Terraform users into the organization, cancel invitations, and remove existing members. The list of users is separated into one tab for active users and one tab for invited users who have not yet accepted their invitations. For active users, the list includes usernames, email addresses, avatar icons, two-factor authentication status, and current team memberships. Use the **Search by username or email** field to filter these lists. User invitations are always sent by email; you cannot invite someone using their HCP Terraform username. To invite a user to an organization: 1. Click **Invite a user**. The **invite a user** box appears. 1. Enter the user's email address and optionally add them to one or more teams. If the user accepts the invitation, HCP Terraform automatically adds them to the specified teams. All permissions in HCP Terraform are managed through teams. Users can join an organization without belonging to any teams, but they cannot use Terraform Cloud features until they belong to a team. Refer to [permissions](/terraform/cloud-docs/users-teams-organizations/permissions) for details. [permissions-citation]: #intentionally-unused---keep-for-maintainers #### Variable Sets View all of the available variable sets and their variables. Users with [`read and write variables` permissions](/terraform/cloud-docs/users-teams-organizations/permissions#general-workspace-permissions) can also create variable sets and assign them to one or more workspaces. Variable sets let you reuse the same variables across multiple workspaces in the organization. For example, you could define a variable set of provider credentials and automatically apply it to several workspaces, rather than manually defining credential variables in each. Changes to variable sets instantly apply to all appropriate workspaces, saving time and reducing errors from manual updates. Refer to the [variables overview](/terraform/cloud-docs/workspaces/variables) documentation for details about variable types, scope, and precedence. Refer to [managing variables](/terraform/cloud-docs/workspaces/variables/managing-variables) for details about how to create and manage variable sets. #### Health <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/health-assessments.mdx' <!-- END: TFC:only name:pnp-callout --> HCP Terraform can perform automatic health assessments in a workspace to assess whether its real infrastructure matches the requirements defined in its Terraform configuration. Health assessments include the following types of evaluations: - Drift detection determines whether your real-world infrastructure matches your Terraform configuration. Drift detection requires Terraform version 0.15.4+. - Continuous validation determines whether custom conditions in the workspace’s configuration continue to pass after Terraform provisions the infrastructure. Continuous validation requires Terraform version 1.3.0+. You can enforce health assessments for all eligible workspaces or let each workspace opt in to health assessments through workspace settings. Refer to [Health](/terraform/cloud-docs/workspaces/health) in the workspaces documentation for more details. #### Runs From the Workspaces page, click **Settings** in the sidebar, then **Runs** to view all of the current runs in your organization's workspaces. The **Runs** page displays: - The name of the run - The run's ID - What triggered the run - The workspace and project where the run is taking place - When the latest change in the run occurred - A button allowing you to cancel that run You can apply the following filters to limit the runs HCP Terraform displays: - Click **Needs Attention** to display runs that require user input to continue, such as approving a plan or overriding a policy. - Click **Running** to display runs that are in progress. - Click **On Hold** to display paused runs. For precise filtering, click **More filters** and check the boxes to filter runs by specific [run statuses](/terraform/cloud-docs/run/states), [run operations](/terraform/cloud-docs/run/modes-and-options), workspaces, or [agent pools](/terraform/cloud-docs/agents/agent-pools). Click **Apply filters** to list the runs that match your criteria. You can dismiss any of your filtering criteria by clicking the **X** next to the filter name above the table displaying your runs. For more details about run states, refer to [Run States and Stages](/terraform/cloud-docs/run/states). ### Integrations #### Cost Estimation Enable and disable the [cost estimation](/terraform/cloud-docs/cost-estimation) feature for all workspaces. #### Policies <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/policies.mdx' <!-- END: TFC:only name:pnp-callout --> Policies let you define and enforce rules for Terraform runs. You can write them using either the [Sentinel](/terraform/cloud-docs/policy-enforcement/sentinel) or [Open Policy Agent (OPA)](/terraform/cloud-docs/policy-enforcement/opa) policy-as-code frameworks and then group them into policy sets that you can apply to workspaces in your organization. To create policies and policy sets, you must have [permission to manage policies](/terraform/cloud-docs/users-teams-organizations/permissions#organization-permissions). #### Policy Sets <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/policies.mdx' <!-- END: TFC:only name:pnp-callout --> Create groups of policies and enforce those policy sets globally or on specific [projects](/terraform/cloud-docs/projects/manage) and workspaces. You can create policy sets through the Terraform API, by connecting a VCS repository containing policies, or directly in HCP Terraform. To create policies and policy sets, you must have [permission to manage policies](/terraform/cloud-docs/users-teams-organizations/permissions#organization-permissions). Refer to [Managing Policy Sets](/terraform/cloud-docs/policy-enforcement/manage-policy-sets) for details. [permissions-citation]: #intentionally-unused---keep-for-maintainers #### Run Tasks <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/run-tasks.mdx' <!-- END: TFC:only name:pnp-callout --> Manage the run tasks that you can add to workspaces within the organization. [Run tasks](/terraform/cloud-docs/workspaces/settings/run-tasks) let you integrate third-party tools and services at specific stages in the HCP Terraform run lifecycle. ### Security #### Agents <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/agents.mdx' <!-- END: TFC:only name:pnp-callout --> Create and manage [HCP Terraform agent pools](/terraform/cloud-docs/agents). HCP Terraform agents let HCP Terraform communicate with isolated, private, or on-premises infrastructure. This is useful for on-premises infrastructure types such as vSphere, Nutanix, OpenStack, enterprise networking providers, and infrastructure within a protected enclave. #### API Tokens Organization owners can set up a special [Organization API Token](/terraform/cloud-docs/users-teams-organizations/api-tokens) that is not associated with a specific user or team. #### Authentication Organization owners can determine when users must reauthenticate and require [two-factor authentication](/terraform/cloud-docs/users-teams-organizations/2fa) for all members of the organization. #### SSH Keys Manage [SSH keys for cloning Git-based modules](/terraform/cloud-docs/workspaces/settings/ssh-keys) during Terraform runs. This does not include keys to access a connected VCS provider. #### SSO Organization owners can set up an SSO provider for the organization. ### Version Control #### VCS General Configure [Automatically cancel plan-only runs triggered by outdated commits](/terraform/cloud-docs/users-teams-organizations/organizations/vcs-speculative-plan-management) to manage the setting. #### VCS Events -> **Note:** This feature is in beta. Review the event logs for GitLab.com connections. #### VCS Providers Configure [VCS providers](/terraform/cloud-docs/vcs) to use in the organization. You must have [permission to manage VCS settings](/terraform/cloud-docs/users-teams-organizations/permissions). [permissions-citation]: #intentionally-unused---keep-for-maintainers ### Destruction and Deletion #### Data Retention Policies <EnterpriseAlert> Data retention policies are exclusive to Terraform Enterprise, and not available in HCP Terraform. <a href="https://developer.hashicorp.com/terraform/enterprise">Learn more about Terraform Enterprise</a>. </EnterpriseAlert> An organization owner can set or override the following data retention policies: - **Admin default policy** - **Do not auto-delete** - **Auto-delete data** Setting the data retention policy to **Admin default policy** disables the other data retention policy settings. By default, the **Do not auto-delete** option is enabled for an organization. This option directs Terraform Enterprise to retain data associated with configuration and state versions, but organization owners can define configurable data retention policies that allow Terraform to _soft delete_ the backing data associated with configuration versions and state versions. Soft deleting refers to marking a data object for garbage collection so that Terraform can delete the object after a set number of days. Once an object is soft deleted, any attempts to read the object will fail. Until the garbage collection process begins, you can restore soft deleted objects using the APIs described in the [configuration version documentation](/terraform/enterprise/api-docs/configuration-versions) and the [state version documentation](/terraform/enterprise/api-docs/state-versions). Terraform permanently deletes the archivist storage after the garbage collection grace period elapses. The organization policy is the default policy applied to all workspaces, but members of individual workspaces can set overriding policies for their workspaces that take precedence over the organization policy. ## Trial Expired Organizations HCP Terraform paid features are available as a free trial. When a free trial has expired, the organization displays a banner reading **TRIAL EXPIRED — Upgrade Required**. Organizations with expired trials return to the feature set of a free organization, but they retain any data created as part of paid features. Specifically, HCP Terraform disables the following features: - Teams other than `owners` and locks users who do not belong to the `owners` team out of the organization. HCP Terraform preserves team membership and permissions and re-enables them after you upgrade the organization. - Sentinel policy checks. HCP Terraform preserves existing policies and policy sets and re-enables them after you upgrade the organization. - Cost estimation.
terraform
page title Organizations overview description Organizations are partitions in HCP Terraform and Terraform Enterprise that let teams within a business unit collaborate on infrastructure as code projects Organizations contain one or more projects which contain one or more workspaces teams terraform cloud docs users teams organizations teams users terraform cloud docs users teams organizations users owners terraform cloud docs users teams organizations teams the owners team Organizations overview This topic provides overview information about how to create and manage organizations in HCP Terraform and Terraform Enterprise An organization contains one or more projects Requirements The admin permission preset must be enabled on your profile to create and manage organizations in the HCP Terraform UI Refer to Permissions terraform cloud docs users teams organizations permissions organization permissions for additional information API and Terraform Enterprise Provider In addition to the HCP Terraform UI you can use the following methods to manage organizations Organizations API terraform cloud docs api docs organizations The tfe provider tfe organization https registry terraform io providers hashicorp tfe latest docs resources organization resource Selecting organizations HCP Terraform displays your current organization in the bottom left of the sidebar To select an organization 1 Click the current organization name to view a list of all the organizations where you are a member 1 Click an organization to select it HCP Terraform displays list of workspaces within that organization Joining and leaving organizations To join an organization the organization owners or a user with specific team management terraform cloud docs users teams organizations permissions team management permissions permissions must invite you and you must accept the emailed invitation Learn more users permissions citation intentionally unused keep for maintainers To leave an organization 1 Click the Terraform logo in the upper left corner to navigate to the Organizations page 1 Click the ellipses next to the organization and select Leave organization You do not need permission from the owners to leave an organization but you cannot leave if you are the last member of the owners team Either add a new owner and then leave or delete the organization terraform cloud docs users teams organizations organizations general Creating organizations On Terraform Enterprise administrators can restrict your ability to create organizations Refer to Administration General Settings terraform enterprise admin application general organization creation for details On HCP Terraform any user can create a new organization If you do not belong to any organizations HCP Terraform prompts you to create one the first time you log in To create an organization 1 Click the current organization name and select Create new organization The Create a new organization page appears 1 Enter a unique Organization name Organization names can include numbers letters underscores and hyphens 1 Provide an Email address to receive notifications about the organization 1 Click Create organization HCP Terraform shows the new organization and prompts you to create a new workspace You can also invite other users users to join the organization BEGIN TFC only name managed resources Managed resources Your organization s managed resource count helps you understand the number of infrastructure resources that HCP Terraform manages across all your workspaces HCP Terraform reads all the workspaces state files to determine the total number of managed resources Each resource terraform language resources syntax instance in the state equals one managed resource HCP Terraform includes resources in modules and each resource created with the count or for each meta arguments HCP Terraform does not include data sources terraform language data sources in the count Refer to Managed Resources Count terraform cloud docs workspaces state managed resources count in the workspace state documentation for more details You can view your organization s managed resource count on the Usage page END TFC only name managed resources Create and manage reserved tags Reserved tags is in private beta and unavailable for some users Contact your HashiCorp representative for information about participating in the private beta Tags are key value pairs that you can apply to projects and workspaces Tags help you organize your projects and resources as well as track resource consumption Refer to the following topics for information about creating and managing tags attached to projects and workspaces Create a project terraform cloud docs projects manage create a project Create workspace tags terraform cloud docs workspaces tags You can define reserved tag keys for your organization so that project and workspace managers can use consistent labels 1 Click on Tags in the sidebar to view all tags in your organization 1 Click on the Reserved Keys tab You can perform the following actions 1 Use the search bar to find a specific tag key 1 Click on a column header to sort the table 1 Click on the ellipses menu to open the management options for each tag key 1 Click New tag key to define a new key You can also view single value tags that workspace managers added directly to their workspaces Refer to Tags tags in the organization settings reference for additional information Managing settings To view and manage an organization s settings click Settings The contents of the organization settings depends on your permissions within the organization All users can review the organization s contact email view the membership of any teams they belong to and view the organization s authentication policy Organization owners owners can view and manage the entire list of organization settings Refer to Organization Permissions terraform cloud docs users teams organizations permissions organization permissions for details You may be able to manage the following organization settings permissions citation intentionally unused keep for maintainers Organization settings General Review the organization name and contact email Organization owners can choose to change the organization name contact email and the default execution mode or delete the organization When an organization owner updates the default execution mode all workspaces configured to inherit this value terraform cloud docs workspaces settings execution mode will be affected Organization owners can also choose whether workspace administrators terraform cloud docs users teams organizations permissions workspace admins can delete workspaces that are managing resources Deleting a workspace with resources under management introduces risk because Terraform can no longer track or manage the infrastructure The workspace s users must manually delete any remaining resources or import terraform cli commands import them into another Terraform workspace BEGIN TFC only name generated tests Organization owners using HCP Terraform Plus edition can choose whether members with module management permissions terraform cloud docs users teams organizations permissions manage private registry can generate module tests terraform cloud docs registry test generated module tests END TFC only name generated tests Renaming an organization Warning Deleting or renaming an organization can be very disruptive We strongly recommend against deleting or renaming organizations with active members To rename an organization that manages infrastructure 1 Alert all members of the organization about the name change 1 Cancel in progress and pending runs or wait for them to finish HCP Terraform cannot change the name of an organization with runs in progress 1 Lock all workspaces to ensure that no new runs will start before you change the name 1 Rename the organization 1 Update all components using the HCP Terraform API to the new organization name This includes Terraform s cloud block CLI integration the tfe Terraform provider and any external API integrations 1 Unlock workspaces and resume normal operations Plan Billing Review the organization s plan and any invoices for previous plan payments Organization owners can also upgrade to one of HCP Terraform s paid plans downgrade to a free plan or begin a free trial of paid features Tags Click the Tags tab in the Tags Management screen to view single value tags that workspace managers added directly to their workspaces For information about key value tag keys refer to Create and manage reserved tags create and manage reserved tags You can perform the following actions in the Tags tab 1 Search for a tag key or value 1 Click on a column header to sort tags Teams BEGIN TFC only name pnp callout include tfc package callouts team management mdx END TFC only name pnp callout All users in an organization can access the Teams page which displays a list of teams within the organization Organization owners and users with the include secret teams permission terraform cloud docs users teams organizations permissions include secret teams can view all secret teams terraform cloud docs users teams organizations teams manage team visibility view each team s membership manage team API tokens HCP Terraform restricts team creation team deletion and management of team API tokens to organization owners and users with the manage teams terraform cloud docs users teams organizations permissions manage teams permission Organization owners and users with the manage membership terraform cloud docs users teams organizations permissions manage membership permission can manage team membership Remember that users must accept their organization invitations before you can add them to a team permissions citation intentionally unused keep for maintainers Users Organization owners and users with manage membership terraform cloud docs users teams organizations permissions manage membership permissions can invite HCP Terraform users into the organization cancel invitations and remove existing members The list of users is separated into one tab for active users and one tab for invited users who have not yet accepted their invitations For active users the list includes usernames email addresses avatar icons two factor authentication status and current team memberships Use the Search by username or email field to filter these lists User invitations are always sent by email you cannot invite someone using their HCP Terraform username To invite a user to an organization 1 Click Invite a user The invite a user box appears 1 Enter the user s email address and optionally add them to one or more teams If the user accepts the invitation HCP Terraform automatically adds them to the specified teams All permissions in HCP Terraform are managed through teams Users can join an organization without belonging to any teams but they cannot use Terraform Cloud features until they belong to a team Refer to permissions terraform cloud docs users teams organizations permissions for details permissions citation intentionally unused keep for maintainers Variable Sets View all of the available variable sets and their variables Users with read and write variables permissions terraform cloud docs users teams organizations permissions general workspace permissions can also create variable sets and assign them to one or more workspaces Variable sets let you reuse the same variables across multiple workspaces in the organization For example you could define a variable set of provider credentials and automatically apply it to several workspaces rather than manually defining credential variables in each Changes to variable sets instantly apply to all appropriate workspaces saving time and reducing errors from manual updates Refer to the variables overview terraform cloud docs workspaces variables documentation for details about variable types scope and precedence Refer to managing variables terraform cloud docs workspaces variables managing variables for details about how to create and manage variable sets Health BEGIN TFC only name pnp callout include tfc package callouts health assessments mdx END TFC only name pnp callout HCP Terraform can perform automatic health assessments in a workspace to assess whether its real infrastructure matches the requirements defined in its Terraform configuration Health assessments include the following types of evaluations Drift detection determines whether your real world infrastructure matches your Terraform configuration Drift detection requires Terraform version 0 15 4 Continuous validation determines whether custom conditions in the workspace s configuration continue to pass after Terraform provisions the infrastructure Continuous validation requires Terraform version 1 3 0 You can enforce health assessments for all eligible workspaces or let each workspace opt in to health assessments through workspace settings Refer to Health terraform cloud docs workspaces health in the workspaces documentation for more details Runs From the Workspaces page click Settings in the sidebar then Runs to view all of the current runs in your organization s workspaces The Runs page displays The name of the run The run s ID What triggered the run The workspace and project where the run is taking place When the latest change in the run occurred A button allowing you to cancel that run You can apply the following filters to limit the runs HCP Terraform displays Click Needs Attention to display runs that require user input to continue such as approving a plan or overriding a policy Click Running to display runs that are in progress Click On Hold to display paused runs For precise filtering click More filters and check the boxes to filter runs by specific run statuses terraform cloud docs run states run operations terraform cloud docs run modes and options workspaces or agent pools terraform cloud docs agents agent pools Click Apply filters to list the runs that match your criteria You can dismiss any of your filtering criteria by clicking the X next to the filter name above the table displaying your runs For more details about run states refer to Run States and Stages terraform cloud docs run states Integrations Cost Estimation Enable and disable the cost estimation terraform cloud docs cost estimation feature for all workspaces Policies BEGIN TFC only name pnp callout include tfc package callouts policies mdx END TFC only name pnp callout Policies let you define and enforce rules for Terraform runs You can write them using either the Sentinel terraform cloud docs policy enforcement sentinel or Open Policy Agent OPA terraform cloud docs policy enforcement opa policy as code frameworks and then group them into policy sets that you can apply to workspaces in your organization To create policies and policy sets you must have permission to manage policies terraform cloud docs users teams organizations permissions organization permissions Policy Sets BEGIN TFC only name pnp callout include tfc package callouts policies mdx END TFC only name pnp callout Create groups of policies and enforce those policy sets globally or on specific projects terraform cloud docs projects manage and workspaces You can create policy sets through the Terraform API by connecting a VCS repository containing policies or directly in HCP Terraform To create policies and policy sets you must have permission to manage policies terraform cloud docs users teams organizations permissions organization permissions Refer to Managing Policy Sets terraform cloud docs policy enforcement manage policy sets for details permissions citation intentionally unused keep for maintainers Run Tasks BEGIN TFC only name pnp callout include tfc package callouts run tasks mdx END TFC only name pnp callout Manage the run tasks that you can add to workspaces within the organization Run tasks terraform cloud docs workspaces settings run tasks let you integrate third party tools and services at specific stages in the HCP Terraform run lifecycle Security Agents BEGIN TFC only name pnp callout include tfc package callouts agents mdx END TFC only name pnp callout Create and manage HCP Terraform agent pools terraform cloud docs agents HCP Terraform agents let HCP Terraform communicate with isolated private or on premises infrastructure This is useful for on premises infrastructure types such as vSphere Nutanix OpenStack enterprise networking providers and infrastructure within a protected enclave API Tokens Organization owners can set up a special Organization API Token terraform cloud docs users teams organizations api tokens that is not associated with a specific user or team Authentication Organization owners can determine when users must reauthenticate and require two factor authentication terraform cloud docs users teams organizations 2fa for all members of the organization SSH Keys Manage SSH keys for cloning Git based modules terraform cloud docs workspaces settings ssh keys during Terraform runs This does not include keys to access a connected VCS provider SSO Organization owners can set up an SSO provider for the organization Version Control VCS General Configure Automatically cancel plan only runs triggered by outdated commits terraform cloud docs users teams organizations organizations vcs speculative plan management to manage the setting VCS Events Note This feature is in beta Review the event logs for GitLab com connections VCS Providers Configure VCS providers terraform cloud docs vcs to use in the organization You must have permission to manage VCS settings terraform cloud docs users teams organizations permissions permissions citation intentionally unused keep for maintainers Destruction and Deletion Data Retention Policies EnterpriseAlert Data retention policies are exclusive to Terraform Enterprise and not available in HCP Terraform a href https developer hashicorp com terraform enterprise Learn more about Terraform Enterprise a EnterpriseAlert An organization owner can set or override the following data retention policies Admin default policy Do not auto delete Auto delete data Setting the data retention policy to Admin default policy disables the other data retention policy settings By default the Do not auto delete option is enabled for an organization This option directs Terraform Enterprise to retain data associated with configuration and state versions but organization owners can define configurable data retention policies that allow Terraform to soft delete the backing data associated with configuration versions and state versions Soft deleting refers to marking a data object for garbage collection so that Terraform can delete the object after a set number of days Once an object is soft deleted any attempts to read the object will fail Until the garbage collection process begins you can restore soft deleted objects using the APIs described in the configuration version documentation terraform enterprise api docs configuration versions and the state version documentation terraform enterprise api docs state versions Terraform permanently deletes the archivist storage after the garbage collection grace period elapses The organization policy is the default policy applied to all workspaces but members of individual workspaces can set overriding policies for their workspaces that take precedence over the organization policy Trial Expired Organizations HCP Terraform paid features are available as a free trial When a free trial has expired the organization displays a banner reading TRIAL EXPIRED Upgrade Required Organizations with expired trials return to the feature set of a free organization but they retain any data created as part of paid features Specifically HCP Terraform disables the following features Teams other than owners and locks users who do not belong to the owners team out of the organization HCP Terraform preserves team membership and permissions and re enables them after you upgrade the organization Sentinel policy checks HCP Terraform preserves existing policies and policy sets and re enables them after you upgrade the organization Cost estimation
terraform page title Microsoft Entra ID Single Sign on Terraform Cloud The Microsoft Entra ID previously Azure Active Directory SSO integration currently supports the following SAML features Single Sign on Microsoft Entra ID Learn how to configure single sign on with Microsoft Entra ID previously Entra active directory tfc only true
--- page_title: Microsoft Entra ID - Single Sign-on - Terraform Cloud tfc_only: true description: >- Learn how to configure single sign-on with Microsoft Entra ID (previously Entra active directory). --- # Single Sign-on: Microsoft Entra ID The Microsoft Entra ID (previously Azure Active Directory) SSO integration currently supports the following SAML features: - Service Provider (SP) initiated SSO - Identity Provider (IdP) initiated SSO - Just-in-Time Provisioning For more information on the listed features, visit the [Microsoft Entra ID SAML Protocol Documentation](https://learn.microsoft.com/en-us/entra/identity-platform/single-sign-on-saml-protocol). ## Configuration (Microsoft Entra ID) 1. Sign in to the Entra portal. 1. On the left navigation pane, select the **Microsoft Entra ID** service. 1. Navigate to **Enterprise Applications** and then select **All Applications**. 1. To add new application, select **New application**. 1. In the **Add from the gallery** section, type **Terraform Cloud** in the search box. 1. Select **Terraform Cloud** from results panel and then add the app. Wait a few seconds while the app is added to your tenant. 1. On the **Terraform Cloud** application integration page, find the **Manage** section and select **single sign-on**. 1. On the **Select a single sign-on method** page, select **SAML**. 1. In the SAML Signing Certificate section (you may need to refresh the page) copy the **App Federation Metadata Url**. ## Configuration (HCP Terraform) 1. Visit your organization settings page and click "SSO". 1. Click "Setup SSO". ![sso-setup](/img/docs/setup.png) 1. Select "Microsoft Entra ID" and click "Next". ![sso-wizard-choose-provider-entra](/img/docs/wizard-choose-provider-entra.png) 1. Provide your App Federation Metadata URL. ![sso-wizard-configure-settings-entra](/img/docs/wizard-configure-settings-entra.png) 1. Save, and you should see a completed Terraform Cloud SAML configuration. 1. Copy Entity ID and Reply URL. ## Configuration (Microsoft Entra ID) 1. In the Entra portal, on the **Terraform Cloud** application integration page, find the **Manage** section and select **single sign-on**. 1. On the **Select a single sign-on method** page, select **SAML**. 1. On the **Set up single sign-on with SAML** page, click the edit/pen icon for **Basic SAML Configuration** to edit the settings. 1. In the **Identifier** text box, paste the **Entity ID**. 1. In the **Reply URL** text box, paste the **Reply URL**. 1. For Service Provider initiated SSO, type `https://app.terraform.io/session` in the **Sign-On URL** text box. Otherwise, leave the box blank. 1. Select **Save**. 1. On the **Single sign-on** page, download the `Certificate (Base64)` file from under **SAML Signing Certificate**. 1. In the app's overview page, find the **Manage** section and select **Users and groups**. 1. Select **Add user**, then select **Users and groups** in the **Add Assignment** dialog. 1. In the **Users and groups** dialog, select your user from the Users list, then click the **Select** button at the bottom of the screen. 1. If you are expecting a role to be assigned to the users, you can select it from the **Select a role** dropdown. If no role has been set up for this app, you see "Default Access" role selected. 1. In the **Add Assignment** dialog, click the **Assign** button. ## Configuration (HCP Terraform) To edit your Entra SSO configuration settings: 1. Go to **Public Certificate**. 1. Paste the contents of the SAML Signing Certificate you downloaded from Microsoft Entra ID. 1. Save Settings. 1. [Verify](/terraform/cloud-docs/users-teams-organizations/single-sign-on/testing) your settings and click "Enable". 1. Your Entra SSO configuration is complete and ready to [use](/terraform/cloud-docs/users-teams-organizations/single-sign-on#signing-in-with-sso). ![sso-settings](/img/docs/settings-entra.png) ## Team and Username Attributes To configure team management in your Microsoft Entra ID application: 1. Navigate to the single sign-on page. 1. Edit step 2, **User Attributes & Claims**. 1. Add a new group claim. 1. In **Group Claims**, select **Security Groups**. 1. In the **Source Attribute** field, select either **sAMAccountName** to use account names or **Group ID** to use group UUIDs. 1. Check **Customize the name of the group claim**. 1. Set **Name (required)** to "MemberOf" and leave the namespace field blank. -> **Note:** When you configure Microsoft Entra ID to use Group Claims, it provides Group UUIDs instead of human readable names in its SAML assertions. We recommend [configuring SSO Team IDs](/terraform/cloud-docs/users-teams-organizations/single-sign-on#team-names-and-sso-team-ids) for your HCP Terraform teams to match these Entra Group UUIDs. If you plan to use SAML to set usernames in your Microsoft Entra ID application: 1. Navigate to the single sign-on page. 1. Edit step 2, **User Attributes & Claims.** We recommend naming the claim "username", leaving the namespace blank, and sourcing `user.displayname` or `user.mailnickname` as a starting point. If you have a Terraform Enterprise account, you can source `user.mail` or `user.userprincipalname`. Note that HCP Terraform usernames only allow lowercase letters, numbers, and dashes. If you namespaced any of your claims, then Microsoft Entra ID passes the attribute name using the format `<claim_namespace/claim_name>`. Consider this format when setting team and username attribute names. ## Troubleshooting the SAML assertion [Use this guide](https://support.hashicorp.com/hc/en-us/articles/1500005371682-Capturing-a-SAML-Assertion) to verify and validate the claims being sent in the SAML response.
terraform
page title Microsoft Entra ID Single Sign on Terraform Cloud tfc only true description Learn how to configure single sign on with Microsoft Entra ID previously Entra active directory Single Sign on Microsoft Entra ID The Microsoft Entra ID previously Azure Active Directory SSO integration currently supports the following SAML features Service Provider SP initiated SSO Identity Provider IdP initiated SSO Just in Time Provisioning For more information on the listed features visit the Microsoft Entra ID SAML Protocol Documentation https learn microsoft com en us entra identity platform single sign on saml protocol Configuration Microsoft Entra ID 1 Sign in to the Entra portal 1 On the left navigation pane select the Microsoft Entra ID service 1 Navigate to Enterprise Applications and then select All Applications 1 To add new application select New application 1 In the Add from the gallery section type Terraform Cloud in the search box 1 Select Terraform Cloud from results panel and then add the app Wait a few seconds while the app is added to your tenant 1 On the Terraform Cloud application integration page find the Manage section and select single sign on 1 On the Select a single sign on method page select SAML 1 In the SAML Signing Certificate section you may need to refresh the page copy the App Federation Metadata Url Configuration HCP Terraform 1 Visit your organization settings page and click SSO 1 Click Setup SSO sso setup img docs setup png 1 Select Microsoft Entra ID and click Next sso wizard choose provider entra img docs wizard choose provider entra png 1 Provide your App Federation Metadata URL sso wizard configure settings entra img docs wizard configure settings entra png 1 Save and you should see a completed Terraform Cloud SAML configuration 1 Copy Entity ID and Reply URL Configuration Microsoft Entra ID 1 In the Entra portal on the Terraform Cloud application integration page find the Manage section and select single sign on 1 On the Select a single sign on method page select SAML 1 On the Set up single sign on with SAML page click the edit pen icon for Basic SAML Configuration to edit the settings 1 In the Identifier text box paste the Entity ID 1 In the Reply URL text box paste the Reply URL 1 For Service Provider initiated SSO type https app terraform io session in the Sign On URL text box Otherwise leave the box blank 1 Select Save 1 On the Single sign on page download the Certificate Base64 file from under SAML Signing Certificate 1 In the app s overview page find the Manage section and select Users and groups 1 Select Add user then select Users and groups in the Add Assignment dialog 1 In the Users and groups dialog select your user from the Users list then click the Select button at the bottom of the screen 1 If you are expecting a role to be assigned to the users you can select it from the Select a role dropdown If no role has been set up for this app you see Default Access role selected 1 In the Add Assignment dialog click the Assign button Configuration HCP Terraform To edit your Entra SSO configuration settings 1 Go to Public Certificate 1 Paste the contents of the SAML Signing Certificate you downloaded from Microsoft Entra ID 1 Save Settings 1 Verify terraform cloud docs users teams organizations single sign on testing your settings and click Enable 1 Your Entra SSO configuration is complete and ready to use terraform cloud docs users teams organizations single sign on signing in with sso sso settings img docs settings entra png Team and Username Attributes To configure team management in your Microsoft Entra ID application 1 Navigate to the single sign on page 1 Edit step 2 User Attributes Claims 1 Add a new group claim 1 In Group Claims select Security Groups 1 In the Source Attribute field select either sAMAccountName to use account names or Group ID to use group UUIDs 1 Check Customize the name of the group claim 1 Set Name required to MemberOf and leave the namespace field blank Note When you configure Microsoft Entra ID to use Group Claims it provides Group UUIDs instead of human readable names in its SAML assertions We recommend configuring SSO Team IDs terraform cloud docs users teams organizations single sign on team names and sso team ids for your HCP Terraform teams to match these Entra Group UUIDs If you plan to use SAML to set usernames in your Microsoft Entra ID application 1 Navigate to the single sign on page 1 Edit step 2 User Attributes Claims We recommend naming the claim username leaving the namespace blank and sourcing user displayname or user mailnickname as a starting point If you have a Terraform Enterprise account you can source user mail or user userprincipalname Note that HCP Terraform usernames only allow lowercase letters numbers and dashes If you namespaced any of your claims then Microsoft Entra ID passes the attribute name using the format claim namespace claim name Consider this format when setting team and username attribute names Troubleshooting the SAML assertion Use this guide https support hashicorp com hc en us articles 1500005371682 Capturing a SAML Assertion to verify and validate the claims being sent in the SAML response
terraform Single Sign on SSO and more page title Single Sign on HCP Terraform Learn how single sign on SSO works in HCP Terraform how to sign in with tfc only true
--- page_title: Single Sign-on - HCP Terraform description: >- Learn how single sign-on (SSO) works in HCP Terraform, how to sign in with SSO, and more. tfc_only: true --- # Single Sign-on ~> **Important:** This page is about configuring single sign-on in HCP Terraform. Terraform Enterprise's single sign-on is configured differently. If you administer a Terraform Enterprise instance, see [Terraform Enterprise: SAML Configuration](/terraform/enterprise/saml/configuration). HCP Terraform allows organizations to configure SAML single sign-on (SSO), an alternative to traditional user management. SSO gives owners more control to secure accessibility to your organization’s [Projects](/terraform/cloud-docs/projects/manage), [Workspaces](/terraform/cloud-docs/workspaces), and [Managed Resources](/terraform/cloud-docs/users-teams-organizations/organizations#managed-resources). By using SSO, your organization can centralize management of users for HCP Terraform and other Software-as-a-Service (SaaS) vendors, providing greater accountability and security for an organization's identity and user management. ## Supported Identity Providers (IdPs) Select your preferred provider to learn more about what is supported for that provider and how to configure SSO for it. * [Microsoft Entra ID](/terraform/cloud-docs/users-teams-organizations/single-sign-on/entra-id) * [Okta](/terraform/cloud-docs/users-teams-organizations/single-sign-on/okta) * [SAML](/terraform/cloud-docs/users-teams-organizations/single-sign-on/saml) ## How SSO Works Organization owners can enable SSO for their organization and configure an identity provider to connect to. Once SSO is enabled for an organization, all non-owner members must sign in through SSO in order to access the organization. (Owners of an SSO-enabled organization can still access the organization through username and password, to enable fixing problems with SSO.) ### SSO Identities and HCP Terraform User Accounts SSO does not automatically provision HCP Terraform user accounts. The first time you sign in with SSO, you must either provide a password to create a new HCP Terraform user account (using your SSO email address as the username), or link your SSO identity to an existing HCP Terraform user account. Once the SSO identity is linked, you can only log in to that organization using the linked account. You must [remove the SSO link](/terraform/cloud-docs/users-teams-organizations/single-sign-on/linking-user-account#remove-sso-identity-link) if you want to access the organization with a different user account. If an organization's owners disable SSO, all members can continue to access the organization using their HCP Terraform or HashiCorp Cloud Platform credentials. ### Enforced Access Policy for HCP Terraform Resources As a non-owner, when you attempt to access an organization that has SSO configured, you will be redirected to the organization's SAML IdP to authenticate and authorize access using your SAML IdP credentials before you can access the organization's [Projects](/terraform/cloud-docs/projects/manage), [Workspaces](/terraform/cloud-docs/workspaces), and [Managed Resources](/terraform/cloud-docs/users-teams-organizations/organizations#managed-resources). Owners of an SSO-enabled organization can still access the organization's resources through their HCP Terraform credentials or their HCP credentials (if linked to their HCP Terraform account). This is to enable a workaround to problems such as your IdP becoming unavailable, lost access to your MFA or IdP credentials, or other authentication issues. <Note> HCP Terraform users are able to use their single HCP Terraform account to access resources in different organizations, however, SAML SSO does not authorize access to: - Account Settings (such as to manage 2FA or generate/revoke User API tokens) - Other organizations with SSO configured with a different SAML IdP. You will need to authenticate to each configured IdP separately. - Other organizations where SSO is not configured. </Note> In order to access these resources, you may be asked to “step-up” authentication using your HCP Terraform or HCP credentials. In most situations, a step-up HCP Terraform or HCP authentication login prompt will be required immediately after SSO authentication so that HCP Terraform can establish a broad user [session](/terraform/cloud-docs/users-teams-organizations/users#sessions) and to check access and authorization to different resources in HCP Terraform. The below diagram explains the the access enforcement policy and the authentication required for an HCP Terraform user account to access different resources in HCP Terraform: ![Screenshot: a diagram of resource access in HCP Terraform with both SSO and non-SSO authentication](/img/docs/tfc-sso-auth.png) ## Signing in with SSO 1. Visit <https://app.terraform.io> and sign out if you're signed in. 1. Click "Sign in via SSO". 1. Provide your organization name and click **Next"**. 1. If you've signed in to HCP Terraform with SSO before, proceed to the next step. If you're signing in for the first time under this account or for the first time accessing this organization, you'll be required to create a new account or link to an existing account. Use the links below the account creation form if you want to link your SSO identity to an existing account, then fill out and submit the relevant form. 1. You will be redirected to your SSO identity provider. Authenticate your account as necessary. 1. You are now signed in to HCP Terraform. ## Configuring SSO in HCP Terraform Free Edition SSO is available to all HCP Terraform organizations, but is configured and managed differently in HCP Terraform Free Edition because Team Management is only available in HCP Terraform Standard and Plus Editions. In HCP Terraform Free Edition organizations, after you successfully configure SSO, HCP Terraform automatically creates a team named `sso` and adds all current members of the `owners` team into it. In the Free Edition, you cannot modify the organization-level permissions for both the `owners` and `sso` teams. These teams grant every member full administrative access to the organization, projects, workspaces, and managed resources. After configuring SSO access, review the `owners` team membership. Members of the `owners` team have permission to bypass SSO in the event that your Identity Provider (IDP) is unavailable to service authentication requests, for example due to an IDP service outage, an administrator forgot their SSO credentials, or lost access to their software authenticator. An owner can use their HCP Terraform or HashiCorp Cloud Platform credentials (if linked) to bypass HCP Terraform SSO authentication at any time. To encourage least privilege practices, HCP Terraform prompts the user who successfully configures SSO to optionally remove other users from the owners group. ## Managing Owners and SSO Team Membership in the Free Edition The Team Management feature set is available in HCP Terraform Standard and Plus Editions only. Inviting users to any Free Edition organization will add them to the `owners` team but not the `sso` team. Review the following to assign the proper team membership between the two teams. For new users new to HCP Terraform - **Assign new users to the `owners` team** by inviting the user to the organization. - **Assign new users to the `sso` team** by asking the user to login directly to the HCP Terraform organization via the SSO authentication login. For managing existing users permissions: - **Assign existing users from the `sso` team to the `owners` team:** Remove the user from the organization. Re-invite the user. - **Assign existing users from the `owners` team to the `sso` team:** Remove the user from the organization. Ask the user to sign in via SSO authentication login directly. ## Managing Team Membership Through SSO HCP Terraform can automatically add users to teams based on their SAML assertion, so you can manage team membership in your directory service. To enable team membership mapping: 1. Click **Settings** in the navigation bar and then click **SSO** in the sidebar. The SSO configuration page appears. 1. Toggle the **Enable team management to customize your team attribute**. When team management is enabled, you can configure which SAML attribute in the SAMLResponse will control team membership. This defaults to the `MemberOf` attribute. The expected format of the corresponding `AttributeValue` in the SAMLResponse is a either a string containing a comma-separated list of teams, or separate `AttributeValue` items specifying teams. When users log in through SAML, Terraform automatically adds them to the teams included in their assertion and automatically removes them from teams that are not included in their assertion. This automatic mapping overrides any manually set team memberships. Each time the user logs in, their team membership is adjusted to match their SAML assertion. HCP Terraform ignores team names that do not exactly match existing teams and will not create new teams from those listed in the assertion. If the chosen SAML attribute is not provided in the SAMLResponse, Terraform assigns users to a default team named `sso` and does not remove them from any existing teams. It is not possible to assign users to the `owners` team through this attribute. ## Team Names and SSO Team IDs HCP Terraform expects the team names in the team membership SAML attribute to exactly match team names or configured SSO team IDs stored in HCP Terraform. Values are case sensitive and literal. HCP Terraform does not process the value passed by the IdP. As a result, you cannot use values such as the full distinguished name (DN). You can configure SSO Team IDs in the organization's **Teams** page. If an SSO Team ID is configured, HCP Terraform will attempt to match the chosen SAML attribute against both the team name and the SSO Team ID when mapping users to teams. You may want to create an SSO Team ID if the team membership SAML attribute is not human readable and is not used as the team's name in HCP Terraform. SSO Team IDs are particularly helpful if your SSO or Microsoft Entra ID provider restricts the `MemberOf` attribute in its SAML responses to Group UUIDs, rather than human readable group names. Setting the SSO Team ID allows you to maintain human readable team names in HCP Terraform, while still managing team membership through SSO or Microsoft Entra ID. ## NameID Format HCP Terraform requires that the NameID format in the SAML response be set to `urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress` with a valid email address being provided as the value for this attribute.
terraform
page title Single Sign on HCP Terraform description Learn how single sign on SSO works in HCP Terraform how to sign in with SSO and more tfc only true Single Sign on Important This page is about configuring single sign on in HCP Terraform Terraform Enterprise s single sign on is configured differently If you administer a Terraform Enterprise instance see Terraform Enterprise SAML Configuration terraform enterprise saml configuration HCP Terraform allows organizations to configure SAML single sign on SSO an alternative to traditional user management SSO gives owners more control to secure accessibility to your organization s Projects terraform cloud docs projects manage Workspaces terraform cloud docs workspaces and Managed Resources terraform cloud docs users teams organizations organizations managed resources By using SSO your organization can centralize management of users for HCP Terraform and other Software as a Service SaaS vendors providing greater accountability and security for an organization s identity and user management Supported Identity Providers IdPs Select your preferred provider to learn more about what is supported for that provider and how to configure SSO for it Microsoft Entra ID terraform cloud docs users teams organizations single sign on entra id Okta terraform cloud docs users teams organizations single sign on okta SAML terraform cloud docs users teams organizations single sign on saml How SSO Works Organization owners can enable SSO for their organization and configure an identity provider to connect to Once SSO is enabled for an organization all non owner members must sign in through SSO in order to access the organization Owners of an SSO enabled organization can still access the organization through username and password to enable fixing problems with SSO SSO Identities and HCP Terraform User Accounts SSO does not automatically provision HCP Terraform user accounts The first time you sign in with SSO you must either provide a password to create a new HCP Terraform user account using your SSO email address as the username or link your SSO identity to an existing HCP Terraform user account Once the SSO identity is linked you can only log in to that organization using the linked account You must remove the SSO link terraform cloud docs users teams organizations single sign on linking user account remove sso identity link if you want to access the organization with a different user account If an organization s owners disable SSO all members can continue to access the organization using their HCP Terraform or HashiCorp Cloud Platform credentials Enforced Access Policy for HCP Terraform Resources As a non owner when you attempt to access an organization that has SSO configured you will be redirected to the organization s SAML IdP to authenticate and authorize access using your SAML IdP credentials before you can access the organization s Projects terraform cloud docs projects manage Workspaces terraform cloud docs workspaces and Managed Resources terraform cloud docs users teams organizations organizations managed resources Owners of an SSO enabled organization can still access the organization s resources through their HCP Terraform credentials or their HCP credentials if linked to their HCP Terraform account This is to enable a workaround to problems such as your IdP becoming unavailable lost access to your MFA or IdP credentials or other authentication issues Note HCP Terraform users are able to use their single HCP Terraform account to access resources in different organizations however SAML SSO does not authorize access to Account Settings such as to manage 2FA or generate revoke User API tokens Other organizations with SSO configured with a different SAML IdP You will need to authenticate to each configured IdP separately Other organizations where SSO is not configured Note In order to access these resources you may be asked to step up authentication using your HCP Terraform or HCP credentials In most situations a step up HCP Terraform or HCP authentication login prompt will be required immediately after SSO authentication so that HCP Terraform can establish a broad user session terraform cloud docs users teams organizations users sessions and to check access and authorization to different resources in HCP Terraform The below diagram explains the the access enforcement policy and the authentication required for an HCP Terraform user account to access different resources in HCP Terraform Screenshot a diagram of resource access in HCP Terraform with both SSO and non SSO authentication img docs tfc sso auth png Signing in with SSO 1 Visit https app terraform io and sign out if you re signed in 1 Click Sign in via SSO 1 Provide your organization name and click Next 1 If you ve signed in to HCP Terraform with SSO before proceed to the next step If you re signing in for the first time under this account or for the first time accessing this organization you ll be required to create a new account or link to an existing account Use the links below the account creation form if you want to link your SSO identity to an existing account then fill out and submit the relevant form 1 You will be redirected to your SSO identity provider Authenticate your account as necessary 1 You are now signed in to HCP Terraform Configuring SSO in HCP Terraform Free Edition SSO is available to all HCP Terraform organizations but is configured and managed differently in HCP Terraform Free Edition because Team Management is only available in HCP Terraform Standard and Plus Editions In HCP Terraform Free Edition organizations after you successfully configure SSO HCP Terraform automatically creates a team named sso and adds all current members of the owners team into it In the Free Edition you cannot modify the organization level permissions for both the owners and sso teams These teams grant every member full administrative access to the organization projects workspaces and managed resources After configuring SSO access review the owners team membership Members of the owners team have permission to bypass SSO in the event that your Identity Provider IDP is unavailable to service authentication requests for example due to an IDP service outage an administrator forgot their SSO credentials or lost access to their software authenticator An owner can use their HCP Terraform or HashiCorp Cloud Platform credentials if linked to bypass HCP Terraform SSO authentication at any time To encourage least privilege practices HCP Terraform prompts the user who successfully configures SSO to optionally remove other users from the owners group Managing Owners and SSO Team Membership in the Free Edition The Team Management feature set is available in HCP Terraform Standard and Plus Editions only Inviting users to any Free Edition organization will add them to the owners team but not the sso team Review the following to assign the proper team membership between the two teams For new users new to HCP Terraform Assign new users to the owners team by inviting the user to the organization Assign new users to the sso team by asking the user to login directly to the HCP Terraform organization via the SSO authentication login For managing existing users permissions Assign existing users from the sso team to the owners team Remove the user from the organization Re invite the user Assign existing users from the owners team to the sso team Remove the user from the organization Ask the user to sign in via SSO authentication login directly Managing Team Membership Through SSO HCP Terraform can automatically add users to teams based on their SAML assertion so you can manage team membership in your directory service To enable team membership mapping 1 Click Settings in the navigation bar and then click SSO in the sidebar The SSO configuration page appears 1 Toggle the Enable team management to customize your team attribute When team management is enabled you can configure which SAML attribute in the SAMLResponse will control team membership This defaults to the MemberOf attribute The expected format of the corresponding AttributeValue in the SAMLResponse is a either a string containing a comma separated list of teams or separate AttributeValue items specifying teams When users log in through SAML Terraform automatically adds them to the teams included in their assertion and automatically removes them from teams that are not included in their assertion This automatic mapping overrides any manually set team memberships Each time the user logs in their team membership is adjusted to match their SAML assertion HCP Terraform ignores team names that do not exactly match existing teams and will not create new teams from those listed in the assertion If the chosen SAML attribute is not provided in the SAMLResponse Terraform assigns users to a default team named sso and does not remove them from any existing teams It is not possible to assign users to the owners team through this attribute Team Names and SSO Team IDs HCP Terraform expects the team names in the team membership SAML attribute to exactly match team names or configured SSO team IDs stored in HCP Terraform Values are case sensitive and literal HCP Terraform does not process the value passed by the IdP As a result you cannot use values such as the full distinguished name DN You can configure SSO Team IDs in the organization s Teams page If an SSO Team ID is configured HCP Terraform will attempt to match the chosen SAML attribute against both the team name and the SSO Team ID when mapping users to teams You may want to create an SSO Team ID if the team membership SAML attribute is not human readable and is not used as the team s name in HCP Terraform SSO Team IDs are particularly helpful if your SSO or Microsoft Entra ID provider restricts the MemberOf attribute in its SAML responses to Group UUIDs rather than human readable group names Setting the SSO Team ID allows you to maintain human readable team names in HCP Terraform while still managing team membership through SSO or Microsoft Entra ID NameID Format HCP Terraform requires that the NameID format in the SAML response be set to urn oasis names tc SAML 1 1 nameid format emailAddress with a valid email address being provided as the value for this attribute
terraform include tfc package callouts notifications mdx page title Manage team notifications Learn how to set up team notifications to notify team members on external systems whenever a particular action takes place Manage team notifications HCP Terraform can use webhooks to notify external systems about run progress change requests and other events Team notifications allow you to configure relevant alerts that notify teams you specify whenever a certain event occurs
--- page_title: Manage team notifications description: Learn how to set up team notifications to notify team members on external systems whenever a particular action takes place. --- # Manage team notifications HCP Terraform can use webhooks to notify external systems about run progress, change requests, and other events. Team notifications allow you to configure relevant alerts that notify teams you specify whenever a certain event occurs. @include 'tfc-package-callouts/notifications.mdx' You can configure an individual team notification to notify up to twenty teams. To set up notifications for teams using the API, refer to the [Notification API](/terraform/cloud-docs/api-docs/notification-configurations#team-notification-configuration). ## Requirements -> **Note**: Team notifications are in public beta. All APIs and workflows are subject to change. To configure team notifications, you need the [**Manage teams**](/terraform/cloud-docs/users-teams-organizations/permissions#manage-teams) permissions for the team for which you want to configure notifications. ## View notification configuration settings To view your current team notifications, perform the following steps: 1. Navigate to your organization’s **Settings** page. 1. Select **Teams** in the sidebar navigation. 1. Select the team for which you want to view the notifications from your list of teams. 1. Select **Notifications** in the sidebar navigation. HCP Terraform displays a list of any notification configurations you have set up. A notification configuration defines how and when you want to send notifications, and once you enable that configuration, it can send notifications. ### Update and enable notification configurations Each notification configuration includes a brief overview of each configuration’s name, type, the events that can trigger the notification, and the last time the notification was triggered. Clicking on a notification configuration opens a page where you can perform the following actions: * Enable your configuration to send notifications by toggling the switch. * Delete a configuration by clicking **Delete notification**, then **Yes, delete notification configuration**. * Test your notification’s configuration by clicking **Send test**. * Click **Edit notification** to edit your notification configuration. After creating a notification configuration, you can only edit the following aspects of that configuration: 1. The configuration’s name. 1. Whether this configuration notifies everyone on a team or specific members. 1. The workspace events that trigger notifications. You can choose from: * **All events** triggers a notification for every event in your workspace. * **No events** means that no workspace events trigger a notification. * **Only certain events** lets you specify which events trigger a notification. After making any changes, click **Update notification** to save your changes. ## Create and configure a notification To configure a new notification for a team or a user, perform the following steps: 1. Navigate to your organization’s **Settings** page. 1. Select **Teams** in the sidebar navigation. 1. Select the team you want to view the notifications for from your list of teams. 1. Select **Notifications** in the sidebar navigation. 1. Click **Create a notification**. You must complete the following fields for all new notification configurations: 1. The **Destination** where HCP Terraform should deliver either a generic or a specifically formatted payload. Refer to [Notification payloads](#notification-payloads) for details. 1. The display **Name** for this notification configuration. 1. If you configure an email notification, you can optionally specify which **Email Recipients** will receive this notification. 1. If you choose to configure a webhook, you must also specify: * A **Webhook URL** for the destination of your webhook payload. Your URL must accept HTTP or HTTPS `POST` requests and be able to use the chosen payload type. * You can optionally configure a **Token** as an arbitrary secret string that HCP Terraform will use to sign its notification webhooks. Refer to [Notification authenticity](#notification-authenticity) for details. You cannot view the token after you save the notification configuration. 1. If you choose to specify either a **Slack** or **Microsoft Teams** notification, you must also configure your webhook URL for either service. For details, refer to Slack's documentation on [creating an incoming webhook](https://api.slack.com/messaging/webhooks#create_a_webhook) and Microsoft's documentation on [creating a workflow from a channel in teams](https://support.microsoft.com/en-us/office/creating-a-workflow-from-a-channel-in-teams-242eb8f2-f328-45be-b81f-9817b51a5f0e). 1. Specify which [**Workspace events**](#workspace-events) should trigger this notification. 1. After you finish configuring your notification, click **Create a notification**. Note that if you are create an email notification, you must have [**Manage membership**](/terraform/cloud-docs/users-teams-organizations/permissions#manage-membership) permissions on a team to select users from that team as email recipients. ### Workspace events HCP Terraform can send notifications for all workspace events, no workspace events, or specific events. The following events are available for you to specify: | Event | Description | | :---- | :---- | | Change Requests | HCP Terraform will notify this team whenever someone creates a change request on a workspace to which this team has access. | ## Enable and verify a notification To configure HCP Terraform to stop sending notifications for a notification configuration, disable the **Enabled** setting on a configuration's detail page . HCP Terraform enables notifications for email configurations by default. Before enabling any webhook notifications, HCP Terraform attempts to verify the notification’s configuration by sending a test message. If the test succeeds, HCP Terraform enables the notification. To verify a notification configuration, the destination must respond with a `2xx` HTTP code. If verification fails, HCP Terraform does not enable the configuration and displays an error message. For successful and unsuccessful verifications, click the **Last Response** box to view more information about the verification results. You can also send additional test messages by clicking **Send a Test**. ## Notification Payloads Notification payloads contain different attributes depending on the integration you specified when configuring that notification. ### Slack Notifications to Slack contain the following information: * Information about the change request, including the username and avatar of the person who created the change request. * The event that triggered the notification and the time that event occurred. ### Microsoft Teams Notifications to Microsoft Teams contain the following information: * Information about the change request, including the username and avatar of the person who created the change request. * The event that triggered the notification and the time that event occurred. ### Email Email notifications contain the following information: * Information about the change request, including the username and avatar of the person who created the change request. * The event that triggered the notification and the time that event occurred. ### Generic A generic notification contains information about the event that triggered it and the time that the event occurred. You can refer to the complete generic notification payload in the [API documentation](/terraform/cloud-docs/api-docs/notification-configurations#notification-payload). You can use some of the values in the payload to retrieve additional information through the API, such as: * The [workspace ID](/terraform/cloud-docs/api-docs/workspaces#list-workspaces) * The [organization name](/terraform/cloud-docs/api-docs/organizations#show-an-organization) ## Notification Authenticity Slack notifications use Slack's own protocols to verify HCP Terraform's webhook requests. Generic notifications can include a signature to verify the request. For notification configurations that include a secret token, HCP Terraform's webhook requests include an `X-TFE-Notification-Signature` header containing an HMAC signature computed from the token using the SHA-512 digest algorithm. The notification’s receiving service is responsible for validating the signature. For more information and an example of how to validate the signature, refer to the [API documentation](/terraform/cloud-docs/api-docs/notification-configurations#notification-payload)
terraform
page title Manage team notifications description Learn how to set up team notifications to notify team members on external systems whenever a particular action takes place Manage team notifications HCP Terraform can use webhooks to notify external systems about run progress change requests and other events Team notifications allow you to configure relevant alerts that notify teams you specify whenever a certain event occurs include tfc package callouts notifications mdx You can configure an individual team notification to notify up to twenty teams To set up notifications for teams using the API refer to the Notification API terraform cloud docs api docs notification configurations team notification configuration Requirements Note Team notifications are in public beta All APIs and workflows are subject to change To configure team notifications you need the Manage teams terraform cloud docs users teams organizations permissions manage teams permissions for the team for which you want to configure notifications View notification configuration settings To view your current team notifications perform the following steps 1 Navigate to your organization s Settings page 1 Select Teams in the sidebar navigation 1 Select the team for which you want to view the notifications from your list of teams 1 Select Notifications in the sidebar navigation HCP Terraform displays a list of any notification configurations you have set up A notification configuration defines how and when you want to send notifications and once you enable that configuration it can send notifications Update and enable notification configurations Each notification configuration includes a brief overview of each configuration s name type the events that can trigger the notification and the last time the notification was triggered Clicking on a notification configuration opens a page where you can perform the following actions Enable your configuration to send notifications by toggling the switch Delete a configuration by clicking Delete notification then Yes delete notification configuration Test your notification s configuration by clicking Send test Click Edit notification to edit your notification configuration After creating a notification configuration you can only edit the following aspects of that configuration 1 The configuration s name 1 Whether this configuration notifies everyone on a team or specific members 1 The workspace events that trigger notifications You can choose from All events triggers a notification for every event in your workspace No events means that no workspace events trigger a notification Only certain events lets you specify which events trigger a notification After making any changes click Update notification to save your changes Create and configure a notification To configure a new notification for a team or a user perform the following steps 1 Navigate to your organization s Settings page 1 Select Teams in the sidebar navigation 1 Select the team you want to view the notifications for from your list of teams 1 Select Notifications in the sidebar navigation 1 Click Create a notification You must complete the following fields for all new notification configurations 1 The Destination where HCP Terraform should deliver either a generic or a specifically formatted payload Refer to Notification payloads notification payloads for details 1 The display Name for this notification configuration 1 If you configure an email notification you can optionally specify which Email Recipients will receive this notification 1 If you choose to configure a webhook you must also specify A Webhook URL for the destination of your webhook payload Your URL must accept HTTP or HTTPS POST requests and be able to use the chosen payload type You can optionally configure a Token as an arbitrary secret string that HCP Terraform will use to sign its notification webhooks Refer to Notification authenticity notification authenticity for details You cannot view the token after you save the notification configuration 1 If you choose to specify either a Slack or Microsoft Teams notification you must also configure your webhook URL for either service For details refer to Slack s documentation on creating an incoming webhook https api slack com messaging webhooks create a webhook and Microsoft s documentation on creating a workflow from a channel in teams https support microsoft com en us office creating a workflow from a channel in teams 242eb8f2 f328 45be b81f 9817b51a5f0e 1 Specify which Workspace events workspace events should trigger this notification 1 After you finish configuring your notification click Create a notification Note that if you are create an email notification you must have Manage membership terraform cloud docs users teams organizations permissions manage membership permissions on a team to select users from that team as email recipients Workspace events HCP Terraform can send notifications for all workspace events no workspace events or specific events The following events are available for you to specify Event Description Change Requests HCP Terraform will notify this team whenever someone creates a change request on a workspace to which this team has access Enable and verify a notification To configure HCP Terraform to stop sending notifications for a notification configuration disable the Enabled setting on a configuration s detail page HCP Terraform enables notifications for email configurations by default Before enabling any webhook notifications HCP Terraform attempts to verify the notification s configuration by sending a test message If the test succeeds HCP Terraform enables the notification To verify a notification configuration the destination must respond with a 2xx HTTP code If verification fails HCP Terraform does not enable the configuration and displays an error message For successful and unsuccessful verifications click the Last Response box to view more information about the verification results You can also send additional test messages by clicking Send a Test Notification Payloads Notification payloads contain different attributes depending on the integration you specified when configuring that notification Slack Notifications to Slack contain the following information Information about the change request including the username and avatar of the person who created the change request The event that triggered the notification and the time that event occurred Microsoft Teams Notifications to Microsoft Teams contain the following information Information about the change request including the username and avatar of the person who created the change request The event that triggered the notification and the time that event occurred Email Email notifications contain the following information Information about the change request including the username and avatar of the person who created the change request The event that triggered the notification and the time that event occurred Generic A generic notification contains information about the event that triggered it and the time that the event occurred You can refer to the complete generic notification payload in the API documentation terraform cloud docs api docs notification configurations notification payload You can use some of the values in the payload to retrieve additional information through the API such as The workspace ID terraform cloud docs api docs workspaces list workspaces The organization name terraform cloud docs api docs organizations show an organization Notification Authenticity Slack notifications use Slack s own protocols to verify HCP Terraform s webhook requests Generic notifications can include a signature to verify the request For notification configurations that include a secret token HCP Terraform s webhook requests include an X TFE Notification Signature header containing an HMAC signature computed from the token using the SHA 512 digest algorithm The notification s receiving service is responsible for validating the signature For more information and an example of how to validate the signature refer to the API documentation terraform cloud docs api docs notification configurations notification payload
terraform Manage teams You can grant team management abilities to members of teams with either one of the manage teams or manage organization access permissions Refer to Team Permissions terraform cloud docs users teams organizations permissions team permissions for details Learn how to manage team creation team deletion team membership and team access to workspaces projects and organizations page title Manage teams
--- page_title: Manage teams description: |- Learn how to manage team creation, team deletion, team membership, and team access to workspaces, projects, and organizations. --- # Manage teams You can grant team management abilities to members of teams with either one of the manage teams or manage organization access permissions. Refer to [Team Permissions](/terraform/cloud-docs/users-teams-organizations/permissions#team-permissions) for details. [Organization owners](/terraform/cloud-docs/users-teams-organizations/teams#the-owners-team) can also create teams, assign team permissions, or view the full list of teams. Other users can view any teams marked as visible within the organization, plus any secret teams they are members of. Refer to [Team Visibility](#team-visibility) for details. To manage teams, perform the following steps: 1. Click **Settings** and then click **Teams**. The **Team Management** page appears, containing a list of all teams within the organization. 1. Click a team to go to its settings page, which lists the team's settings and current members. Members that have [two-factor authentication](/terraform/cloud-docs/users-teams-organizations/2fa) enabled have a **2FA** badge. You can manage a team on its settings page by adding or removing members, changing its visibility, and controlling access to workspaces, projects, and the organization. ## Create teams To create a new team, perform the following steps: 1. Click **Settings** and then click **Teams**. The **Team Management** page appears, containing a list of all teams within the organization. 1. Enter a unique team **Name** and click **Create Team**. Team names can include numbers, letters, underscores (`_`), and hyphens (`-`). The new team's settings page appears, where you can add new members and grant permissions. ## Delete teams ~> **Important:** Team deletion is permanent, and you cannot undo it. To delete a team, perform the following steps: 1. Click **Settings**, then click **Teams**. The **Team Management** page appears, containing a list of all teams within the organization. 1. Click the team you want to delete to go to its settings page. 1. Click **Delete [team name]** at the bottom of the page. The **Deleting team "[team name]"** box appears. 1. Click **Yes, delete team** to permanently delete the team and all of its data from HCP Terraform. ## Manage team membership Team structure often resembles your company's organizational structure. ### Add users If the user is not yet in the organization, [invite them to join the organization](/terraform/cloud-docs/users-teams-organizations/organizations#users) and include a list of teams they should belong to in the invitation. Once the user accepts the invitation, HCP Terraform automatically adds them to those teams. To add a user that is already in the organization: 1. Click **Settings** and then click **Teams**. The **Team Management** page appears, containing a list of all teams within the organization. 1. Click the team to go to its settings page. 1. Choose a user under **Add a New Team Member**. Use the text field to filter the list by username or email. 1. Click the user to add them to the team. HCP Terraform now displays the user under **Members**. ### Remove users To remove a user from a team: 1. Click **Settings** and then click **Teams**. The **Team Management** page appears, containing a list of all teams within the organization. 1. Click the team to go to its settings page. 1. Click **...** next to the user's name and choose **Remove from team** from the menu. HCP Terraform removes the user from the list of team members. ## Team visibility The settings under **Visibility** allow you to control who can see a team within the organization. To edit a team's visibility: 1. Click **Settings** and then click **Teams**. The **Team Management** page appears, containing a list of all teams within the organization. 1. Click the team to go to its settings page. 1. Enable one of the following settings: - **Visible:** Every user in the organization can see the team and its membership. Non-members have read-only access. - **Secret:** The default setting is that only team members and organization owners can view a team and its membership. We recommend making the majority of teams visible to simplify workspace administration. Secret teams should only have [organization-level permissions](/terraform/cloud-docs/users-teams-organizations/permissions#organization-permissions) since workspace admins cannot manage permissions for teams they cannot view. ## Manage workspace access You can grant teams various permissions on workspaces. Refer to [Workspace Permissions](/terraform/cloud-docs/users-teams-organizations/permissions#workspace-permissions) for details. HCP Terraform uses the most permissive permission level from your teams to determine what actions you can take on a particular resource. For example, if you belong to a team that only has permission to read runs for a workspace and another team with admin access to that workspace, HCP Terraform grants you admin access. HCP Terraform grants the most permissive permissions regardless of whether an organization, project, team, or workspace set those permissions. For example, if a team has permission to read runs for a given workspace and has permission to manage that workspace through the organization, then members of that team can manage that workspace. Refer to [organization permissions](/terraform/cloud-docs/users-teams-organizations/permissions#organization-permissions) and [project permissions](/terraform/cloud-docs/users-teams-organizations/permissions#project-permissions) for additional information. Another example is when a team has permission at the organization-level to read runs for all workspaces and admin access to a specific workspace. HCP Terraform grants the more permissive admin permissions to that workspace. To manage team permissions on a workspace: 1. Go to the workspace and click **Settings > Team Access**. The **Team Access** page appears. 1. Click **Add team and permissions** to select a team and assign a pre-built or custom permission set. ## Manage project access You can grant teams permissions to manage a project and the workspaces that belong to it. Refer to [Project Permissions](/terraform/cloud-docs/users-teams-organizations/permissions#project-permissions) for details. ## Manage organization access Organization owners can grant teams permissions to manage policies, projects and workspaces, team and organization membership, VCS settings, private registry providers and modules, and policy overrides across an organization. Refer to [Organization Permissions](/terraform/cloud-docs/users-teams-organizations/permissions#organization-permissions) for details. [permissions-citation]: #intentionally-unused---keep-for-maintainers
terraform
page title Manage teams description Learn how to manage team creation team deletion team membership and team access to workspaces projects and organizations Manage teams You can grant team management abilities to members of teams with either one of the manage teams or manage organization access permissions Refer to Team Permissions terraform cloud docs users teams organizations permissions team permissions for details Organization owners terraform cloud docs users teams organizations teams the owners team can also create teams assign team permissions or view the full list of teams Other users can view any teams marked as visible within the organization plus any secret teams they are members of Refer to Team Visibility team visibility for details To manage teams perform the following steps 1 Click Settings and then click Teams The Team Management page appears containing a list of all teams within the organization 1 Click a team to go to its settings page which lists the team s settings and current members Members that have two factor authentication terraform cloud docs users teams organizations 2fa enabled have a 2FA badge You can manage a team on its settings page by adding or removing members changing its visibility and controlling access to workspaces projects and the organization Create teams To create a new team perform the following steps 1 Click Settings and then click Teams The Team Management page appears containing a list of all teams within the organization 1 Enter a unique team Name and click Create Team Team names can include numbers letters underscores and hyphens The new team s settings page appears where you can add new members and grant permissions Delete teams Important Team deletion is permanent and you cannot undo it To delete a team perform the following steps 1 Click Settings then click Teams The Team Management page appears containing a list of all teams within the organization 1 Click the team you want to delete to go to its settings page 1 Click Delete team name at the bottom of the page The Deleting team team name box appears 1 Click Yes delete team to permanently delete the team and all of its data from HCP Terraform Manage team membership Team structure often resembles your company s organizational structure Add users If the user is not yet in the organization invite them to join the organization terraform cloud docs users teams organizations organizations users and include a list of teams they should belong to in the invitation Once the user accepts the invitation HCP Terraform automatically adds them to those teams To add a user that is already in the organization 1 Click Settings and then click Teams The Team Management page appears containing a list of all teams within the organization 1 Click the team to go to its settings page 1 Choose a user under Add a New Team Member Use the text field to filter the list by username or email 1 Click the user to add them to the team HCP Terraform now displays the user under Members Remove users To remove a user from a team 1 Click Settings and then click Teams The Team Management page appears containing a list of all teams within the organization 1 Click the team to go to its settings page 1 Click next to the user s name and choose Remove from team from the menu HCP Terraform removes the user from the list of team members Team visibility The settings under Visibility allow you to control who can see a team within the organization To edit a team s visibility 1 Click Settings and then click Teams The Team Management page appears containing a list of all teams within the organization 1 Click the team to go to its settings page 1 Enable one of the following settings Visible Every user in the organization can see the team and its membership Non members have read only access Secret The default setting is that only team members and organization owners can view a team and its membership We recommend making the majority of teams visible to simplify workspace administration Secret teams should only have organization level permissions terraform cloud docs users teams organizations permissions organization permissions since workspace admins cannot manage permissions for teams they cannot view Manage workspace access You can grant teams various permissions on workspaces Refer to Workspace Permissions terraform cloud docs users teams organizations permissions workspace permissions for details HCP Terraform uses the most permissive permission level from your teams to determine what actions you can take on a particular resource For example if you belong to a team that only has permission to read runs for a workspace and another team with admin access to that workspace HCP Terraform grants you admin access HCP Terraform grants the most permissive permissions regardless of whether an organization project team or workspace set those permissions For example if a team has permission to read runs for a given workspace and has permission to manage that workspace through the organization then members of that team can manage that workspace Refer to organization permissions terraform cloud docs users teams organizations permissions organization permissions and project permissions terraform cloud docs users teams organizations permissions project permissions for additional information Another example is when a team has permission at the organization level to read runs for all workspaces and admin access to a specific workspace HCP Terraform grants the more permissive admin permissions to that workspace To manage team permissions on a workspace 1 Go to the workspace and click Settings Team Access The Team Access page appears 1 Click Add team and permissions to select a team and assign a pre built or custom permission set Manage project access You can grant teams permissions to manage a project and the workspaces that belong to it Refer to Project Permissions terraform cloud docs users teams organizations permissions project permissions for details Manage organization access Organization owners can grant teams permissions to manage policies projects and workspaces team and organization membership VCS settings private registry providers and modules and policy overrides across an organization Refer to Organization Permissions terraform cloud docs users teams organizations permissions organization permissions for details permissions citation intentionally unused keep for maintainers
terraform Part 3 3 How to Move from Infrastructure as Code to Collaborative Infrastructure as Code Move to collaborative infrastructure as code workflows Learn about HCP Terraform s run environment create workspaces plan and create teams assign permissions and restrict non Terraform access page title Terraform Recommended Practices tfc only true Part 3 3 From Infrastructure as Code to Collaborative Infrastructure as Code
--- page_title: >- Part 3.3: From Infrastructure as Code to Collaborative Infrastructure as Code - Terraform Recommended Practices tfc_only: true description: >- Move to collaborative infrastructure-as-code workflows. Learn about HCP Terraform's run environment, create workspaces, plan and create teams, assign permissions, and restrict non-Terraform access. --- # Part 3.3: How to Move from Infrastructure as Code to Collaborative Infrastructure as Code Using version-controlled Terraform configurations to manage key infrastructure eliminates a great deal of technical complexity and inconsistency. Now that you have the basics under control, you’re ready to focus on other problems. Your next goals are to: - Adopt consistent workflows for Terraform usage across teams - Expand the benefits of Terraform beyond the core of engineers who directly edit Terraform code. - Manage infrastructure provisioning permissions for users and teams. [HCP Terraform](https://www.hashicorp.com/products/terraform/) is the product we’ve built to help you address these next-level problems. The following section describes how to start using it most effectively. Note: If you aren’t already using mature Terraform code to manage a significant portion of your infrastructure, make sure you follow the steps in the previous section first. ## 1. Install or Sign Up for HCP Terraform You have two options for using HCP Terraform: the SaaS hosted by HashiCorp, or a private instance you manage with Terraform Enterprise. If you have chosen the SaaS version then you can skip this step; otherwise visit the [Terraform Enterprise documentation](/terraform/enterprise) to get started. ## 2. Learn HCP Terraform's Run Environment Get familiar with how Terraform runs work in HCP Terraform. With Terraform Community Edition, you generally use external VCS tools to get code onto the filesystem, then execute runs from the command line or from a general purpose CI system. HCP Terraform does things differently: a workspace is associated directly with a VCS repo, and you use HCP Terraform’s UI or API to start and monitor runs. To get familiar with this operating model: - Read the documentation on how to [perform and configure Terraform runs](/terraform/cloud-docs/run/remote-operations) in HCP Terraform. - Create a proof-of-concept workspace, associate it with Terraform code in a VCS repo, set variables as needed, and use HCP Terraform to perform some Terraform runs with that code. ## 3. Design Your Organization’s Workspace Structure In HCP Terraform, each Terraform configuration should manage a specific infrastructure component, and each environment of a given configuration should be a separate workspace — in other words, Terraform configurations \* environments = workspaces. A workspace name should be something like “networking-dev,” so you can tell at a glance which infrastructure and environment it manages. The definition of an “infrastructure component” depends on your organization’s structure. A given workspace might manage an application, a service, or a group of related services; it might provision infrastructure used by a single engineering team, or it might provision shared, foundational infrastructure used by the entire business. You should structure your workspaces to match the divisions of responsibility in your infrastructure. You will probably end up with a mixture: some components, like networking, are foundational infrastructure controlled by central IT staff; others are application-specific and should be controlled by the engineering teams that rely on them. Also, keep in mind: - Some workspaces publish output data to be used by other workspaces. - The workspaces that make up a configuration’s environments (app1-dev, app1-stage, app1-prod) should be run in order, to ensure code is properly verified. The first relationship, a relationship between workspaces for different components but the same environment, creates a graph of dependencies between workspaces, and you should stay aware of it. The second relationship, a relationship between workspaces for the same component but different environments, creates a pipeline between workspaces. HCP Terraform doesn’t currently have the ability to act on these dependencies, but features like cascading updates and promotion are coming soon, and you’ll be able to use them more easily if you already understand how your workspaces relate. ## 4. Create Workspaces Create workspaces in HCP Terraform, and map VCS repositories to them. Each workspace reads its Terraform code from your version control system. You’ll need to assign a repository and branch to each workspace. We recommend using the same repository and branch for every environment of a given app or service — write your Terraform code such that you can differentiate the environments via variables, and set those variables appropriately per workspace. This might not be practical for your existing code yet, in which case you can use different branches per workspace and handle promotion through your merge strategy, but we believe a model of one canonical branch works best. ![Changes in VCS branches can be merged to master and then promoted between workspaces representing a staging environment, a UAT environment, and finally a production environment.](/img/docs/image1.png) ## 5. Plan and Create Teams HCP Terraform manages workspace access with teams, which are groups of user accounts. Your HCP Terraform teams should match your understanding of who's responsible for which infrastructure. That isn't always an exact match for your org chart, so make sure you spend some time thinking about this and talking to people across the organization. Keep in mind: - Some teams need to administer many workspaces, and others only need permissions on one or two. - A team might not have the same permissions on every workspace they use; for example, application developers might have read/write access to their app’s dev and stage environments, but read-only access to prod. Managing an accurate and complete map of how responsibilities are delegated is one of the most difficult parts of practicing collaborative infrastructure as code. When managing team membership, you have two options: - Manage user accounts with [SAML single sign-on](/terraform/enterprise/saml/configuration). SAML support is exclusive to Terraform Enterprise, and lets users log into HCP Terraform via your organization's existing identity provider. If your organization is at a scale where you use a SAML-compatible identity provider, we recommend this option. If your identity provider already has information about your colleagues' teams or groups, you can [manage team membership via your identity provider](/terraform/enterprise/saml/team-membership). Otherwise, you can add users to teams with the UI or with [the team membership API](/terraform/cloud-docs/api-docs/team-members). - Manage user accounts in HCP Terraform. Your colleagues must create their own HCP Terraform user accounts, and you can add them to your organization by adding their username to at least one team. You can manage team membership with the UI or with [the team membership API](/terraform/cloud-docs/api-docs/team-members). ## 6. Assign Permissions Assign workspace ownership and permissions to teams. HCP Terraform supports granular team permissions for each workspace. For complete information about the available permissions, see [the HCP Terraform permissions documentation.](/terraform/cloud-docs/users-teams-organizations/permissions) [permissions-citation]: #intentionally-unused---keep-for-maintainers Most workspaces will give access to multiple teams with different permissions. | Workspace | Team Permissions | | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | | app1-dev | Team-eng-app1: Apply runs, read and write variables <br /> Team-owners-app1: Admin <br /> Team-central-IT: Admin | | app1-prod | Team-eng-app1: Queue plans, read variables <br /> Team-owners-app1: Apply runs, read and write variables <br /> Team-central-IT: Admin | | networking-dev | Team-eng-networking: Apply runs, read and write variables <br /> Team-owners-networking: Admin <br /> Team-central-IT: Admin | | networking-prod | Team-eng-networking: Queue plans, read variables <br /> Team-owners-networking: Apply runs, read and write variables <br /> Team-central-IT: Admin | ## 7. Restrict Non-Terraform Access Restrict access to cloud provider UIs and APIs. Since HCP Terraform is now your organization’s primary interface for infrastructure provisioning, you should restrict access to any alternate interface that bypasses HCP Terraform. For almost all users, it should be impossible to manually modify infrastructure without using the organization’s agreed-upon Terraform workflow. As long as no one can bypass Terraform, your code review processes and your HCP Terraform workspace permissions are the definitive record of who can modify which infrastructure. This makes everything about your infrastructure more knowable and controllable. HCP Terraform is one workflow to learn, one workflow to secure, and one workflow to audit for provisioning any infrastructure in your organization. ## Next At this point, you have successfully adopted a collaborative infrastructure as code workflow with HCP Terraform. You can provision infrastructure across multiple providers using a single workflow, and you have a shared interface that helps manage your organization’s standards around access control and code promotion. Next, you can make additional improvements to your workflows and practices. Continue on to [Part 3.4: Advanced Improvements to Collaborative Infrastructure as Code](/terraform/cloud-docs/recommended-practices/part3.4).
terraform
page title Part 3 3 From Infrastructure as Code to Collaborative Infrastructure as Code Terraform Recommended Practices tfc only true description Move to collaborative infrastructure as code workflows Learn about HCP Terraform s run environment create workspaces plan and create teams assign permissions and restrict non Terraform access Part 3 3 How to Move from Infrastructure as Code to Collaborative Infrastructure as Code Using version controlled Terraform configurations to manage key infrastructure eliminates a great deal of technical complexity and inconsistency Now that you have the basics under control you re ready to focus on other problems Your next goals are to Adopt consistent workflows for Terraform usage across teams Expand the benefits of Terraform beyond the core of engineers who directly edit Terraform code Manage infrastructure provisioning permissions for users and teams HCP Terraform https www hashicorp com products terraform is the product we ve built to help you address these next level problems The following section describes how to start using it most effectively Note If you aren t already using mature Terraform code to manage a significant portion of your infrastructure make sure you follow the steps in the previous section first 1 Install or Sign Up for HCP Terraform You have two options for using HCP Terraform the SaaS hosted by HashiCorp or a private instance you manage with Terraform Enterprise If you have chosen the SaaS version then you can skip this step otherwise visit the Terraform Enterprise documentation terraform enterprise to get started 2 Learn HCP Terraform s Run Environment Get familiar with how Terraform runs work in HCP Terraform With Terraform Community Edition you generally use external VCS tools to get code onto the filesystem then execute runs from the command line or from a general purpose CI system HCP Terraform does things differently a workspace is associated directly with a VCS repo and you use HCP Terraform s UI or API to start and monitor runs To get familiar with this operating model Read the documentation on how to perform and configure Terraform runs terraform cloud docs run remote operations in HCP Terraform Create a proof of concept workspace associate it with Terraform code in a VCS repo set variables as needed and use HCP Terraform to perform some Terraform runs with that code 3 Design Your Organization s Workspace Structure In HCP Terraform each Terraform configuration should manage a specific infrastructure component and each environment of a given configuration should be a separate workspace in other words Terraform configurations environments workspaces A workspace name should be something like networking dev so you can tell at a glance which infrastructure and environment it manages The definition of an infrastructure component depends on your organization s structure A given workspace might manage an application a service or a group of related services it might provision infrastructure used by a single engineering team or it might provision shared foundational infrastructure used by the entire business You should structure your workspaces to match the divisions of responsibility in your infrastructure You will probably end up with a mixture some components like networking are foundational infrastructure controlled by central IT staff others are application specific and should be controlled by the engineering teams that rely on them Also keep in mind Some workspaces publish output data to be used by other workspaces The workspaces that make up a configuration s environments app1 dev app1 stage app1 prod should be run in order to ensure code is properly verified The first relationship a relationship between workspaces for different components but the same environment creates a graph of dependencies between workspaces and you should stay aware of it The second relationship a relationship between workspaces for the same component but different environments creates a pipeline between workspaces HCP Terraform doesn t currently have the ability to act on these dependencies but features like cascading updates and promotion are coming soon and you ll be able to use them more easily if you already understand how your workspaces relate 4 Create Workspaces Create workspaces in HCP Terraform and map VCS repositories to them Each workspace reads its Terraform code from your version control system You ll need to assign a repository and branch to each workspace We recommend using the same repository and branch for every environment of a given app or service write your Terraform code such that you can differentiate the environments via variables and set those variables appropriately per workspace This might not be practical for your existing code yet in which case you can use different branches per workspace and handle promotion through your merge strategy but we believe a model of one canonical branch works best Changes in VCS branches can be merged to master and then promoted between workspaces representing a staging environment a UAT environment and finally a production environment img docs image1 png 5 Plan and Create Teams HCP Terraform manages workspace access with teams which are groups of user accounts Your HCP Terraform teams should match your understanding of who s responsible for which infrastructure That isn t always an exact match for your org chart so make sure you spend some time thinking about this and talking to people across the organization Keep in mind Some teams need to administer many workspaces and others only need permissions on one or two A team might not have the same permissions on every workspace they use for example application developers might have read write access to their app s dev and stage environments but read only access to prod Managing an accurate and complete map of how responsibilities are delegated is one of the most difficult parts of practicing collaborative infrastructure as code When managing team membership you have two options Manage user accounts with SAML single sign on terraform enterprise saml configuration SAML support is exclusive to Terraform Enterprise and lets users log into HCP Terraform via your organization s existing identity provider If your organization is at a scale where you use a SAML compatible identity provider we recommend this option If your identity provider already has information about your colleagues teams or groups you can manage team membership via your identity provider terraform enterprise saml team membership Otherwise you can add users to teams with the UI or with the team membership API terraform cloud docs api docs team members Manage user accounts in HCP Terraform Your colleagues must create their own HCP Terraform user accounts and you can add them to your organization by adding their username to at least one team You can manage team membership with the UI or with the team membership API terraform cloud docs api docs team members 6 Assign Permissions Assign workspace ownership and permissions to teams HCP Terraform supports granular team permissions for each workspace For complete information about the available permissions see the HCP Terraform permissions documentation terraform cloud docs users teams organizations permissions permissions citation intentionally unused keep for maintainers Most workspaces will give access to multiple teams with different permissions Workspace Team Permissions app1 dev Team eng app1 Apply runs read and write variables br Team owners app1 Admin br Team central IT Admin app1 prod Team eng app1 Queue plans read variables br Team owners app1 Apply runs read and write variables br Team central IT Admin networking dev Team eng networking Apply runs read and write variables br Team owners networking Admin br Team central IT Admin networking prod Team eng networking Queue plans read variables br Team owners networking Apply runs read and write variables br Team central IT Admin 7 Restrict Non Terraform Access Restrict access to cloud provider UIs and APIs Since HCP Terraform is now your organization s primary interface for infrastructure provisioning you should restrict access to any alternate interface that bypasses HCP Terraform For almost all users it should be impossible to manually modify infrastructure without using the organization s agreed upon Terraform workflow As long as no one can bypass Terraform your code review processes and your HCP Terraform workspace permissions are the definitive record of who can modify which infrastructure This makes everything about your infrastructure more knowable and controllable HCP Terraform is one workflow to learn one workflow to secure and one workflow to audit for provisioning any infrastructure in your organization Next At this point you have successfully adopted a collaborative infrastructure as code workflow with HCP Terraform You can provision infrastructure across multiple providers using a single workflow and you have a shared interface that helps manage your organization s standards around access control and code promotion Next you can make additional improvements to your workflows and practices Continue on to Part 3 4 Advanced Improvements to Collaborative Infrastructure as Code terraform cloud docs recommended practices part3 4
terraform Learn about our recommended Terraform workflow in this recommended practices guide Part 1 An Overview of Our Recommended Workflow Terraform s purpose is to provide one workflow to provision any infrastructure In this section we ll show you our recommended practices for organizing Terraform usage across a large organization This is the set of practices that we call collaborative infrastructure as code page title Part 1 Overview of Our Recommended Workflow Terraform Recommended Practices tfc only true
--- page_title: 'Part 1: Overview of Our Recommended Workflow - Terraform Recommended Practices' tfc_only: true description: >- Learn about our recommended Terraform workflow in this recommended practices guide. --- # Part 1: An Overview of Our Recommended Workflow Terraform's purpose is to provide one workflow to provision any infrastructure. In this section, we'll show you our recommended practices for organizing Terraform usage across a large organization. This is the set of practices that we call "collaborative infrastructure as code." ## Fundamental Challenges in Provisioning There are two major challenges everyone faces when trying to improve their provisioning practices: technical complexity and organizational complexity. 1. Technical complexity — Different infrastructure providers use different interfaces to provision new resources, and the inconsistency between these interfaces imposes extra costs on daily operations. These costs get worse as you add more infrastructure providers and more collaborators. Terraform addresses this complexity by separating the provisioning workload. It uses a single core engine to read infrastructure as code configurations and determine the relationships between resources, then uses many [provider plugins](/terraform/language/providers) to create, modify, and destroy resources on the infrastructure providers. These provider plugins can talk to IaaS (e.g. AWS, GCP, Microsoft Azure, OpenStack), PaaS (e.g. Heroku), or SaaS services (e.g. GitHub, DNSimple, Cloudflare). In other words, Terraform uses a model of workflow-level abstraction, rather than resource-level abstraction. It lets you use a single workflow for managing infrastructure, but acknowledges the uniqueness of each provider instead of imposing generic concepts on non-equivalent resources. 1. Organizational complexity — As infrastructure scales, it requires more teams to maintain it. For effective collaboration, it's important to delegate ownership of infrastructure across these teams and empower them to work in parallel without conflict. Terraform and HCP Terraform can help delegate infrastructure in the same way components of a large application are delegated. To delegate a large application, companies often split it into small, focused microservice components that are owned by specific teams. Each microservice provides an API, and as long as those APIs don't change, microservice teams can make changes in parallel despite relying on each others' functionality. Similarly, infrastructure code can be split into smaller Terraform configurations, which have limited scope and are owned by specific teams. These independent configurations use [output variables](/terraform/language/values/outputs) to publish information and [remote state resources](/terraform/language/state/remote-state-data) to access output data from other workspaces. Just like microservices communicate and connect via APIs, Terraform workspaces connect via remote state. Once you have loosely-coupled Terraform configurations, you can delegate their development and maintenance to different teams. To do this effectively, you need to control access to that code. Version control systems can regulate who can commit code, but since Terraform affects real infrastructure, you also need to regulate who can run the code. This is how HCP Terraform solves the organizational complexity of provisioning: by providing a centralized run environment for Terraform that supports and enforces your organization's access control decisions across all workspaces. This helps you delegate infrastructure ownership to enable parallel development. ## Personas, Responsibilities, and Desired User Experiences There are four main personas for managing infrastructure at scale. These roles have different responsibilities and needs, and HCP Terraform supports them with different tools and permissions. ### Central IT This team is responsible for defining common infrastructure practices, enforcing policy across teams, and maintaining shared services. Central IT users want a single dashboard to view the status and compliance of all infrastructure, so they can quickly fix misconfigurations or malfunctions. Since HCP Terraform is tightly integrated with Terraform's run data and is designed around Terraform's concepts of workspaces and runs, it offers a more integrated workflow experience than a general-purpose CI system. ### Organization Architect This team defines how global infrastructure is divided and delegated to the teams within the business unit. This team also enables connectivity between workspaces by defining the APIs each workspace must expose, and sets organization-wide variables and policies. Organization Architects want a single dashboard to view the status of all workspaces and the graph of connectivity between them. ### Workspace Owner This individual owns a specific set of workspaces, which build a given Terraform configuration across several environments. They are responsible for the health of those workspaces, managing the full change lifecycle through dev, UAT, staging, and production. They are the main approver of changes to production within their domain. Workspace Owners want: * A single dashboard to view the status of all workspaces that use their infrastructure code. * A streamlined way to promote changes between environments. * An interface to set variables used by a Terraform configuration across environments. ### Workspace Contributor Contributors submit changes to workspaces by making updates to the infrastructure as code configuration. They usually do not have approval to make changes to production, but can make changes in dev, UAT, and staging. Workspace Contributors want a simple workflow to submit changes to a workspace and promote changes between workspaces. They can edit a subset of workspace variables and their own personal variables. Workspace contributors are often already familiar with Terraform's operating model and command line interface, and can usually adapt quickly to HCP Terraform's web interface. ## The Recommended Terraform Workspace Structure ### About Workspaces HCP Terraform's main unit of organization is a workspace. A workspace is a collection of everything Terraform needs to run: a Terraform configuration (usually from a VCS repo), values for that configuration's variables, and state data to keep track of operations between runs. In Terraform Community edition, a workspace is an independent state file on the local disk. In HCP Terraform, they're persistent shared resources; you can assign them their own access controls, monitor their run states, and more. ### One Workspace Per Environment Per Terraform Configuration Workspaces are HCP Terraform's primary tool for delegating control, which means their structure should match your organizational permissions structure. The best approach is to use one workspace for each environment of a given infrastructure component. Or in other words, Terraform configurations \* environments = workspaces. This is different from how some other tools view environments; notably, you shouldn't use a single Terraform workspace to manage everything that makes up your production or staging environment. Instead, make smaller workspaces that are easy to delegate. This also means not every configuration has to use the exact same environments; if a UAT environment doesn't make sense for your security infrastructure, you aren't forced to use one. Name your workspaces with both their component and their environment. For example, if you have a Terraform configuration for managing an internal billing app and another for your networking infrastructure, you could name the workspaces as follows: * billing-app-dev * billing-app-stage * billing-app-prod * networking-dev * networking-stage * networking-prod ### Delegating Workspaces Since each workspace is one environment of one infrastructure component, you can use per-workspace access controls to delegate ownership of components and regulate code promotion across environments. For example: * Teams that help manage a component can start Terraform runs and edit variables in dev or staging. * The owners or senior contributors of a component can start Terraform runs in production, after reviewing other contributors' work. * Central IT and organization architects can administer permissions on all workspaces, to ensure everyone has what they need to work. * Teams that have no role managing a given component don't have access to its workspaces. To use HCP Terraform effectively, you must make sure the division of workspaces and permissions matches your organization's division of responsibilities. If it's difficult to separate your workspaces effectively, it might reveal an area of your infrastructure where responsibility is muddled and unclear. If so, this is a chance to disentangle the code and enforce better boundaries of ownership. ## Next Now that you're familiar with the outlines of the HCP Terraform workflow, it's time to assess your organization's provisioning practices. Continue on to [Part 2: Evaluating Your Current Provisioning Practices](/terraform/cloud-docs/recommended-practices/part2).
terraform
page title Part 1 Overview of Our Recommended Workflow Terraform Recommended Practices tfc only true description Learn about our recommended Terraform workflow in this recommended practices guide Part 1 An Overview of Our Recommended Workflow Terraform s purpose is to provide one workflow to provision any infrastructure In this section we ll show you our recommended practices for organizing Terraform usage across a large organization This is the set of practices that we call collaborative infrastructure as code Fundamental Challenges in Provisioning There are two major challenges everyone faces when trying to improve their provisioning practices technical complexity and organizational complexity 1 Technical complexity Different infrastructure providers use different interfaces to provision new resources and the inconsistency between these interfaces imposes extra costs on daily operations These costs get worse as you add more infrastructure providers and more collaborators Terraform addresses this complexity by separating the provisioning workload It uses a single core engine to read infrastructure as code configurations and determine the relationships between resources then uses many provider plugins terraform language providers to create modify and destroy resources on the infrastructure providers These provider plugins can talk to IaaS e g AWS GCP Microsoft Azure OpenStack PaaS e g Heroku or SaaS services e g GitHub DNSimple Cloudflare In other words Terraform uses a model of workflow level abstraction rather than resource level abstraction It lets you use a single workflow for managing infrastructure but acknowledges the uniqueness of each provider instead of imposing generic concepts on non equivalent resources 1 Organizational complexity As infrastructure scales it requires more teams to maintain it For effective collaboration it s important to delegate ownership of infrastructure across these teams and empower them to work in parallel without conflict Terraform and HCP Terraform can help delegate infrastructure in the same way components of a large application are delegated To delegate a large application companies often split it into small focused microservice components that are owned by specific teams Each microservice provides an API and as long as those APIs don t change microservice teams can make changes in parallel despite relying on each others functionality Similarly infrastructure code can be split into smaller Terraform configurations which have limited scope and are owned by specific teams These independent configurations use output variables terraform language values outputs to publish information and remote state resources terraform language state remote state data to access output data from other workspaces Just like microservices communicate and connect via APIs Terraform workspaces connect via remote state Once you have loosely coupled Terraform configurations you can delegate their development and maintenance to different teams To do this effectively you need to control access to that code Version control systems can regulate who can commit code but since Terraform affects real infrastructure you also need to regulate who can run the code This is how HCP Terraform solves the organizational complexity of provisioning by providing a centralized run environment for Terraform that supports and enforces your organization s access control decisions across all workspaces This helps you delegate infrastructure ownership to enable parallel development Personas Responsibilities and Desired User Experiences There are four main personas for managing infrastructure at scale These roles have different responsibilities and needs and HCP Terraform supports them with different tools and permissions Central IT This team is responsible for defining common infrastructure practices enforcing policy across teams and maintaining shared services Central IT users want a single dashboard to view the status and compliance of all infrastructure so they can quickly fix misconfigurations or malfunctions Since HCP Terraform is tightly integrated with Terraform s run data and is designed around Terraform s concepts of workspaces and runs it offers a more integrated workflow experience than a general purpose CI system Organization Architect This team defines how global infrastructure is divided and delegated to the teams within the business unit This team also enables connectivity between workspaces by defining the APIs each workspace must expose and sets organization wide variables and policies Organization Architects want a single dashboard to view the status of all workspaces and the graph of connectivity between them Workspace Owner This individual owns a specific set of workspaces which build a given Terraform configuration across several environments They are responsible for the health of those workspaces managing the full change lifecycle through dev UAT staging and production They are the main approver of changes to production within their domain Workspace Owners want A single dashboard to view the status of all workspaces that use their infrastructure code A streamlined way to promote changes between environments An interface to set variables used by a Terraform configuration across environments Workspace Contributor Contributors submit changes to workspaces by making updates to the infrastructure as code configuration They usually do not have approval to make changes to production but can make changes in dev UAT and staging Workspace Contributors want a simple workflow to submit changes to a workspace and promote changes between workspaces They can edit a subset of workspace variables and their own personal variables Workspace contributors are often already familiar with Terraform s operating model and command line interface and can usually adapt quickly to HCP Terraform s web interface The Recommended Terraform Workspace Structure About Workspaces HCP Terraform s main unit of organization is a workspace A workspace is a collection of everything Terraform needs to run a Terraform configuration usually from a VCS repo values for that configuration s variables and state data to keep track of operations between runs In Terraform Community edition a workspace is an independent state file on the local disk In HCP Terraform they re persistent shared resources you can assign them their own access controls monitor their run states and more One Workspace Per Environment Per Terraform Configuration Workspaces are HCP Terraform s primary tool for delegating control which means their structure should match your organizational permissions structure The best approach is to use one workspace for each environment of a given infrastructure component Or in other words Terraform configurations environments workspaces This is different from how some other tools view environments notably you shouldn t use a single Terraform workspace to manage everything that makes up your production or staging environment Instead make smaller workspaces that are easy to delegate This also means not every configuration has to use the exact same environments if a UAT environment doesn t make sense for your security infrastructure you aren t forced to use one Name your workspaces with both their component and their environment For example if you have a Terraform configuration for managing an internal billing app and another for your networking infrastructure you could name the workspaces as follows billing app dev billing app stage billing app prod networking dev networking stage networking prod Delegating Workspaces Since each workspace is one environment of one infrastructure component you can use per workspace access controls to delegate ownership of components and regulate code promotion across environments For example Teams that help manage a component can start Terraform runs and edit variables in dev or staging The owners or senior contributors of a component can start Terraform runs in production after reviewing other contributors work Central IT and organization architects can administer permissions on all workspaces to ensure everyone has what they need to work Teams that have no role managing a given component don t have access to its workspaces To use HCP Terraform effectively you must make sure the division of workspaces and permissions matches your organization s division of responsibilities If it s difficult to separate your workspaces effectively it might reveal an area of your infrastructure where responsibility is muddled and unclear If so this is a chance to disentangle the code and enforce better boundaries of ownership Next Now that you re familiar with the outlines of the HCP Terraform workflow it s time to assess your organization s provisioning practices Continue on to Part 2 Evaluating Your Current Provisioning Practices terraform cloud docs recommended practices part2
terraform Part 2 Evaluating Your Current Provisioning Practices Practices page title Use a quiz to evaluate your current Terraform provisioning practices Learn whether your practices are mostly manual semi automated infrastructure as code or collaborative infrastructure as code tfc only true Part 2 Evaluating Your Current Provisioning Practices Terraform Recommended
--- page_title: >- Part 2: Evaluating Your Current Provisioning Practices - Terraform Recommended Practices tfc_only: true description: >- Use a quiz to evaluate your current Terraform provisioning practices. Learn whether your practices are mostly manual, semi-automated, infrastructure-as-code, or collaborative infrastructure-as-code. --- # Part 2: Evaluating Your Current Provisioning Practices HCP Terraform depends on several foundational IT practices. Before you can implement HCP Terraform's collaborative infrastructure as code workflows, you need to understand which of those practices you're already using, and which ones you still need to implement. We've written the section below in the form of a quiz or interview, with multiple-choice answers that represent the range of operational maturity levels we've seen across many organizations. You should read it with a notepad handy, and take note of any questions where your organization can improve its use of automation and collaboration. This quiz doesn't have a passing or failing score, but it's important to know your organization's answers. Once you know which of your IT practices need the most attention, Section 3 will guide you from your current state to our recommended practices in the most direct way. ## Four Levels of Operational Maturity Each question has several answers, each of which aligns with a different level of operational maturity. Those levels are as follows: 1. **Manual** * Infrastructure is provisioned through a UI or CLI. * Configuration changes do not leave a traceable history, and aren't always visible. * Limited or no naming standards in place. 1. **Semi-automated** * Infrastructure is provisioned through a combination of UI/CLI, infrastructure as code, and scripts or configuration management. * Traceability is limited, since different record-keeping methods are used across the organization. * Rollbacks are hard to achieve due to differing record-keeping methods. 1. **Infrastructure as code** * Infrastructure is provisioned using Terraform OSS. * Provisioning and deployment processes are automated. * Infrastructure configuration is consistent, with all necessary details fully documented (nothing siloed in a sysadmin's head). * Source files are stored in version control to record editing history, and, if necessary, roll back to older versions. * Some Terraform code is split out into modules, to promote consistent reuse of your organization's more common architectural patterns. 1. **Collaborative infrastructure as code** * Users across the organization can safely provision infrastructure with Terraform, without conflicts and with clear understanding of their access permissions. * Expert users within an organization can produce standardized infrastructure templates, and beginner users can consume those to follow infrastructure best practices for the organization. * Per-workspace access control helps committers and approvers on workspaces protect production environments. * Functional groups that don't directly write Terraform code have visibility into infrastructure status and changes through HCP Terraform's UI. By the end of this section, you should have a clear understanding of which operational maturity stage you are in. Section 3 will explain the recommended steps to move from your current stage to the next one. Answering these questions will help you understand your organization's method for provisioning infrastructure, its change workflow, its operation model, and its security model. Once you understand your current practices, you can identify the remaining steps for implementing HCP Terraform. ## Your Current Configuration and Provisioning Practices How does your organization configure and provision infrastructure today? Automated and consistent practices help make your infrastructure more knowable and reliable, and reduce the amount of time spent on troubleshooting. The following questions will help you evaluate your current level of automation for configuration and provisioning. ### Q1. How do you currently manage your infrastructure? 1. Through a UI or CLI. This might seem like the easiest option for one-off tasks, but for recurring operations it is a big consumer of valuable engineering time. It's also difficult to track and manage changes. 1. Through reusable command line scripts, or a combination of UI and infrastructure as code. This is faster and more reliable than pure ad-hoc management and makes recurring operations repeatable, but the lack of consistency and versioning makes it difficult to manage over time. 1. Through an infrastructure as code tool (Terraform, CloudFormation). Infrastructure as code enables scalable, repeatable, and versioned infrastructure. It dramatically increases the productivity of each operator and can enforce consistency across environments when used appropriately. 1. Through a general-purpose automation framework (i.e. Jenkins + scripts / Jenkins + Terraform). This centralizes the management workflow, albeit with a tool that isn't built specifically for provisioning tasks. ### Q2. What topology is in place for your service provider accounts? 1. Flat structure, single account. All infrastructure is provisioned within the same account. 1. Flat structure, multiple accounts. Infrastructure is provisioned using different infrastructure providers, with an account per environment. 1. Tree hierarchy. This features a master billing account, an audit/security/logging account, and project/environment-specific infrastructure accounts. ### Q3. How do you manage the infrastructure for different environments? 1. Manual. Everything is manual, with no configuration management in place. 1. Siloed. Each application team has its own way of managing infrastructure — some manually, some using infrastructure as code or custom scripts. 1. Infrastructure as code with different code bases per environment. Having different code bases for infrastructure as code configurations can lead to untracked changes from one environment to the other if there is no promotion within environments. 1. Infrastructure as code with a single code base and differing environment variables. All resources, regardless of environment, are provisioned with the same code, ensuring that changes promote through your deployment tiers in a predictable way. ### Q4. How do teams collaborate and share infrastructure configuration and code? 1. N/A. Infrastructure as code is not used. 1. Locally. Infrastructure configuration is hosted locally and shared via email, documents or spreadsheets. 1. Ticketing system. Code is shared through journal entries in change requests or problem/incident tickets. 1. Centralized without version control. Code is stored on a shared filesystem and secured through security groups. Changes are not versioned. Rollbacks are only possible through restores from backups or snapshots. 1. Configuration stored and collaborated in a version control system (VCS) (Git repositories, etc.). Teams collaborate on infrastructure configurations within a VCS workflow, and can review infrastructure changes before they enter production. This is the most mature approach, as it offers the best record-keeping and cross-department/cross-team visibility. ### Q5. Do you use reusable modules for writing infrastructure as code? 1. Everything is manual. No infrastructure as code currently used. 1. No modularity. Infrastructure as code is used, but primarily as one-off configurations. Users usually don't share or re-use code. 1. Teams use modules internally but do not share them across teams. 1. Modules are shared organization-wide. Similar to shared software libraries, a module for a common infrastructure pattern can be updated once and the entire organization benefits. ## Your Current Change Control Workflow Change control is a formal process to coordinate and approve changes to a product or system. The goals of a change control process include: * Minimizing disruption to services. * Reducing rollbacks. * Reducing the overall cost of changes. * Preventing unnecessary changes. * Allowing users to make changes without impacting changes made by other users. The following questions will help you assess the maturity of your change control workflow. ### Q6. How do you govern the access to control changes to infrastructure? 1. Access is not restricted or audited. Everyone in the platform team has the flexibility to create, change, and destroy all infrastructure. This leads to a complex system that is unstable and hard to manage. 1. Access is not restricted, only audited. This makes it easier to track changes after the fact, but doesn't proactively protect your infrastructure's stability. 1. Access is restricted based on service provider account level. Members of the team have admin access to different accounts based on the environment they are responsible for. 1. Access is restricted based on user roles. All access is restricted based on user roles at infrastructure provider level. ### Q7. What is the process for changing existing infrastructure? 1. Manual changes by remotely logging into machines. Repetitive manual tasks are inefficient and prone to human errors. 1. Runtime configuration management (Puppet, Chef, etc.). Configuration management tools let you make fast, automated changes based on readable and auditable code. However, since they don't produce static artifacts, the outcome of a given configuration version isn't always 100% repeatable, making rollbacks only partially reliable. 1. Immutable infrastructure (images, containers). Immutable components can be replaced for every deployment (rather than being updated in-place), using static deployment artifacts. If you maintain sharp boundaries between ephemeral layers and state-storing layers, immutable infrastructure can be much easier to test, validate, and roll back. ### Q8. How do you deploy applications? 1. Manually (SSH, WinRM, rsync, robocopy, etc.). Repetitive manual tasks are inefficient and prone to human errors. 1. With scripts (Fabric, Capistrano, custom, etc.). 1. With a configuration management tool (Chef, Puppet, Ansible, Salt, etc.), or by passing userdata scripts to CloudFormation Templates or Terraform configuration files. 1. With a scheduler (Kubernetes, Nomad, Mesos, Swarm, ECS, etc.). ## Your Current Security Model ### Q9. How are infrastructure service provider credentials managed? 1. By hardcoding them in the source code. This is highly insecure. 1. By using infrastructure provider roles (like EC2 instance roles for AWS).Since the service provider knows the identity of the machines it's providing, you can grant some machines permission to make API requests without giving them a copy of your actual credentials. 1. By using a secrets management solution (like Vault, Keywhis, or PAR).We recommend this. 1. By using short-lived tokens. This is one of the most secure methods, since the temporary credentials you distribute expire quickly and are very difficult to exploit. However, this can be more complex to use than a secrets management solution. ### Q10. How do you control users and objects hosted by your infrastructure provider (like logins, access and role control, etc.)? 1. A common 'admin' or 'superuser' account shared by engineers. This increases the possibility of a breach into your infrastructure provider account. 1. Individual named user accounts. This makes a loss of credentials less likely and easier to recover from, but it doesn't scale very well as the team grows. 1. LDAP and/or Microsoft Entra ID integration. This is much more secure than shared accounts, but requires additional architectural considerations to ensure that the provider's access into your corporate network is configured correctly. 1. Single sign-on through OAuth or SAML. This provides token-based access into your infrastructure provider while not requiring your provider to have access to your corporate network. ### Q11. How do you track the changes made by different users in your infrastructure provider's environments? 1. No logging in place. Auditing and troubleshooting can be very difficult without a record of who made which changes when. 1. Manual changelog. Users manually write down their changes to infrastructure in a shared document. This method is prone to human error. 1. By logging all API calls to an audit trail service or log management service (like CloudTrail, Loggly, or Splunk). We recommend this. This ensures that an audit trail is available during troubleshooting and/or security reviews. ### Q12. How is the access of former employees revoked? 1. Immediately, manually. If you don't use infrastructure as code, the easiest and quickest way is by removing access for that employee manually using the infrastructure provider's console. 1. Delayed, as part of the next release. if your release process is extremely coupled and most of your security changes have to pass through a CAB (Change Advisory Board) meeting in order to be executed in production, this could be delayed. 1. Immediately, writing a hot-fix in the infrastructure as code. this is the most secure and recommended option. Before the employee leaves the building, access must be removed. ## Assessing the Overall Maturity of Your Provisioning Practices After reviewing all of these questions, look back at your notes and assess your organization's overall stage of maturity: are your practices mostly manual, semi-automated, infrastructure as code, or collaborative infrastructure as code? Keep your current state in mind as you read the next section. ## Next Now that you've taken a hard look at your current practices, it's time to begin improving them. Continue on to [Part 3: How to Evolve Your Provisioning Practices](/terraform/cloud-docs/recommended-practices/part3).
terraform
page title Part 2 Evaluating Your Current Provisioning Practices Terraform Recommended Practices tfc only true description Use a quiz to evaluate your current Terraform provisioning practices Learn whether your practices are mostly manual semi automated infrastructure as code or collaborative infrastructure as code Part 2 Evaluating Your Current Provisioning Practices HCP Terraform depends on several foundational IT practices Before you can implement HCP Terraform s collaborative infrastructure as code workflows you need to understand which of those practices you re already using and which ones you still need to implement We ve written the section below in the form of a quiz or interview with multiple choice answers that represent the range of operational maturity levels we ve seen across many organizations You should read it with a notepad handy and take note of any questions where your organization can improve its use of automation and collaboration This quiz doesn t have a passing or failing score but it s important to know your organization s answers Once you know which of your IT practices need the most attention Section 3 will guide you from your current state to our recommended practices in the most direct way Four Levels of Operational Maturity Each question has several answers each of which aligns with a different level of operational maturity Those levels are as follows 1 Manual Infrastructure is provisioned through a UI or CLI Configuration changes do not leave a traceable history and aren t always visible Limited or no naming standards in place 1 Semi automated Infrastructure is provisioned through a combination of UI CLI infrastructure as code and scripts or configuration management Traceability is limited since different record keeping methods are used across the organization Rollbacks are hard to achieve due to differing record keeping methods 1 Infrastructure as code Infrastructure is provisioned using Terraform OSS Provisioning and deployment processes are automated Infrastructure configuration is consistent with all necessary details fully documented nothing siloed in a sysadmin s head Source files are stored in version control to record editing history and if necessary roll back to older versions Some Terraform code is split out into modules to promote consistent reuse of your organization s more common architectural patterns 1 Collaborative infrastructure as code Users across the organization can safely provision infrastructure with Terraform without conflicts and with clear understanding of their access permissions Expert users within an organization can produce standardized infrastructure templates and beginner users can consume those to follow infrastructure best practices for the organization Per workspace access control helps committers and approvers on workspaces protect production environments Functional groups that don t directly write Terraform code have visibility into infrastructure status and changes through HCP Terraform s UI By the end of this section you should have a clear understanding of which operational maturity stage you are in Section 3 will explain the recommended steps to move from your current stage to the next one Answering these questions will help you understand your organization s method for provisioning infrastructure its change workflow its operation model and its security model Once you understand your current practices you can identify the remaining steps for implementing HCP Terraform Your Current Configuration and Provisioning Practices How does your organization configure and provision infrastructure today Automated and consistent practices help make your infrastructure more knowable and reliable and reduce the amount of time spent on troubleshooting The following questions will help you evaluate your current level of automation for configuration and provisioning Q1 How do you currently manage your infrastructure 1 Through a UI or CLI This might seem like the easiest option for one off tasks but for recurring operations it is a big consumer of valuable engineering time It s also difficult to track and manage changes 1 Through reusable command line scripts or a combination of UI and infrastructure as code This is faster and more reliable than pure ad hoc management and makes recurring operations repeatable but the lack of consistency and versioning makes it difficult to manage over time 1 Through an infrastructure as code tool Terraform CloudFormation Infrastructure as code enables scalable repeatable and versioned infrastructure It dramatically increases the productivity of each operator and can enforce consistency across environments when used appropriately 1 Through a general purpose automation framework i e Jenkins scripts Jenkins Terraform This centralizes the management workflow albeit with a tool that isn t built specifically for provisioning tasks Q2 What topology is in place for your service provider accounts 1 Flat structure single account All infrastructure is provisioned within the same account 1 Flat structure multiple accounts Infrastructure is provisioned using different infrastructure providers with an account per environment 1 Tree hierarchy This features a master billing account an audit security logging account and project environment specific infrastructure accounts Q3 How do you manage the infrastructure for different environments 1 Manual Everything is manual with no configuration management in place 1 Siloed Each application team has its own way of managing infrastructure some manually some using infrastructure as code or custom scripts 1 Infrastructure as code with different code bases per environment Having different code bases for infrastructure as code configurations can lead to untracked changes from one environment to the other if there is no promotion within environments 1 Infrastructure as code with a single code base and differing environment variables All resources regardless of environment are provisioned with the same code ensuring that changes promote through your deployment tiers in a predictable way Q4 How do teams collaborate and share infrastructure configuration and code 1 N A Infrastructure as code is not used 1 Locally Infrastructure configuration is hosted locally and shared via email documents or spreadsheets 1 Ticketing system Code is shared through journal entries in change requests or problem incident tickets 1 Centralized without version control Code is stored on a shared filesystem and secured through security groups Changes are not versioned Rollbacks are only possible through restores from backups or snapshots 1 Configuration stored and collaborated in a version control system VCS Git repositories etc Teams collaborate on infrastructure configurations within a VCS workflow and can review infrastructure changes before they enter production This is the most mature approach as it offers the best record keeping and cross department cross team visibility Q5 Do you use reusable modules for writing infrastructure as code 1 Everything is manual No infrastructure as code currently used 1 No modularity Infrastructure as code is used but primarily as one off configurations Users usually don t share or re use code 1 Teams use modules internally but do not share them across teams 1 Modules are shared organization wide Similar to shared software libraries a module for a common infrastructure pattern can be updated once and the entire organization benefits Your Current Change Control Workflow Change control is a formal process to coordinate and approve changes to a product or system The goals of a change control process include Minimizing disruption to services Reducing rollbacks Reducing the overall cost of changes Preventing unnecessary changes Allowing users to make changes without impacting changes made by other users The following questions will help you assess the maturity of your change control workflow Q6 How do you govern the access to control changes to infrastructure 1 Access is not restricted or audited Everyone in the platform team has the flexibility to create change and destroy all infrastructure This leads to a complex system that is unstable and hard to manage 1 Access is not restricted only audited This makes it easier to track changes after the fact but doesn t proactively protect your infrastructure s stability 1 Access is restricted based on service provider account level Members of the team have admin access to different accounts based on the environment they are responsible for 1 Access is restricted based on user roles All access is restricted based on user roles at infrastructure provider level Q7 What is the process for changing existing infrastructure 1 Manual changes by remotely logging into machines Repetitive manual tasks are inefficient and prone to human errors 1 Runtime configuration management Puppet Chef etc Configuration management tools let you make fast automated changes based on readable and auditable code However since they don t produce static artifacts the outcome of a given configuration version isn t always 100 repeatable making rollbacks only partially reliable 1 Immutable infrastructure images containers Immutable components can be replaced for every deployment rather than being updated in place using static deployment artifacts If you maintain sharp boundaries between ephemeral layers and state storing layers immutable infrastructure can be much easier to test validate and roll back Q8 How do you deploy applications 1 Manually SSH WinRM rsync robocopy etc Repetitive manual tasks are inefficient and prone to human errors 1 With scripts Fabric Capistrano custom etc 1 With a configuration management tool Chef Puppet Ansible Salt etc or by passing userdata scripts to CloudFormation Templates or Terraform configuration files 1 With a scheduler Kubernetes Nomad Mesos Swarm ECS etc Your Current Security Model Q9 How are infrastructure service provider credentials managed 1 By hardcoding them in the source code This is highly insecure 1 By using infrastructure provider roles like EC2 instance roles for AWS Since the service provider knows the identity of the machines it s providing you can grant some machines permission to make API requests without giving them a copy of your actual credentials 1 By using a secrets management solution like Vault Keywhis or PAR We recommend this 1 By using short lived tokens This is one of the most secure methods since the temporary credentials you distribute expire quickly and are very difficult to exploit However this can be more complex to use than a secrets management solution Q10 How do you control users and objects hosted by your infrastructure provider like logins access and role control etc 1 A common admin or superuser account shared by engineers This increases the possibility of a breach into your infrastructure provider account 1 Individual named user accounts This makes a loss of credentials less likely and easier to recover from but it doesn t scale very well as the team grows 1 LDAP and or Microsoft Entra ID integration This is much more secure than shared accounts but requires additional architectural considerations to ensure that the provider s access into your corporate network is configured correctly 1 Single sign on through OAuth or SAML This provides token based access into your infrastructure provider while not requiring your provider to have access to your corporate network Q11 How do you track the changes made by different users in your infrastructure provider s environments 1 No logging in place Auditing and troubleshooting can be very difficult without a record of who made which changes when 1 Manual changelog Users manually write down their changes to infrastructure in a shared document This method is prone to human error 1 By logging all API calls to an audit trail service or log management service like CloudTrail Loggly or Splunk We recommend this This ensures that an audit trail is available during troubleshooting and or security reviews Q12 How is the access of former employees revoked 1 Immediately manually If you don t use infrastructure as code the easiest and quickest way is by removing access for that employee manually using the infrastructure provider s console 1 Delayed as part of the next release if your release process is extremely coupled and most of your security changes have to pass through a CAB Change Advisory Board meeting in order to be executed in production this could be delayed 1 Immediately writing a hot fix in the infrastructure as code this is the most secure and recommended option Before the employee leaves the building access must be removed Assessing the Overall Maturity of Your Provisioning Practices After reviewing all of these questions look back at your notes and assess your organization s overall stage of maturity are your practices mostly manual semi automated infrastructure as code or collaborative infrastructure as code Keep your current state in mind as you read the next section Next Now that you ve taken a hard look at your current practices it s time to begin improving them Continue on to Part 3 How to Evolve Your Provisioning Practices terraform cloud docs recommended practices part3
terraform ServiceNow Service Graph Connector for Terraform Setup Note Follow the Configure ServiceNow Service Graph Connector for HCP Terraform terraform tutorials it saas servicenow sgc tutorial for hands on instructions on how to import an AWS resource deployed in your HCP Terraform organization to the ServiceNow CMDB by using the Service Graph Connector for Terraform ServiceNow Service Graph Connector for Terraform integrates with HCP Terraform and offers two modes of import for Terraform resources page title Overview ServiceNow Service Graph Connector for Terraform Integration summary of the setup process
--- page_title: Overview - ServiceNow Service Graph Connector for Terraform Integration - summary of the setup process description: >- ServiceNow Service Graph Connector for Terraform integrates with HCP Terraform and offers two modes of import for Terraform resources. --- # ServiceNow Service Graph Connector for Terraform – Setup -> **Note:** Follow the [Configure ServiceNow Service Graph Connector for HCP Terraform](/terraform/tutorials/it-saas/servicenow-sgc) tutorial for hands-on instructions on how to import an AWS resource deployed in your HCP Terraform organization to the ServiceNow CMDB by using the Service Graph Connector for Terraform. The ServiceNow Service Graph Connector for Terraform is a certified scoped application available in the ServiceNow Store. Search for ”Service Graph Connector for Terraform” published by ”HashiCorp Inc” and click **Install**. ## Prerequisites To start using the Service Graph Connector for Terraform, you must have: - An administrator account on a Terraform Enterprise instance or within an HCP Terraform organization. - An administrator account on your ServiceNow vendor instance. The Service Graph Connector for Terraform supports the following ServiceNow server versions: - Utah - Vancouver - Washington DC - Xanadu The following ServiceNow plugins are required dependencies: - ITOM Discovery License - Integration Commons for CMDB - Discovery and Service Mapping Patterns - ServiceNow IntegrationHub Standard Pack Additionally, you can install the IntegrationHub ETL application if you want to modify the default CMDB mappings. -> **Note:** Dependent plugins are installed on your ServiceNow instance automatically when the app is downloaded from the ServiceNow Store. Before installing the Service Graph Connector for Terraform, you must activate the ITOM Discovery License plugin in your production instance. ## Connect ServiceNow to HCP Terraform -> **ServiceNow roles:** `admin`, `x_hashi_service_gr.terraform_user` Once the integration is installed, you can proceed to the guided setup form where you will enter your Terraform credentials. This step will establish a secure connection between HCP Terraform and your ServiceNow instance. ### Create and scope Terraform API token In order for ServiceNow to connect to HCP Terraform, you must give it an HCP Terraform API token. The permissions of this token determine what resources the Service Graph Connector will import into the CMDB. While you could use a user API token, it could import resources from multiple organizations. By providing a team API token, you can scope permissions to only import resources from specified workspaces within a single organization. Visit your organization’s **Settings** > **Teams** page. Scroll down to the **Team API Token** section and click **Create a team token**. Save this token in a safe place since HCP Terraform only displays it once. You will use it to configure ServiceNow in the next section. ![ServiceNow Service Graph Connector Configure Team API token in HCP Terraform](/img/docs/service-now-service-graph-team-token-gen.png) ### Configure Service Graph Connector for Terraform API token In the top navigation of your ServiceNow instance's control panel, click on **All**, search for **Service Graph Connector for Terraform**, and click **SG-Setup**. Next, click **Get Started**. Next, in the **Configure the Terraform connection** section, click **Get Started**. In the **Configure Terraform authentication credentials** section, click **Configure**. If you want to route traffic between your HCP Terraform and the ServiceNow instance through a MID server acting as a proxy, change the **Applies to** dropdown to "Specific MID servers" and select your previously configured MID server name. If you don't use MID servers, leave the default value. Set the **API Key** to the HCP Terraform team API token that you created in the previous section and click **Update**. ![ServiceNow Service Graph Connector API Key Credentials configuration screen. The API key is provided, then saved by clicking the Update button](/img/docs/service-now-service-graph-apikey.png) In the **Configure Terraform authentication credentials** section, click **Mark as Complete**. ### Configure Terraform Webhook Notification token To improve security, HCP Terraform includes an HMAC signature on all "generic" webhook notifications using a user-provided **token**. This token is an arbitrary secret string that HCP Terraform uses to sign each webhook notification. ServiceNow uses the same token to verify the request authenticity. Refer to [Notification Authenticity](/terraform/cloud-docs/api-docs/notification-configurations#notification-authenticity) for more information. Create a token and save it in a safe place. This secret token can be any value but should be treated as sensitive. In the **Configure Terraform Webhook token** section, click **Configure**. In the **Token** field, enter the secret token that will be shared between the HCP Terraform and your ServiceNow instance and click **Update**. ![ServiceNow Service Graph Connector Webhook token configuration screen. The Token is provided, then saved by clicking the Update button](/img/docs/service-now-service-graph-webhook-token.png) In the **Configure Terraform Webhook token** section, click **Mark as Complete**. ### Configure Terraform connection In the **Configure Terraform connection** section, click **Configure**. If you are using Terraform Enterprise, set the **Connection URL** to the URL of your Terraform Enterprise instance. If you are using HCP Terraform, leave the **Connection URL** as the default value of `https://app.terraform.io`. ![ServiceNow Service Graph Connector HTTP Connection configuration screen. A Terraform Enterprise URL may be provided in the Connection URL field, the saved by clicking the Update button](/img/docs/service-now-service-graph-tfconn.png) If you want to use a MID server, check **Use MID server** box, change **MID Selection** dropdown to "Specific MID sever" and select your previously configured and validated MID server. Click **Update** to save these settings. In the **Configure Terraform connection** section, click **Mark as Complete**. ## Import Resources Refer to the documentation explaining the difference between the [two modes of import](/terraform/cloud-docs/integrations/service-now/service-graph#import-methods) offered by the Service Graph Connector for Terraform. Both options may be enabled, or you may choose to enable only the webhook or scheduled import. ### Configure scheduled import In the **Set up scheduled import job** section of the setup form, proceed to **Configure the scheduled jobs** and click **Configure**. You can use the **Execute Now** option to run a single import job, which is useful for testing. The import set will be displayed in the table below the scheduled import form, after refreshing the page. Once the import is successfully triggered, click on the **Import Set** field of the record to view the logs associated with the import run, as well as its status. Activate the job by checking the **Activate** box. Set the **Repeat Interval** and click **Update**. Note that the import processing time depends of the number of organizations and workspaces in your HCP Terraform. Setting the import job to run frequently is not recommended for big environments. ![ServiceNow Service Graph Connector scheduled import screen](/img/docs/service-now-service-graph-scheduled-import.png) You can also access the scheduler interface by searching for **Service Graph Connector for Terraform** in the top navigation menu and selecting **SG-Import Schedule**. ### Configure Terraform Webhook In the top navigation, click on **All**, search for **Scheduled Imports**, and click on **Scheduled Imports**. Select the **SG-Terraform Scheduled Process State** record, then click **To edit the record click here**. Click the **Active** checkbox to enable it. Leave the default value for the **Repeat Interval** of 5 seconds. Click **Update**. ![ServiceNow Service Graph Connector scheduled import screen showing the Active checkbox enabled](/img/docs/service-now-service-graph-webhook-schedule.png) Next, create the webhook in HCP Terraform. Select a workspace and click **Settings > Notifications**. Click **Create a Notification**. Keep the **Destination** as the default option of **Webhook**. Choose a descriptive name **Name**. Set the **Webhook URL** enter `https://<SERVICENOW_HOSTNAME>/api/x_hashi_service_gr/sg_terraform_webhook` and replace `<SERVICENOW_HOSTNAME>` with the hostname of your ServiceNow instance. In the **Token** field, enter the same string you provided in **Terraform Webhook token** section the of the Service Graph guided setup form. Under **Health Events** choose **No events**. Under **Run Events** choose **Only certain events** and enable notifications only on **Completed** runs. Click **Create Notification**. ![HCP Terraform notification creation screen, showing a webhook pointing to ServiceNow which is only triggered on completed runs](/img/docs/service-now-service-graph-webhook-tfc.png) Trigger a run in your workspace. Once the run is successfully completed, a webhook notification request will be sent to your ServiceNow instance. ### Monitor the import job By following these steps, you can track the status of import jobs in ServiceNow and verify the completion of the import process before accessing the imported resources in the CMDB. For scheduled imports, navigate back to the **SG-Import Schedule** interface. For webhook imports, go to the **SG-Terraform Scheduled Process State** interface. Under the form, you will find a table containing all registered import sets. Locate and select the relevant import set record. Click on the **Import Set** field to open it and view its details. The **Outbound Http Requests** tab lists all requests made by your ServiceNow instance to HCP Terraform in order to retrieve the latest Terraform state. Monitor the state of the import job. Wait for it to change to **Complete**, indicated by a green mark. Once the import job is complete, you can access the imported resources in the CMDB. ![ServiceNow Service Graph Connector: import set with successfully completed status](/img/docs/service-now-service-graph-import-set.png) You can also access all import sets, regardless of the import type, by navigating to **All** and selecting **Import Sets** under the **Advanced** category. ### View resources in ServiceNow CMDB In the top navigation of ServiceNow, click on **All** and search for **CMDB Workspace**, and click on **CMDB Workspace**. Perform a search by entering a Configuration Item (CI) name in the **Search** field (for example, **Virtual Machine Instance**). CI names supported by the application are listed on the [resource mapping page](/terraform/cloud-docs/integrations/service-now/service-graph/resource-coverage).
terraform
page title Overview ServiceNow Service Graph Connector for Terraform Integration summary of the setup process description ServiceNow Service Graph Connector for Terraform integrates with HCP Terraform and offers two modes of import for Terraform resources ServiceNow Service Graph Connector for Terraform Setup Note Follow the Configure ServiceNow Service Graph Connector for HCP Terraform terraform tutorials it saas servicenow sgc tutorial for hands on instructions on how to import an AWS resource deployed in your HCP Terraform organization to the ServiceNow CMDB by using the Service Graph Connector for Terraform The ServiceNow Service Graph Connector for Terraform is a certified scoped application available in the ServiceNow Store Search for Service Graph Connector for Terraform published by HashiCorp Inc and click Install Prerequisites To start using the Service Graph Connector for Terraform you must have An administrator account on a Terraform Enterprise instance or within an HCP Terraform organization An administrator account on your ServiceNow vendor instance The Service Graph Connector for Terraform supports the following ServiceNow server versions Utah Vancouver Washington DC Xanadu The following ServiceNow plugins are required dependencies ITOM Discovery License Integration Commons for CMDB Discovery and Service Mapping Patterns ServiceNow IntegrationHub Standard Pack Additionally you can install the IntegrationHub ETL application if you want to modify the default CMDB mappings Note Dependent plugins are installed on your ServiceNow instance automatically when the app is downloaded from the ServiceNow Store Before installing the Service Graph Connector for Terraform you must activate the ITOM Discovery License plugin in your production instance Connect ServiceNow to HCP Terraform ServiceNow roles admin x hashi service gr terraform user Once the integration is installed you can proceed to the guided setup form where you will enter your Terraform credentials This step will establish a secure connection between HCP Terraform and your ServiceNow instance Create and scope Terraform API token In order for ServiceNow to connect to HCP Terraform you must give it an HCP Terraform API token The permissions of this token determine what resources the Service Graph Connector will import into the CMDB While you could use a user API token it could import resources from multiple organizations By providing a team API token you can scope permissions to only import resources from specified workspaces within a single organization Visit your organization s Settings Teams page Scroll down to the Team API Token section and click Create a team token Save this token in a safe place since HCP Terraform only displays it once You will use it to configure ServiceNow in the next section ServiceNow Service Graph Connector Configure Team API token in HCP Terraform img docs service now service graph team token gen png Configure Service Graph Connector for Terraform API token In the top navigation of your ServiceNow instance s control panel click on All search for Service Graph Connector for Terraform and click SG Setup Next click Get Started Next in the Configure the Terraform connection section click Get Started In the Configure Terraform authentication credentials section click Configure If you want to route traffic between your HCP Terraform and the ServiceNow instance through a MID server acting as a proxy change the Applies to dropdown to Specific MID servers and select your previously configured MID server name If you don t use MID servers leave the default value Set the API Key to the HCP Terraform team API token that you created in the previous section and click Update ServiceNow Service Graph Connector API Key Credentials configuration screen The API key is provided then saved by clicking the Update button img docs service now service graph apikey png In the Configure Terraform authentication credentials section click Mark as Complete Configure Terraform Webhook Notification token To improve security HCP Terraform includes an HMAC signature on all generic webhook notifications using a user provided token This token is an arbitrary secret string that HCP Terraform uses to sign each webhook notification ServiceNow uses the same token to verify the request authenticity Refer to Notification Authenticity terraform cloud docs api docs notification configurations notification authenticity for more information Create a token and save it in a safe place This secret token can be any value but should be treated as sensitive In the Configure Terraform Webhook token section click Configure In the Token field enter the secret token that will be shared between the HCP Terraform and your ServiceNow instance and click Update ServiceNow Service Graph Connector Webhook token configuration screen The Token is provided then saved by clicking the Update button img docs service now service graph webhook token png In the Configure Terraform Webhook token section click Mark as Complete Configure Terraform connection In the Configure Terraform connection section click Configure If you are using Terraform Enterprise set the Connection URL to the URL of your Terraform Enterprise instance If you are using HCP Terraform leave the Connection URL as the default value of https app terraform io ServiceNow Service Graph Connector HTTP Connection configuration screen A Terraform Enterprise URL may be provided in the Connection URL field the saved by clicking the Update button img docs service now service graph tfconn png If you want to use a MID server check Use MID server box change MID Selection dropdown to Specific MID sever and select your previously configured and validated MID server Click Update to save these settings In the Configure Terraform connection section click Mark as Complete Import Resources Refer to the documentation explaining the difference between the two modes of import terraform cloud docs integrations service now service graph import methods offered by the Service Graph Connector for Terraform Both options may be enabled or you may choose to enable only the webhook or scheduled import Configure scheduled import In the Set up scheduled import job section of the setup form proceed to Configure the scheduled jobs and click Configure You can use the Execute Now option to run a single import job which is useful for testing The import set will be displayed in the table below the scheduled import form after refreshing the page Once the import is successfully triggered click on the Import Set field of the record to view the logs associated with the import run as well as its status Activate the job by checking the Activate box Set the Repeat Interval and click Update Note that the import processing time depends of the number of organizations and workspaces in your HCP Terraform Setting the import job to run frequently is not recommended for big environments ServiceNow Service Graph Connector scheduled import screen img docs service now service graph scheduled import png You can also access the scheduler interface by searching for Service Graph Connector for Terraform in the top navigation menu and selecting SG Import Schedule Configure Terraform Webhook In the top navigation click on All search for Scheduled Imports and click on Scheduled Imports Select the SG Terraform Scheduled Process State record then click To edit the record click here Click the Active checkbox to enable it Leave the default value for the Repeat Interval of 5 seconds Click Update ServiceNow Service Graph Connector scheduled import screen showing the Active checkbox enabled img docs service now service graph webhook schedule png Next create the webhook in HCP Terraform Select a workspace and click Settings Notifications Click Create a Notification Keep the Destination as the default option of Webhook Choose a descriptive name Name Set the Webhook URL enter https SERVICENOW HOSTNAME api x hashi service gr sg terraform webhook and replace SERVICENOW HOSTNAME with the hostname of your ServiceNow instance In the Token field enter the same string you provided in Terraform Webhook token section the of the Service Graph guided setup form Under Health Events choose No events Under Run Events choose Only certain events and enable notifications only on Completed runs Click Create Notification HCP Terraform notification creation screen showing a webhook pointing to ServiceNow which is only triggered on completed runs img docs service now service graph webhook tfc png Trigger a run in your workspace Once the run is successfully completed a webhook notification request will be sent to your ServiceNow instance Monitor the import job By following these steps you can track the status of import jobs in ServiceNow and verify the completion of the import process before accessing the imported resources in the CMDB For scheduled imports navigate back to the SG Import Schedule interface For webhook imports go to the SG Terraform Scheduled Process State interface Under the form you will find a table containing all registered import sets Locate and select the relevant import set record Click on the Import Set field to open it and view its details The Outbound Http Requests tab lists all requests made by your ServiceNow instance to HCP Terraform in order to retrieve the latest Terraform state Monitor the state of the import job Wait for it to change to Complete indicated by a green mark Once the import job is complete you can access the imported resources in the CMDB ServiceNow Service Graph Connector import set with successfully completed status img docs service now service graph import set png You can also access all import sets regardless of the import type by navigating to All and selecting Import Sets under the Advanced category View resources in ServiceNow CMDB In the top navigation of ServiceNow click on All and search for CMDB Workspace and click on CMDB Workspace Perform a search by entering a Configuration Item CI name in the Search field for example Virtual Machine Instance CI names supported by the application are listed on the resource mapping page terraform cloud docs integrations service now service graph resource coverage
terraform Google Cloud Platform This page provides details on how Google Cloud resources set up using Terraform are corresponded to the classes within the ServiceNow CMDB ServiceNow Service Graph integration allows to import selected resources from Google Cloud Platform into ServiceNow CMDB page title ServiceNow Service Graph Connector for Terraform Integration GCP Coverage
--- page_title: ServiceNow Service Graph Connector for Terraform Integration - GCP Coverage description: >- ServiceNow Service Graph integration allows to import selected resources from Google Cloud Platform into ServiceNow CMDB. --- # Google Cloud Platform This page provides details on how Google Cloud resources, set up using Terraform, are corresponded to the classes within the ServiceNow CMDB. ## Mapping of Terraform resources to CMDB CI Classes | Google resource | Terraform resource name | ServiceNow CMDB CI Class | ServiceNow CMDB Category Name | |----------------------------|-----------------------------------------------------------------------|---------------------------------|-------------------------------| | Project ID | N/A | `cmdb_ci_cloud_service_account` | Cloud Service Account | | Region (location) | N/A | `cmdb_ci_google_datacenter` | Google Datacenter | | Virtual Machine Instance | `google_compute_instance` | `cmdb_ci_vm_instance` | Virtual Machine Instance | | Kubernetes Cluster | `google_container_cluster` | `cmdb_ci_kubernetes_cluster` | Kubernetes Cluster | | Google Storage | `google_storage_bucket` | `cmdb_ci_cloud_storage_account` | Cloud Storage Account | | Google BigQuery | `google_bigquery_table` | `cmdb_ci_cloud_database` | Cloud DataBase | | Google SQL | `google_sql_database` | `cmdb_ci_cloud_database` | Cloud DataBase | | Google Compute Firewall | `google_compute_firewall` | `cmdb_ci_compute_security_group`| Compute Security Group | | Cloud Function | `google_cloudfunctions_function` or `google_cloudfunctions2_function` | `cmdb_ci_cloud_function` | Cloud Function | | Load Balancer | `google_compute_forwarding_rule` | `cmdb_ci_cloud_load_balancer` | Cloud Load Balancer | | VPC | `google_compute_network` | `cmdb_ci_network` | Cloud Network | | Tags | N/A | `cmdb_key_value` | Key Value | ## Resource relationships | Child CI Class | Relationship type | Parent CI Class | |------------------------------------------------------------|------------------------|-----------------------------------------------------------| | Google Datacenter 1 (`cmdb_ci_google_datacenter`) | Hosted On::Hosts | Cloud Service Account 4 (`cmdb_ci_cloud_service_account`) | | Google Datacenter 2 (`cmdb_ci_google_datacenter`) | Hosted On::Hosts | Cloud Service Account 4 (`cmdb_ci_cloud_service_account`) | | Virtual Machine Instance 4 (`cmdb_ci_vm_instance`) | Hosted On::Hosts | Google Datacenter 1 (`cmdb_ci_google_datacenter`) | | Virtual Machine Instance 4 (`cmdb_ci_vm_instance`) | Reference | Key Value 13 (`cmdb_key_value`) | | Cloud Network 3 (`cmdb_ci_network`) | Hosted On::Hosts | Google Datacenter 1 (`cmdb_ci_google_datacenter`) | | Cloud Network 3 (`cmdb_ci_network`) | Reference | Key Value 18 (`cmdb_key_value`) | | Compute Security Group 3 (`cmdb_ci_compute_security_group`)| Hosted On::Hosts | Google Datacenter 1 (`cmdb_ci_google_datacenter`) | | Compute Security Group 3 (`cmdb_ci_compute_security_group`)| Reference | Key Value 21 (`cmdb_key_value`) | | Kubernetes Cluster 3 (`cmdb_ci_kubernetes_cluster`) | Hosted On::Hosts | Google Datacenter 1 (`cmdb_ci_google_datacenter`) | | Kubernetes Cluster 3 (`cmdb_ci_kubernetes_cluster`) | Reference | Key Value 22 (`cmdb_key_value`) | | Cloud DataBase 3 (`cmdb_ci_cloud_database` ) | Hosted On::Hosts | Google Datacenter 1 (`cmdb_ci_google_datacenter`) | | Cloud DataBase 2 (`cmdb_ci_cloud_database` ) | Reference | Key Value 24 (`cmdb_key_value`) | | Cloud Function 3 (`cmdb_ci_cloud_function`) | Hosted On::Hosts | Google Datacenter 1 (`cmdb_ci_google_datacenter`) | | Cloud Function 3 (`cmdb_ci_cloud_function`) | Reference | Key Value 25 (`cmdb_key_value`) | | Cloud Load Balancer 2 (`cmdb_ci_cloud_load_balancer`) | Hosted On::Hosts | Google Datacenter 1 (`cmdb_ci_google_datacenter`) | | Cloud Load Balancer 2 (`cmdb_ci_cloud_load_balancer`) | Reference | Key Value 26 (`cmdb_key_value`) | | Cloud Storage Account 2 (`cmdb_ci_cloud_storage_account`) | Hosted On::Hosts | Google Datacenter 2 (`cmdb_ci_google_datacenter`) | | Cloud Storage Account 2 (`cmdb_ci_cloud_storage_account`) | Reference | Key Value 23 (`cmdb_key_value`) | ## Field attributes mapping ### Cloud Service Account (`cmdb_ci_cloud_service_account`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `project` | | Account Id | `project` | | Datacenter Type | Defaults to `google` | | Object ID | `project` | | Name | `project` | | Operational Status| Defaults to "1" ("Operational") | ### Google Datacenter (`cmdb_ci_google_datacenter`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | Concatenation of `project` and region extracted from `id` | | Object Id | Region extracted from `id` | | Region | Region extracted from `id` | | Name | Region extracted from `id` | | Operational Status| Defaults to "1" ("Operational") | ### Virtual Machine Instance (`cmdb_ci_vm_instance`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `id` | | Object Id | `id` | | Name | `name` | | Category | `machine_type` | | Operational Status| Defaults to "1" ("Operational") | ### Cloud Network (`cmdb_ci_network`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `id` | | Object Id | `id` | | Name | `name` | | Operational Status| Defaults to "1" ("Operational") | ### Compute Security Group (`cmdb_ci_compute_security_group`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `id` | | Object Id | `id` | | Name | `name` | | Operational Status| Defaults to "1" ("Operational") | ### Kubernetes Cluster (`cmdb_ci_kubernetes_cluster`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `arn` | | IP Address | `endpoint` | | Port | Defaults to "6443" | | Name | `name` | | Operational Status| Defaults to "1" ("Operational") | ### Cloud Object Storage (`cmdb_ci_cloud_object_storage`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `arn` | | Object Id | `id` | | Cloud Provider | Resource cloud provider extracted from `arn` | | Name | `bucket` | | Operational Status| Defaults to "1" ("Operational") | ### Cloud Storage Account (`cmdb_ci_cloud_storage_account`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `id` | | Object Id | `id` | | Name | `name` | | Name | `location` | | Operational Status| Defaults to "1" ("Operational") | ### Cloud DataBase (`cmdb_ci_cloud_database`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `id` | | Object Id | `id` | | Name | Name extracted from `id` | | Operational Status| Defaults to "1" ("Operational") | ### Cloud Function (`cmdb_ci_cloud_function`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `id` | | Object Id | `id` | | Name | `name` | | Operational Status| Defaults to "1" ("Operational") | ### Cloud Load Balancer (`cmdb_ci_cloud_load_balancer`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `id` | | Object Id | `id` | | Name | `name` | | Operational Status| Defaults to "1" ("Operational")
terraform
page title ServiceNow Service Graph Connector for Terraform Integration GCP Coverage description ServiceNow Service Graph integration allows to import selected resources from Google Cloud Platform into ServiceNow CMDB Google Cloud Platform This page provides details on how Google Cloud resources set up using Terraform are corresponded to the classes within the ServiceNow CMDB Mapping of Terraform resources to CMDB CI Classes Google resource Terraform resource name ServiceNow CMDB CI Class ServiceNow CMDB Category Name Project ID N A cmdb ci cloud service account Cloud Service Account Region location N A cmdb ci google datacenter Google Datacenter Virtual Machine Instance google compute instance cmdb ci vm instance Virtual Machine Instance Kubernetes Cluster google container cluster cmdb ci kubernetes cluster Kubernetes Cluster Google Storage google storage bucket cmdb ci cloud storage account Cloud Storage Account Google BigQuery google bigquery table cmdb ci cloud database Cloud DataBase Google SQL google sql database cmdb ci cloud database Cloud DataBase Google Compute Firewall google compute firewall cmdb ci compute security group Compute Security Group Cloud Function google cloudfunctions function or google cloudfunctions2 function cmdb ci cloud function Cloud Function Load Balancer google compute forwarding rule cmdb ci cloud load balancer Cloud Load Balancer VPC google compute network cmdb ci network Cloud Network Tags N A cmdb key value Key Value Resource relationships Child CI Class Relationship type Parent CI Class Google Datacenter 1 cmdb ci google datacenter Hosted On Hosts Cloud Service Account 4 cmdb ci cloud service account Google Datacenter 2 cmdb ci google datacenter Hosted On Hosts Cloud Service Account 4 cmdb ci cloud service account Virtual Machine Instance 4 cmdb ci vm instance Hosted On Hosts Google Datacenter 1 cmdb ci google datacenter Virtual Machine Instance 4 cmdb ci vm instance Reference Key Value 13 cmdb key value Cloud Network 3 cmdb ci network Hosted On Hosts Google Datacenter 1 cmdb ci google datacenter Cloud Network 3 cmdb ci network Reference Key Value 18 cmdb key value Compute Security Group 3 cmdb ci compute security group Hosted On Hosts Google Datacenter 1 cmdb ci google datacenter Compute Security Group 3 cmdb ci compute security group Reference Key Value 21 cmdb key value Kubernetes Cluster 3 cmdb ci kubernetes cluster Hosted On Hosts Google Datacenter 1 cmdb ci google datacenter Kubernetes Cluster 3 cmdb ci kubernetes cluster Reference Key Value 22 cmdb key value Cloud DataBase 3 cmdb ci cloud database Hosted On Hosts Google Datacenter 1 cmdb ci google datacenter Cloud DataBase 2 cmdb ci cloud database Reference Key Value 24 cmdb key value Cloud Function 3 cmdb ci cloud function Hosted On Hosts Google Datacenter 1 cmdb ci google datacenter Cloud Function 3 cmdb ci cloud function Reference Key Value 25 cmdb key value Cloud Load Balancer 2 cmdb ci cloud load balancer Hosted On Hosts Google Datacenter 1 cmdb ci google datacenter Cloud Load Balancer 2 cmdb ci cloud load balancer Reference Key Value 26 cmdb key value Cloud Storage Account 2 cmdb ci cloud storage account Hosted On Hosts Google Datacenter 2 cmdb ci google datacenter Cloud Storage Account 2 cmdb ci cloud storage account Reference Key Value 23 cmdb key value Field attributes mapping Cloud Service Account cmdb ci cloud service account CMDB field Terraform state field Source Native Key project Account Id project Datacenter Type Defaults to google Object ID project Name project Operational Status Defaults to 1 Operational Google Datacenter cmdb ci google datacenter CMDB field Terraform state field Source Native Key Concatenation of project and region extracted from id Object Id Region extracted from id Region Region extracted from id Name Region extracted from id Operational Status Defaults to 1 Operational Virtual Machine Instance cmdb ci vm instance CMDB field Terraform state field Source Native Key id Object Id id Name name Category machine type Operational Status Defaults to 1 Operational Cloud Network cmdb ci network CMDB field Terraform state field Source Native Key id Object Id id Name name Operational Status Defaults to 1 Operational Compute Security Group cmdb ci compute security group CMDB field Terraform state field Source Native Key id Object Id id Name name Operational Status Defaults to 1 Operational Kubernetes Cluster cmdb ci kubernetes cluster CMDB field Terraform state field Source Native Key arn IP Address endpoint Port Defaults to 6443 Name name Operational Status Defaults to 1 Operational Cloud Object Storage cmdb ci cloud object storage CMDB field Terraform state field Source Native Key arn Object Id id Cloud Provider Resource cloud provider extracted from arn Name bucket Operational Status Defaults to 1 Operational Cloud Storage Account cmdb ci cloud storage account CMDB field Terraform state field Source Native Key id Object Id id Name name Name location Operational Status Defaults to 1 Operational Cloud DataBase cmdb ci cloud database CMDB field Terraform state field Source Native Key id Object Id id Name Name extracted from id Operational Status Defaults to 1 Operational Cloud Function cmdb ci cloud function CMDB field Terraform state field Source Native Key id Object Id id Name name Operational Status Defaults to 1 Operational Cloud Load Balancer cmdb ci cloud load balancer CMDB field Terraform state field Source Native Key id Object Id id Name name Operational Status Defaults to 1 Operational
terraform AWS This page details the mapping rules for importing AWS resources provisioned with Terraform into ServiceNow CMDB page title ServiceNow Service Graph Connector for Terraform Integration AWS Coverage ServiceNow Service Graph integration allows to import selected resources from AWS into ServiceNow CMDB
--- page_title: ServiceNow Service Graph Connector for Terraform Integration - AWS Coverage description: >- ServiceNow Service Graph integration allows to import selected resources from AWS into ServiceNow CMDB. --- # AWS This page details the mapping rules for importing AWS resources, provisioned with Terraform, into ServiceNow CMDB. ## Mapping of Terraform resources to CMDB CI Classes | AWS resource | Terraform resource name | ServiceNow CMDB CI Class | ServiceNow CMDB Category Name | |--------------------------------------------------------------------------------------|----------------------------|---------------------------------|-------------------------------| | AWS account | N/A | `cmdb_ci_cloud_service_account` | Cloud Service Account | | AWS region | N/A | `cmdb_ci_aws_datacenter` | AWS Datacenter | | EC2 Instance | `aws_instance` | `cmdb_ci_vm_instance` | Virtual Machine Instance | | S3 Bucket | `aws_s3_bucket` | `cmdb_ci_cloud_object_storage` | Cloud Object Storage | | ECS Cluster | `aws_ecs_cluster` | `cmdb_ci_cloud_ecs_cluster` | AWS Cloud ECS Cluster | | EKS Cluster | `aws_eks_cluster` | `cmdb_ci_kubernetes_cluster` | Kubernetes Cluster | | VPC | `aws_vpc` | `cmdb_ci_network` | Cloud Network | | Database Instance (*non-Aurora databases: e.g., MySQL, PostgreSQL, SQL Server, etc.*)| `aws_db_instance` | `cmdb_ci_cloud_database` | Cloud DataBase | | RDS Aurora Cluster | `aws_rds_cluster` | `cmdb_ci_cloud_db_cluster` | Cloud DataBase Cluster | | RDS Aurora Instance | `aws_rds_cluster_instance` | `cmdb_ci_cloud_database` | Cloud DataBase | | DynamoDB Global Table | `aws_dynamodb_global_table`| `cmdb_ci_dynamodb_global_table` | DynamoDB Global Table | | DynamoDB Table | `aws_dynamodb_table` | `cmdb_ci_dynamodb_table` | DynamoDB Table | | Security Group | `aws_security_group` | `cmdb_ci_compute_security_group`| Compute Security Group | | Lambda | `aws_lambda_function` | `cmdb_ci_cloud_function` | Cloud Function | | Load Balancer | `aws_lb` | `cmdb_ci_cloud_load_balancer` | Cloud Load Balancer | | Tags | N/A | `cmdb_key_value` | Key Value | ## Resource relationships | Child CI Class | Relationship type| Parent CI Class | |------------------------------------------------------------|------------------|-----------------------------------------------------------| | AWS Datacenter 1 (`cmdb_ci_aws_datacenter`) | Hosted On::Hosts | Cloud Service Account 1 (`cmdb_ci_cloud_service_account`) | | AWS Datacenter 2 (`cmdb_ci_aws_datacenter`) | Hosted On::Hosts | Cloud Service Account 6 (`cmdb_ci_cloud_service_account`) | | Virtual Machine Instance 1 (`cmdb_ci_vm_instance`) | Hosted On::Hosts | AWS Datacenter 1 (`cmdb_ci_aws_datacenter`) | | Virtual Machine Instance 1 (`cmdb_ci_vm_instance`) | Reference | Key Value 1 (`cmdb_key_value`) | | AWS Cloud ECS Cluster 1 (`cmdb_ci_cloud_ecs_cluster`) | Hosted On::Hosts | AWS Datacenter 1 (`cmdb_ci_aws_datacenter`) | | AWS Cloud ECS Cluster 1 (`cmdb_ci_cloud_ecs_cluster`) | Reference | Key Value 2 (`cmdb_key_value`) | | Cloud Object Storage 1 (`cmdb_ci_cloud_object_storage`) | Hosted On::Hosts | AWS Datacenter 2 (`cmdb_ci_aws_datacenter`) | | Cloud Object Storage 1 (`cmdb_ci_cloud_object_storage`) | Reference | Key Value 3 (`cmdb_key_value`) | | Kubernetes Cluster 1 (`cmdb_ci_kubernetes_cluster`) | Hosted On::Hosts | AWS Datacenter 1 (`cmdb_ci_aws_datacenter`) | | Kubernetes Cluster 1 (`cmdb_ci_kubernetes_cluster`) | Reference | Key Value 4 (`cmdb_key_value`) | | Cloud Network 1 (`cmdb_ci_network`) | Hosted On::Hosts | AWS Datacenter 1 (`cmdb_ci_aws_datacenter`) | | Cloud Network 1 (`cmdb_ci_network`) | Reference | Key Value 5 (`cmdb_key_value`) | | Cloud DataBase 1 (`cmdb_ci_cloud_database` ) | Hosted On::Hosts | AWS Datacenter 1 (`cmdb_ci_aws_datacenter`) | | Cloud DataBase 1 (`cmdb_ci_cloud_database` ) | Reference | Key Value 6 (`cmdb_key_value`) | | Cloud DataBase Cluster 1 (`cmdb_ci_cloud_db_cluster`) | Hosted On::Hosts | AWS Datacenter 1 (`cmdb_ci_aws_datacenter`) | | Cloud DataBase Cluster 1 (`cmdb_ci_cloud_db_cluster`) | Reference | Key Value 7 (`cmdb_key_value`) | | DynamoDB Global Table 1 (`cmdb_ci_dynamodb_global_table`) | Hosted On::Hosts | Cloud Service Account 1 (`cmdb_ci_cloud_service_account`) | | DynamoDB Table 1 (`cmdb_ci_dynamodb_table`) | Hosted On::Hosts | AWS Datacenter 1 (`cmdb_ci_aws_datacenter`) | | DynamoDB Table 1 (`cmdb_ci_dynamodb_table`) | Reference | Key Value 8 (`cmdb_key_value`) | | Compute Security Group 1 (`cmdb_ci_compute_security_group`)| Hosted On::Hosts | AWS Datacenter 1 (`cmdb_ci_aws_datacenter`) | | Compute Security Group 1 (`cmdb_ci_compute_security_group`)| Reference | Key Value 10 (`cmdb_key_value`) | | Cloud Function 1 (`cmdb_ci_cloud_function`) | Hosted On::Hosts | AWS Datacenter 1 (`cmdb_ci_aws_datacenter`) | | Cloud Function 1 (`cmdb_ci_cloud_function`) | Reference | Key Value 11 (`cmdb_key_value`) | | Cloud Load Balancer 1 (`cmdb_ci_cloud_load_balancer`) | Hosted On::Hosts | AWS Datacenter 1 (`cmdb_ci_aws_datacenter`) | | Cloud Load Balancer 1 (`cmdb_ci_cloud_load_balancer`) | Reference | Key Value 12 (`cmdb_key_value`) | ## Field attributes mapping ### Cloud Service Account (`cmdb_ci_cloud_service_account`) | CMDB field | Terraform state field | |--------------------|-----------------------------------------------| | Source Native Key | Resource account number extracted from `arn` | | Account Id | Resource account number extracted from `arn` | | Datacenter Type | Resource cloud provider extracted from `arn` | | Object ID | Resource id extracted from `arn` | | Name | Resource name extracted from `arn` | | Operational Status | Defaults to "1" ("Operational") | ### AWS Datacenter (`cmdb_ci_aws_datacenter`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | Concatenation of region and account number extracted from `arn`| | Object Id | Region extracted from `arn` | | Region | Region extracted from `arn` | | Name | Region extracted from `arn` | | Operational Status| Defaults to "1" ("Operational") | ### Virtual Machine Instance (`cmdb_ci_vm_instance`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `arn` | | Object Id | `id` | | Placement Group ID| `placement_group` | | IP Address | `public_ip` | | Status | `instance_state` | | VM Instance ID | `id` | | Name | `id` | | State | `state` | | CPU | `cpu_core_count` | | Operational Status| Defaults to "1" ("Operational") | ### AWS Cloud ECS Cluster (`cmdb_ci_cloud_ecs_cluster`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `arn` | | Object Id | `id` | | Name | `name` | | Operational Status| Defaults to "1" ("Operational") | ### Cloud Object Storage (`cmdb_ci_cloud_object_storage`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `arn` | | Object Id | `id` | | Cloud Provider | Resource cloud provider extracted from `arn` | | Name | `bucket` | | Operational Status| Defaults to "1" ("Operational") | ### Kubernetes Cluster (`cmdb_ci_kubernetes_cluster`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `arn` | | IP Address | `endpoint` | | Port | Defaults to "6443" | | Name | `name` | | Operational Status| Defaults to "1" ("Operational") | ### Cloud Network (`cmdb_ci_network`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `arn` | | Object Id | `id` | | Name | `name` | | Operational Status| Defaults to "1" ("Operational") | ### Cloud DataBase (`cmdb_ci_cloud_database`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `arn` | | Object Id | `id` | | Version | `engine_version` | | Type | `engine` | | TCP port(s) | `port` | | Category | `instance_class` | | Fully qualified domain name| `endpoint` | | Location | Region extracted from `arn` | | Name | `name` | | Vendor | Resource cloud provider extracted from `arn` | | Operational Status| Defaults to "1" ("Operational") | ### Cloud DataBase Cluster (`cmdb_ci_cloud_db_cluster`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `arn` | | Cluster ID | `cluster_resource_id` | | Name | `name` | | TCP port(s) | `port` | | Fully qualified domain name| `endpoint` | | Vendor | Resource cloud provider extracted from `arn` | | Operational Status| Defaults to "1" ("Operational") | ### DynamoDB Table (`cmdb_ci_dynamodb_table`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `arn` | | Object Id | `arn` | | Location | Region extracted from `arn` | | Name | `name` | | Operational Status| Defaults to "1" ("Operational") | ### DynamoDB Global Table (`cmdb_ci_dynamodb_global_table`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `arn` | | Object Id | `arn` | | Name | `name` | | Operational Status| Defaults to "1" ("Operational") | ### Compute Security Group (`cmdb_ci_compute_security_group`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `arn` | | Object Id | `id` | | Location | Region extracted from `arn` | | Name | `name` | | Operational Status| Defaults to "1" ("Operational") | ### Cloud Function (`cmdb_ci_cloud_function`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `arn` | | Object Id | `arn` | | Language | `runtime` | | Code Size | `source_code_size` | | Location | Region extracted from `arn` | | Name | `function_name` | | Operational Status| Defaults to "1" ("Operational") | ### Cloud Load Balancer (`cmdb_ci_cloud_load_balancer`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `arn` | | Object Id | `id` | | Canonical Hosted Zone Name| `dns_name` | | Canonical Hosted Zone ID| `zone_id` | | Location | Region extracted from `arn` | | Name | `name` | | Operational Status| Defaults to "1" ("Operational")
terraform
page title ServiceNow Service Graph Connector for Terraform Integration AWS Coverage description ServiceNow Service Graph integration allows to import selected resources from AWS into ServiceNow CMDB AWS This page details the mapping rules for importing AWS resources provisioned with Terraform into ServiceNow CMDB Mapping of Terraform resources to CMDB CI Classes AWS resource Terraform resource name ServiceNow CMDB CI Class ServiceNow CMDB Category Name AWS account N A cmdb ci cloud service account Cloud Service Account AWS region N A cmdb ci aws datacenter AWS Datacenter EC2 Instance aws instance cmdb ci vm instance Virtual Machine Instance S3 Bucket aws s3 bucket cmdb ci cloud object storage Cloud Object Storage ECS Cluster aws ecs cluster cmdb ci cloud ecs cluster AWS Cloud ECS Cluster EKS Cluster aws eks cluster cmdb ci kubernetes cluster Kubernetes Cluster VPC aws vpc cmdb ci network Cloud Network Database Instance non Aurora databases e g MySQL PostgreSQL SQL Server etc aws db instance cmdb ci cloud database Cloud DataBase RDS Aurora Cluster aws rds cluster cmdb ci cloud db cluster Cloud DataBase Cluster RDS Aurora Instance aws rds cluster instance cmdb ci cloud database Cloud DataBase DynamoDB Global Table aws dynamodb global table cmdb ci dynamodb global table DynamoDB Global Table DynamoDB Table aws dynamodb table cmdb ci dynamodb table DynamoDB Table Security Group aws security group cmdb ci compute security group Compute Security Group Lambda aws lambda function cmdb ci cloud function Cloud Function Load Balancer aws lb cmdb ci cloud load balancer Cloud Load Balancer Tags N A cmdb key value Key Value Resource relationships Child CI Class Relationship type Parent CI Class AWS Datacenter 1 cmdb ci aws datacenter Hosted On Hosts Cloud Service Account 1 cmdb ci cloud service account AWS Datacenter 2 cmdb ci aws datacenter Hosted On Hosts Cloud Service Account 6 cmdb ci cloud service account Virtual Machine Instance 1 cmdb ci vm instance Hosted On Hosts AWS Datacenter 1 cmdb ci aws datacenter Virtual Machine Instance 1 cmdb ci vm instance Reference Key Value 1 cmdb key value AWS Cloud ECS Cluster 1 cmdb ci cloud ecs cluster Hosted On Hosts AWS Datacenter 1 cmdb ci aws datacenter AWS Cloud ECS Cluster 1 cmdb ci cloud ecs cluster Reference Key Value 2 cmdb key value Cloud Object Storage 1 cmdb ci cloud object storage Hosted On Hosts AWS Datacenter 2 cmdb ci aws datacenter Cloud Object Storage 1 cmdb ci cloud object storage Reference Key Value 3 cmdb key value Kubernetes Cluster 1 cmdb ci kubernetes cluster Hosted On Hosts AWS Datacenter 1 cmdb ci aws datacenter Kubernetes Cluster 1 cmdb ci kubernetes cluster Reference Key Value 4 cmdb key value Cloud Network 1 cmdb ci network Hosted On Hosts AWS Datacenter 1 cmdb ci aws datacenter Cloud Network 1 cmdb ci network Reference Key Value 5 cmdb key value Cloud DataBase 1 cmdb ci cloud database Hosted On Hosts AWS Datacenter 1 cmdb ci aws datacenter Cloud DataBase 1 cmdb ci cloud database Reference Key Value 6 cmdb key value Cloud DataBase Cluster 1 cmdb ci cloud db cluster Hosted On Hosts AWS Datacenter 1 cmdb ci aws datacenter Cloud DataBase Cluster 1 cmdb ci cloud db cluster Reference Key Value 7 cmdb key value DynamoDB Global Table 1 cmdb ci dynamodb global table Hosted On Hosts Cloud Service Account 1 cmdb ci cloud service account DynamoDB Table 1 cmdb ci dynamodb table Hosted On Hosts AWS Datacenter 1 cmdb ci aws datacenter DynamoDB Table 1 cmdb ci dynamodb table Reference Key Value 8 cmdb key value Compute Security Group 1 cmdb ci compute security group Hosted On Hosts AWS Datacenter 1 cmdb ci aws datacenter Compute Security Group 1 cmdb ci compute security group Reference Key Value 10 cmdb key value Cloud Function 1 cmdb ci cloud function Hosted On Hosts AWS Datacenter 1 cmdb ci aws datacenter Cloud Function 1 cmdb ci cloud function Reference Key Value 11 cmdb key value Cloud Load Balancer 1 cmdb ci cloud load balancer Hosted On Hosts AWS Datacenter 1 cmdb ci aws datacenter Cloud Load Balancer 1 cmdb ci cloud load balancer Reference Key Value 12 cmdb key value Field attributes mapping Cloud Service Account cmdb ci cloud service account CMDB field Terraform state field Source Native Key Resource account number extracted from arn Account Id Resource account number extracted from arn Datacenter Type Resource cloud provider extracted from arn Object ID Resource id extracted from arn Name Resource name extracted from arn Operational Status Defaults to 1 Operational AWS Datacenter cmdb ci aws datacenter CMDB field Terraform state field Source Native Key Concatenation of region and account number extracted from arn Object Id Region extracted from arn Region Region extracted from arn Name Region extracted from arn Operational Status Defaults to 1 Operational Virtual Machine Instance cmdb ci vm instance CMDB field Terraform state field Source Native Key arn Object Id id Placement Group ID placement group IP Address public ip Status instance state VM Instance ID id Name id State state CPU cpu core count Operational Status Defaults to 1 Operational AWS Cloud ECS Cluster cmdb ci cloud ecs cluster CMDB field Terraform state field Source Native Key arn Object Id id Name name Operational Status Defaults to 1 Operational Cloud Object Storage cmdb ci cloud object storage CMDB field Terraform state field Source Native Key arn Object Id id Cloud Provider Resource cloud provider extracted from arn Name bucket Operational Status Defaults to 1 Operational Kubernetes Cluster cmdb ci kubernetes cluster CMDB field Terraform state field Source Native Key arn IP Address endpoint Port Defaults to 6443 Name name Operational Status Defaults to 1 Operational Cloud Network cmdb ci network CMDB field Terraform state field Source Native Key arn Object Id id Name name Operational Status Defaults to 1 Operational Cloud DataBase cmdb ci cloud database CMDB field Terraform state field Source Native Key arn Object Id id Version engine version Type engine TCP port s port Category instance class Fully qualified domain name endpoint Location Region extracted from arn Name name Vendor Resource cloud provider extracted from arn Operational Status Defaults to 1 Operational Cloud DataBase Cluster cmdb ci cloud db cluster CMDB field Terraform state field Source Native Key arn Cluster ID cluster resource id Name name TCP port s port Fully qualified domain name endpoint Vendor Resource cloud provider extracted from arn Operational Status Defaults to 1 Operational DynamoDB Table cmdb ci dynamodb table CMDB field Terraform state field Source Native Key arn Object Id arn Location Region extracted from arn Name name Operational Status Defaults to 1 Operational DynamoDB Global Table cmdb ci dynamodb global table CMDB field Terraform state field Source Native Key arn Object Id arn Name name Operational Status Defaults to 1 Operational Compute Security Group cmdb ci compute security group CMDB field Terraform state field Source Native Key arn Object Id id Location Region extracted from arn Name name Operational Status Defaults to 1 Operational Cloud Function cmdb ci cloud function CMDB field Terraform state field Source Native Key arn Object Id arn Language runtime Code Size source code size Location Region extracted from arn Name function name Operational Status Defaults to 1 Operational Cloud Load Balancer cmdb ci cloud load balancer CMDB field Terraform state field Source Native Key arn Object Id id Canonical Hosted Zone Name dns name Canonical Hosted Zone ID zone id Location Region extracted from arn Name name Operational Status Defaults to 1 Operational
terraform This page describes how Terraform provisioned Azure resources are mapped to the classes within the ServiceNow CMDB Microsoft Azure ServiceNow Service Graph integration allows to import selected resources from Azure into ServiceNow CMDB page title ServiceNow Service Graph Connector for Terraform Integration Azure Coverage
--- page_title: ServiceNow Service Graph Connector for Terraform Integration - Azure Coverage description: >- ServiceNow Service Graph integration allows to import selected resources from Azure into ServiceNow CMDB. --- # Microsoft Azure This page describes how Terraform-provisioned Azure resources are mapped to the classes within the ServiceNow CMDB. ## Mapping of Terraform resources to CMDB CI Classes | Azure resource | Terraform resource name | ServiceNow CMDB CI Class | ServiceNow CMDB Category Name | |----------------------------|------------------------------------|---------------------------------|-------------------------------| | Azure account | N/A | `cmdb_ci_cloud_service_account` | Cloud Service Account | | Azure region | N/A | `cmdb_ci_azure_datacenter` | Azure Datacenter | | Resource Group | `azurerm_resource_group` | `cmdb_ci_resource_group` | Resource Group | | Windows VM | `azurerm_windows_virtual_machine` | `cmdb_ci_vm_instance` | Virtual Machine Instance | | Linux VM | `azurerm_linux_virtual_machine` | `cmdb_ci_vm_instance` | Virtual Machine Instance | | AKS Cluster | `azurerm_kubernetes_cluster` | `cmdb_ci_kubernetes_cluster` | Kubernetes Cluster | | Storage Container | `azurerm_storage_container` | `cmdb_ci_cloud_storage_account` | Cloud Storage Account | | MariaDB Database | `azurerm_mariadb_server` | `cmdb_ci_cloud_database` | Cloud DataBase | | MS SQL Database | `azurerm_mssql_server` | `cmdb_ci_cloud_database` | Cloud DataBase | | MySQL Database | `azurerm_mysql_server` | `cmdb_ci_cloud_database` | Cloud DataBase | | PostgreSQL Database | `azurerm_postgresql_server` | `cmdb_ci_cloud_database` | Cloud DataBase | | Network security group | `azurerm_network_security_group` | `cmdb_ci_compute_security_group`| Compute Security Group | | Linux Function App | `azurerm_linux_function_app` | `cmdb_ci_cloud_function` | Cloud Function | | Windows Function App | `azurerm_windows_function_app` | `cmdb_ci_cloud_function` | Cloud Function | | Virtual Network | `azurerm_virtual_network` | `cmdb_ci_network` | Cloud Network | | Tags | N/A | `cmdb_key_value` | Key Value | ## Resource relationships | Child CI Class | Relationship type | Parent CI Class | |------------------------------------------------------------|------------------------|-----------------------------------------------------------| | Azure Datacenter 1 (`cmdb_ci_azure_datacenter`) | Hosted On::Hosts | Cloud Service Account 2 (`cmdb_ci_cloud_service_account`) | | Azure Datacenter 2 (`cmdb_ci_azure_datacenter`) | Hosted On::Hosts | Cloud Service Account 3 (`cmdb_ci_cloud_service_account`) | | Azure Datacenter 1 (`cmdb_ci_azure_datacenter`) | Contains::Contained by | Resource Group 1 (`cmdb_ci_resource_group`) | | Cloud Storage Account 1 (`cmdb_ci_cloud_storage_account`) | Hosted On::Hosts | Azure Datacenter 2 (`cmdb_ci_azure_datacenter`) | | Virtual Machine Instance 2 (`cmdb_ci_vm_instance`) | Hosted On::Hosts | Azure Datacenter 1 (`cmdb_ci_azure_datacenter`) | | Virtual Machine Instance 2 (`cmdb_ci_vm_instance`) | Reference | Key Value 14 (`cmdb_key_value`) | | Virtual Machine Instance 3 (`cmdb_ci_vm_instance`) | Hosted On::Hosts | Azure Datacenter 1 (`cmdb_ci_azure_datacenter`) | | Virtual Machine Instance 3 (`cmdb_ci_vm_instance`) | Reference | Key Value 15 (`cmdb_key_value`) | | Kubernetes Cluster 2 (`cmdb_ci_kubernetes_cluster`) | Hosted On::Hosts | Azure Datacenter 1 (`cmdb_ci_azure_datacenter`) | | Kubernetes Cluster 2 (`cmdb_ci_kubernetes_cluster`) | Reference | Key Value 16 (`cmdb_key_value`) | | Cloud DataBase 2 (`cmdb_ci_cloud_database` ) | Hosted On::Hosts | Azure Datacenter 1 (`cmdb_ci_azure_datacenter`) | | Cloud DataBase 2 (`cmdb_ci_cloud_database` ) | Reference | Key Value 9 (`cmdb_key_value`) | | Compute Security Group 2 (`cmdb_ci_compute_security_group`)| Hosted On::Hosts | Azure Datacenter 1 (`cmdb_ci_azure_datacenter`) | | Compute Security Group 2 (`cmdb_ci_compute_security_group`)| Reference | Key Value 17 (`cmdb_key_value`) | | Cloud Function 2 (`cmdb_ci_cloud_function`) | Hosted On::Hosts | Azure Datacenter 1 (`cmdb_ci_azure_datacenter`) | | Cloud Function 2 (`cmdb_ci_cloud_function`) | Reference | Key Value 19 (`cmdb_key_value`) | | Cloud Network 2 (`cmdb_ci_network`) | Hosted On::Hosts | Azure Datacenter 1 (`cmdb_ci_azure_datacenter`) | | Cloud Network 2 (`cmdb_ci_network`) | Reference | Key Value 20 (`cmdb_key_value`) | ## Field attributes mapping ### Cloud Service Account (`cmdb_ci_cloud_service_account`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | Subscription ID extracted from `id` | | Account Id | Subscription ID extracted from `id` | | Datacenter Type | Defaults to `azure` | | Object ID | Subscription ID extracted from `id` | | Name | Subscription ID extracted from `id` | | Operational Status| Defaults to "1" ("Operational") | ### Azure Datacenter (`cmdb_ci_azure_datacenter`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | Concatenation of `location` and Subscription ID | | Object Id | `location` | | Region | `location` | | Name | `location` | | Operational Status| Defaults to "1" ("Operational") | ### Virtual Machine Instance (`cmdb_ci_vm_instance`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `id` | | Object Id | `id` | | Name | `name` | | Operational Status| Defaults to "1" ("Operational") | ### Cloud Storage Account (`cmdb_ci_cloud_storage_account`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `resource_manager_id` | | Object Id | `resource_manager_id` | | Fully qualified domain name| `id` | | Blob Service | `storage_account_name` | | Name | `name` | | Operational Status| Defaults to "1" ("Operational") | ### Resource Group (`cmdb_ci_resource_group`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `id` | | Object Id | `id` | | Name | `name` | | Location | `location` | | Operational Status| Defaults to "1" ("Operational") | ### Kubernetes Cluster (`cmdb_ci_kubernetes_cluster`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `id` | | IP Address | `fqdn` | | Port | Defaults to "6443" | | Name | `name` | | Location | `location` | | Operational Status| Defaults to "1" ("Operational") | ### Cloud DataBase (`cmdb_ci_cloud_database`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `id` | | Object Id | `id` | | Version | `engine_version` | | Fully qualified domain name| `fqdn` | | Name | `name` | | Vendor | Defaults to `azure` | | Operational Status| Defaults to "1" ("Operational") | ### Compute Security Group (`cmdb_ci_compute_security_group`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `id` | | Object Id | `id` | | Name | `name` | | Operational Status| Defaults to "1" ("Operational") | ### Cloud Function (`cmdb_ci_cloud_function`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `id` | | Object Id | `id` | | Name | `name` | | Operational Status| Defaults to "1" ("Operational") | ### Cloud Network (`cmdb_ci_network`) | CMDB field | Terraform state field | |-------------------|----------------------------------------------------------------| | Source Native Key | `id` | | Object Id | `id` | | Name | `name` | | Operational Status| Defaults to "1" ("Operational")
terraform
page title ServiceNow Service Graph Connector for Terraform Integration Azure Coverage description ServiceNow Service Graph integration allows to import selected resources from Azure into ServiceNow CMDB Microsoft Azure This page describes how Terraform provisioned Azure resources are mapped to the classes within the ServiceNow CMDB Mapping of Terraform resources to CMDB CI Classes Azure resource Terraform resource name ServiceNow CMDB CI Class ServiceNow CMDB Category Name Azure account N A cmdb ci cloud service account Cloud Service Account Azure region N A cmdb ci azure datacenter Azure Datacenter Resource Group azurerm resource group cmdb ci resource group Resource Group Windows VM azurerm windows virtual machine cmdb ci vm instance Virtual Machine Instance Linux VM azurerm linux virtual machine cmdb ci vm instance Virtual Machine Instance AKS Cluster azurerm kubernetes cluster cmdb ci kubernetes cluster Kubernetes Cluster Storage Container azurerm storage container cmdb ci cloud storage account Cloud Storage Account MariaDB Database azurerm mariadb server cmdb ci cloud database Cloud DataBase MS SQL Database azurerm mssql server cmdb ci cloud database Cloud DataBase MySQL Database azurerm mysql server cmdb ci cloud database Cloud DataBase PostgreSQL Database azurerm postgresql server cmdb ci cloud database Cloud DataBase Network security group azurerm network security group cmdb ci compute security group Compute Security Group Linux Function App azurerm linux function app cmdb ci cloud function Cloud Function Windows Function App azurerm windows function app cmdb ci cloud function Cloud Function Virtual Network azurerm virtual network cmdb ci network Cloud Network Tags N A cmdb key value Key Value Resource relationships Child CI Class Relationship type Parent CI Class Azure Datacenter 1 cmdb ci azure datacenter Hosted On Hosts Cloud Service Account 2 cmdb ci cloud service account Azure Datacenter 2 cmdb ci azure datacenter Hosted On Hosts Cloud Service Account 3 cmdb ci cloud service account Azure Datacenter 1 cmdb ci azure datacenter Contains Contained by Resource Group 1 cmdb ci resource group Cloud Storage Account 1 cmdb ci cloud storage account Hosted On Hosts Azure Datacenter 2 cmdb ci azure datacenter Virtual Machine Instance 2 cmdb ci vm instance Hosted On Hosts Azure Datacenter 1 cmdb ci azure datacenter Virtual Machine Instance 2 cmdb ci vm instance Reference Key Value 14 cmdb key value Virtual Machine Instance 3 cmdb ci vm instance Hosted On Hosts Azure Datacenter 1 cmdb ci azure datacenter Virtual Machine Instance 3 cmdb ci vm instance Reference Key Value 15 cmdb key value Kubernetes Cluster 2 cmdb ci kubernetes cluster Hosted On Hosts Azure Datacenter 1 cmdb ci azure datacenter Kubernetes Cluster 2 cmdb ci kubernetes cluster Reference Key Value 16 cmdb key value Cloud DataBase 2 cmdb ci cloud database Hosted On Hosts Azure Datacenter 1 cmdb ci azure datacenter Cloud DataBase 2 cmdb ci cloud database Reference Key Value 9 cmdb key value Compute Security Group 2 cmdb ci compute security group Hosted On Hosts Azure Datacenter 1 cmdb ci azure datacenter Compute Security Group 2 cmdb ci compute security group Reference Key Value 17 cmdb key value Cloud Function 2 cmdb ci cloud function Hosted On Hosts Azure Datacenter 1 cmdb ci azure datacenter Cloud Function 2 cmdb ci cloud function Reference Key Value 19 cmdb key value Cloud Network 2 cmdb ci network Hosted On Hosts Azure Datacenter 1 cmdb ci azure datacenter Cloud Network 2 cmdb ci network Reference Key Value 20 cmdb key value Field attributes mapping Cloud Service Account cmdb ci cloud service account CMDB field Terraform state field Source Native Key Subscription ID extracted from id Account Id Subscription ID extracted from id Datacenter Type Defaults to azure Object ID Subscription ID extracted from id Name Subscription ID extracted from id Operational Status Defaults to 1 Operational Azure Datacenter cmdb ci azure datacenter CMDB field Terraform state field Source Native Key Concatenation of location and Subscription ID Object Id location Region location Name location Operational Status Defaults to 1 Operational Virtual Machine Instance cmdb ci vm instance CMDB field Terraform state field Source Native Key id Object Id id Name name Operational Status Defaults to 1 Operational Cloud Storage Account cmdb ci cloud storage account CMDB field Terraform state field Source Native Key resource manager id Object Id resource manager id Fully qualified domain name id Blob Service storage account name Name name Operational Status Defaults to 1 Operational Resource Group cmdb ci resource group CMDB field Terraform state field Source Native Key id Object Id id Name name Location location Operational Status Defaults to 1 Operational Kubernetes Cluster cmdb ci kubernetes cluster CMDB field Terraform state field Source Native Key id IP Address fqdn Port Defaults to 6443 Name name Location location Operational Status Defaults to 1 Operational Cloud DataBase cmdb ci cloud database CMDB field Terraform state field Source Native Key id Object Id id Version engine version Fully qualified domain name fqdn Name name Vendor Defaults to azure Operational Status Defaults to 1 Operational Compute Security Group cmdb ci compute security group CMDB field Terraform state field Source Native Key id Object Id id Name name Operational Status Defaults to 1 Operational Cloud Function cmdb ci cloud function CMDB field Terraform state field Source Native Key id Object Id id Name name Operational Status Defaults to 1 Operational Cloud Network cmdb ci network CMDB field Terraform state field Source Native Key id Object Id id Name name Operational Status Defaults to 1 Operational
terraform Example customizations for the ServiceNow Service Catalog Integration This example use case creates a Terraform Catalog Item for requesting resources Cloud Example Customizations ServiceNow Service Catalog Integration Terraform page title Example Customizations
--- page_title: >- Example Customizations - ServiceNow Service Catalog Integration - Terraform Cloud description: Example customizations for the ServiceNow Service Catalog Integration. --- # Example Customizations This example use case creates a Terraform Catalog Item for requesting resources with custom variable values passed to the Terraform configuration. ## Change the scope When you make a customization to the app, ensure you switch to the "Terraform" scope. This guarantees that all items you create are correctly assigned to that scope. To change the scope in your ServiceNow instance, click the globe icon at the top right of the screen. For detailed instructions on changing the scope, refer to the [ServiceNow documentation](https://developer.servicenow.com/dev.do#!/learn/learning-plans/xanadu/new_to_servicenow/app_store_learnv2_buildneedit_xanadu_application_scope). ## Make a copy of the existing Catalog Item The ServiceNow Service Catalog for Terraform application provides pre-configured [Catalog Items](/terraform/cloud-docs/integrations/service-now/service-catalog-terraform/developer-reference#example-service-catalog-flows-and-actions) for immediate use. We recommend creating a copy of the most recent version of the Catalog Item to ensure you have access to the latest features and improvements. Make a copy of the most appropriate Catalog Item for your specific business requirements by following these steps: 1. Navigate to **All > Service Catalog > Catalogs > Terraform Catalog**, and review the Catalog Items based on flows, whose names use the suffix "Flow". We recommend choosing Flows over Workflows because Flows provide enhanced functionality and performance and are actively developed by ServiceNow. For more information, refer to [Catalog Items based on Flows vs. Workflows](/terraform/cloud-docs/integrations/service-now/service-catalog-terraform/developer-reference#example-service-catalog-flows-and-actions). 1. Open the Catalog Item in editing mode: 1. Click the Catalog Item to open the request form. 1. Click **...** in the top right corner. 1. Select **Configure Item** from the menu. ![Screenshot: ServiceNow Configure Catalog Item](/img/docs/servicenow-catalog-configure-item.png "Screenshot of the ServiceNow Configure Catalog Item dropdown menu") 1. Click the **Process Engine** tab in the Catalog Item configuration. Take note of the Flow name associated with the Catalog Item, because you need to create a copy of this Flow as well. ![Screenshot: ServiceNow Process Engine](/img/docs/servicenow-catalog-process-engine.png "Screenshot of the ServiceNow Configure Catalog Item – Process Engine tab") 1. Start the copying process: 1. Click the **Copy** button above the **Related Links** section. 1. Assign a new name to the copied Catalog Item. 1. Optionally, modify the description and short description fields. Right-click the header and select **Save**. ![Screenshot: ServiceNow Copy Item](/img/docs/servicenow-catalog-copied-item.png "Screenshot of the copied ServiceNow Catalog Item") ## Adjust the Variable Set If a Catalog Item requires users to input variable values, you must update the variable set with those required variables. Although some default Catalog Items come with pre-defined example variables, it is common practice to remove these and replace them with your own custom variables. 1. Create a new Variable Set. 1. On the Catalog Item's configuration page, under the **Related Links** section, click the **Variable Sets** tab. 1. Click the **New** button to create a new variable set. Ensure that the variables in your new set match the variables required by your Terraform configuration. ![Screenshot: ServiceNow New Variable Set](/img/docs/servicenow-catalog-new-varset.png "Screenshot of the ServiceNow Catalog Item – new Variable Set") 1. Select **Single-Row Variable Set** and provide a title and description. 1. Click **Submit**. Upon submission, you will be redirected back to the Catalog Item's configuration page. ![Screenshot: ServiceNow New Variable Set Form](/img/docs/servicenow-catalog-new-varset-form.png "Screenshot of the ServiceNow Catalog Item – new Variable Set") 1. Click the name of your newly created Variable Set and create your variables. You must follow the [naming convention for Terraform variables](/terraform/cloud-docs/integrations/service-now/service-catalog-terraform/developer-reference#terraform-variables-and-servicenow-variable-sets). ServiceNow offers various types of variable representation (such as strings, booleans, and dropdown menus). Refer to the [ServiceNow documentation on variables](https://docs.servicenow.com/csh?topicname=c_ServiceCatalogVariables.html&version=latest) and select the types that best suit your use case. You can also set default values for the variables in the **Default Value** tab, which ServiceNow prefills for the end users. ![Screenshot: ServiceNow New Variables](/img/docs/servicenow-catalog-variables.png "Screenshot of the ServiceNow Catalog Item – new variables") 1. Attach the newly created Variable Set to your custom Catalog Item and remove the default Workspace Variables. 1. Return to the **Variable Sets** tab on the Catalog Item's configuration page and click the **Edit** button. 1. Move the "Workspace Variables" Set from the right side to the left side and click **Save**. Do not remove the "Workspace Request Create" or the "Workspace Request Update" Sets. ![Screenshot: ServiceNow Remove Example Variables](/img/docs/servicenow-catalog-remove-example-variables.png "Screenshot of the ServiceNow Catalog Item – new variables") ## Make a copy of the Flow and Action 1. Open the ServiceNow Studio by navigating to **All > Studio** and open the "Terraform" application. Once in the **Terraform** application, navigate to **Flow Designer > Flows**. ![Screenshot: ServiceNow Flow Designer Interface](/img/docs/servicenow-catalog-original-flow.png "Screenshot of the ServiceNow Flow Designer – selecting a Flow") Another way to access the ServiceNow Studio is to click **All**, select "Flow Designer", then select **Flows**. You can set the **Application** filter to "Terraform" to quickly find the desired Flow. 1. Open the Flow referenced in your Catalog Item. Click **...** in the top right corner of the Flow Designer interface and select **Copy flow**. Provide a name for the copied Flow and click **Copy**. ![Screenshot: ServiceNow Copy Flow Interface](/img/docs/servicenow-catalog-copy-flow.png "Screenshot of the ServiceNow Flow Designer – copying a Flow") 1. Customize your newly copied Flow by clicking **Edit flow**. ![Screenshot: ServiceNow Edit New Flow Interface](/img/docs/servicenow-catalog-edit-flow.png "Screenshot of the ServiceNow Flow Designer – editing a Flow") 1. Do not change the **Service Catalog** trigger. 1. Update the "Get Catalog Variables" action: 1. Keep the "Requested Item Record" in the **Submitted Request** field. 1. Select your newly created Catalog Item from the dropdown menu for **Template Catalog Item**. 1. Move all of your variables to the **Selected** side in the **Catalog Variables** section. Remove any previous example variables from the **Available** side. ![Screenshot: ServiceNow Get Variables Flow Step](/img/docs/servicenow-catalog-get-variables.png "Screenshot of the ServiceNow Flow Designer – getting Variables step") 1. Click **Done** to finish configuring this Action. 1. Unfold the second Action in the Flow and click the arrow to open it in the Action Designer. ![Screenshot: ServiceNow Open Action Designer](/img/docs/servicenow-catalog-open-action.png "Screenshot of the ServiceNow Action Designer") 1. Click **...** in the top right corner and select **Copy Action**. ![Screenshot: ServiceNow Copy Action](/img/docs/servicenow-catalog-copy-action.png "Screenshot of the ServiceNow Copy Action") Rename it and click **Copy**. ![Screenshot: ServiceNow Rename Action](/img/docs/servicenow-catalog-rename-action.png "Screenshot of the ServiceNow Rename Action") 1. In the the Inputs section, remove any previous example variables. ![Screenshot: ServiceNow Remove Variables From Action](/img/docs/servicenow-catalog-remove-example-variables-from-action.png "Screenshot of the ServiceNow Action Input Variables") 1. Add your custom variables by clicking the **Create Input** button. Ensure that the variable names match your Catalog Item variables and select the variable type that matches each variable. Click **Save**. ![Screenshot: ServiceNow Add Variables To Action](/img/docs/servicenow-catalog-add-variables-to-action.png "Screenshot of adding ServiceNow Action Input Variables") 1. Open the **Script step** within the Action. Remove any example variables and add your custom variables by clicking **Create Variable** at the bottom. Enter the name of each variable and drag the corresponding data pill from the right into the **Value field**. ![Screenshot: ServiceNow Add Script Step Variables To Action](/img/docs/servicenow-catalog-adjust-script-variables.png "Screenshot of adjusting ServiceNow Action Script Variables") 1. Click **Save** and then **Publish**. 1. Reopen the Flow and attach the newly created Action to the Flow after "Get Catalog Variables" step: 1. Remove the "Create Terraform Workspace with Vars" Action that you copied earlier and replace it with your newly created Action. ![Screenshot: ServiceNow Replace Action Step](/img/docs/servicenow-catalog-replace-action.png "Screenshot of replacing ServiceNow Action step") 1. Connect the new Action to the Flow by dragging and dropping the data pills from the "Get Catalog Variables" Action to the corresponding inputs of your new Action. Click **Done** to save this step. ![Screenshot: ServiceNow Fill Variables for Action](/img/docs/servicenow-catalog-fill-new-action-step.png "Screenshot of filling out ServiceNow Action variables") 1. Click **Save**. 1. Click **Activate** to enable the Flow and make it available for use. ## Set the Flow for your Catalog Item 1. Navigate back to the Catalog by clicking on **All** and then go to **Service Catalog > Catalogs > Terraform Catalog**. 1. Locate your custom Catalog Item and click **...** at the top of the item. From the dropdown menu, select **Configure item**. 1. In the configuration settings, click the **Process Engine** tab. 1. In the **Flow** field, search for the Flow you recently created. Click the Flow then click the **Update**. ![Screenshot: ServiceNow Update Process Engine](/img/docs/servicenow-catalog-update-process-engine.png "Screenshot of updating Process Engine for the Catalog Item") ## Test the Catalog Item The new item is now available in the Terraform Service Catalog. To make the new item accessible to your end users via the Service Portal, follow these steps: 1. Navigate to the configuration page of the item you want to make available. 1. Locate the **Catalogs** field on the configuration page and click the lock icon next to it. 1. In the search bar, type "Service Catalog" and select it from the search results. Add "Service Catalog" to the list of catalogs associated with the item. Click the lock icon again to lock the changes. ![Screenshot: ServiceNow Enable Service Portal](/img/docs/servicenow-catalog-service-portal.png "Screenshot of adding the Catalog Item to the Service Portal") 1. Click the **Update** button at the top of the page. After completing these steps, end users will be able to access the new item through the Service Portal of your ServiceNow instance. You can access the Service Portal by navigating to **All > Service Portal Home**
terraform
page title Example Customizations ServiceNow Service Catalog Integration Terraform Cloud description Example customizations for the ServiceNow Service Catalog Integration Example Customizations This example use case creates a Terraform Catalog Item for requesting resources with custom variable values passed to the Terraform configuration Change the scope When you make a customization to the app ensure you switch to the Terraform scope This guarantees that all items you create are correctly assigned to that scope To change the scope in your ServiceNow instance click the globe icon at the top right of the screen For detailed instructions on changing the scope refer to the ServiceNow documentation https developer servicenow com dev do learn learning plans xanadu new to servicenow app store learnv2 buildneedit xanadu application scope Make a copy of the existing Catalog Item The ServiceNow Service Catalog for Terraform application provides pre configured Catalog Items terraform cloud docs integrations service now service catalog terraform developer reference example service catalog flows and actions for immediate use We recommend creating a copy of the most recent version of the Catalog Item to ensure you have access to the latest features and improvements Make a copy of the most appropriate Catalog Item for your specific business requirements by following these steps 1 Navigate to All Service Catalog Catalogs Terraform Catalog and review the Catalog Items based on flows whose names use the suffix Flow We recommend choosing Flows over Workflows because Flows provide enhanced functionality and performance and are actively developed by ServiceNow For more information refer to Catalog Items based on Flows vs Workflows terraform cloud docs integrations service now service catalog terraform developer reference example service catalog flows and actions 1 Open the Catalog Item in editing mode 1 Click the Catalog Item to open the request form 1 Click in the top right corner 1 Select Configure Item from the menu Screenshot ServiceNow Configure Catalog Item img docs servicenow catalog configure item png Screenshot of the ServiceNow Configure Catalog Item dropdown menu 1 Click the Process Engine tab in the Catalog Item configuration Take note of the Flow name associated with the Catalog Item because you need to create a copy of this Flow as well Screenshot ServiceNow Process Engine img docs servicenow catalog process engine png Screenshot of the ServiceNow Configure Catalog Item Process Engine tab 1 Start the copying process 1 Click the Copy button above the Related Links section 1 Assign a new name to the copied Catalog Item 1 Optionally modify the description and short description fields Right click the header and select Save Screenshot ServiceNow Copy Item img docs servicenow catalog copied item png Screenshot of the copied ServiceNow Catalog Item Adjust the Variable Set If a Catalog Item requires users to input variable values you must update the variable set with those required variables Although some default Catalog Items come with pre defined example variables it is common practice to remove these and replace them with your own custom variables 1 Create a new Variable Set 1 On the Catalog Item s configuration page under the Related Links section click the Variable Sets tab 1 Click the New button to create a new variable set Ensure that the variables in your new set match the variables required by your Terraform configuration Screenshot ServiceNow New Variable Set img docs servicenow catalog new varset png Screenshot of the ServiceNow Catalog Item new Variable Set 1 Select Single Row Variable Set and provide a title and description 1 Click Submit Upon submission you will be redirected back to the Catalog Item s configuration page Screenshot ServiceNow New Variable Set Form img docs servicenow catalog new varset form png Screenshot of the ServiceNow Catalog Item new Variable Set 1 Click the name of your newly created Variable Set and create your variables You must follow the naming convention for Terraform variables terraform cloud docs integrations service now service catalog terraform developer reference terraform variables and servicenow variable sets ServiceNow offers various types of variable representation such as strings booleans and dropdown menus Refer to the ServiceNow documentation on variables https docs servicenow com csh topicname c ServiceCatalogVariables html version latest and select the types that best suit your use case You can also set default values for the variables in the Default Value tab which ServiceNow prefills for the end users Screenshot ServiceNow New Variables img docs servicenow catalog variables png Screenshot of the ServiceNow Catalog Item new variables 1 Attach the newly created Variable Set to your custom Catalog Item and remove the default Workspace Variables 1 Return to the Variable Sets tab on the Catalog Item s configuration page and click the Edit button 1 Move the Workspace Variables Set from the right side to the left side and click Save Do not remove the Workspace Request Create or the Workspace Request Update Sets Screenshot ServiceNow Remove Example Variables img docs servicenow catalog remove example variables png Screenshot of the ServiceNow Catalog Item new variables Make a copy of the Flow and Action 1 Open the ServiceNow Studio by navigating to All Studio and open the Terraform application Once in the Terraform application navigate to Flow Designer Flows Screenshot ServiceNow Flow Designer Interface img docs servicenow catalog original flow png Screenshot of the ServiceNow Flow Designer selecting a Flow Another way to access the ServiceNow Studio is to click All select Flow Designer then select Flows You can set the Application filter to Terraform to quickly find the desired Flow 1 Open the Flow referenced in your Catalog Item Click in the top right corner of the Flow Designer interface and select Copy flow Provide a name for the copied Flow and click Copy Screenshot ServiceNow Copy Flow Interface img docs servicenow catalog copy flow png Screenshot of the ServiceNow Flow Designer copying a Flow 1 Customize your newly copied Flow by clicking Edit flow Screenshot ServiceNow Edit New Flow Interface img docs servicenow catalog edit flow png Screenshot of the ServiceNow Flow Designer editing a Flow 1 Do not change the Service Catalog trigger 1 Update the Get Catalog Variables action 1 Keep the Requested Item Record in the Submitted Request field 1 Select your newly created Catalog Item from the dropdown menu for Template Catalog Item 1 Move all of your variables to the Selected side in the Catalog Variables section Remove any previous example variables from the Available side Screenshot ServiceNow Get Variables Flow Step img docs servicenow catalog get variables png Screenshot of the ServiceNow Flow Designer getting Variables step 1 Click Done to finish configuring this Action 1 Unfold the second Action in the Flow and click the arrow to open it in the Action Designer Screenshot ServiceNow Open Action Designer img docs servicenow catalog open action png Screenshot of the ServiceNow Action Designer 1 Click in the top right corner and select Copy Action Screenshot ServiceNow Copy Action img docs servicenow catalog copy action png Screenshot of the ServiceNow Copy Action Rename it and click Copy Screenshot ServiceNow Rename Action img docs servicenow catalog rename action png Screenshot of the ServiceNow Rename Action 1 In the the Inputs section remove any previous example variables Screenshot ServiceNow Remove Variables From Action img docs servicenow catalog remove example variables from action png Screenshot of the ServiceNow Action Input Variables 1 Add your custom variables by clicking the Create Input button Ensure that the variable names match your Catalog Item variables and select the variable type that matches each variable Click Save Screenshot ServiceNow Add Variables To Action img docs servicenow catalog add variables to action png Screenshot of adding ServiceNow Action Input Variables 1 Open the Script step within the Action Remove any example variables and add your custom variables by clicking Create Variable at the bottom Enter the name of each variable and drag the corresponding data pill from the right into the Value field Screenshot ServiceNow Add Script Step Variables To Action img docs servicenow catalog adjust script variables png Screenshot of adjusting ServiceNow Action Script Variables 1 Click Save and then Publish 1 Reopen the Flow and attach the newly created Action to the Flow after Get Catalog Variables step 1 Remove the Create Terraform Workspace with Vars Action that you copied earlier and replace it with your newly created Action Screenshot ServiceNow Replace Action Step img docs servicenow catalog replace action png Screenshot of replacing ServiceNow Action step 1 Connect the new Action to the Flow by dragging and dropping the data pills from the Get Catalog Variables Action to the corresponding inputs of your new Action Click Done to save this step Screenshot ServiceNow Fill Variables for Action img docs servicenow catalog fill new action step png Screenshot of filling out ServiceNow Action variables 1 Click Save 1 Click Activate to enable the Flow and make it available for use Set the Flow for your Catalog Item 1 Navigate back to the Catalog by clicking on All and then go to Service Catalog Catalogs Terraform Catalog 1 Locate your custom Catalog Item and click at the top of the item From the dropdown menu select Configure item 1 In the configuration settings click the Process Engine tab 1 In the Flow field search for the Flow you recently created Click the Flow then click the Update Screenshot ServiceNow Update Process Engine img docs servicenow catalog update process engine png Screenshot of updating Process Engine for the Catalog Item Test the Catalog Item The new item is now available in the Terraform Service Catalog To make the new item accessible to your end users via the Service Portal follow these steps 1 Navigate to the configuration page of the item you want to make available 1 Locate the Catalogs field on the configuration page and click the lock icon next to it 1 In the search bar type Service Catalog and select it from the search results Add Service Catalog to the list of catalogs associated with the item Click the lock icon again to lock the changes Screenshot ServiceNow Enable Service Portal img docs servicenow catalog service portal png Screenshot of adding the Catalog Item to the Service Portal 1 Click the Update button at the top of the page After completing these steps end users will be able to access the new item through the Service Portal of your ServiceNow instance You can access the Service Portal by navigating to All Service Portal Home
terraform infrastructure from ServiceNow page title Setup Instructions ServiceNow Service Catalog Integration HCP Terraform Terraform ServiceNow Service Catalog Integration Setup Instructions Integration version v2 7 0 ServiceNow integration enables your users to order Terraform built
--- page_title: Setup Instructions - ServiceNow Service Catalog Integration - HCP Terraform description: >- ServiceNow integration enables your users to order Terraform-built infrastructure from ServiceNow. --- # Terraform ServiceNow Service Catalog Integration Setup Instructions -> **Integration version:** v2.7.0 The Terraform ServiceNow Service Catalog integration enables your end-users to provision self-serve infrastructure via ServiceNow. By connecting ServiceNow to HCP Terraform, this integration lets ServiceNow users order Service Items, create workspaces, and perform Terraform runs using prepared Terraform configurations hosted in VCS repositories or as [no-code modules](/terraform/cloud-docs/no-code-provisioning/module-design) for self-service provisioning. <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/servicenow-catalog.mdx' <!-- END: TFC:only name:pnp-callout --> ## Summary of the Setup Process The integration relies on Terraform ServiceNow Catalog integration software installed within your ServiceNow instance. Installing and configuring this integration requires administration in both ServiceNow and HCP Terraform. Since administrators of these services within your organization are not necessarily the same person, this documentation refers to a **ServiceNow Admin** and a **Terraform Admin**. First, the Terraform Admin configures your HCP Terraform organization with a dedicated team for the ServiceNow integration, and obtains a team API token for that team. The Terraform Admin provides the following to your ServiceNow admin: * An Organization name * A team API token * The hostname of your HCP Terraform instance * Any available no-code modules or version control repositories containing Terraform configurations * Other required variables token, the hostname of your HCP Terraform instance, and details about no-code modules or version control repositories containing Terraform configurations and required variables to the ServiceNow Admin. Next, the ServiceNow Admin will install the Terraform ServiceNow Catalog integration to your ServiceNow instance, and configure it using the team API token and hostname. Finally, the ServiceNow Admin will create a Service Catalog within ServiceNow for the Terraform integration, and configure it using the version control repositories or no-code modules, and variable definitions provided by the Terraform Admin. | ServiceNow Admin | Terraform Admin | | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | | Prepare an organization for use with the ServiceNow Catalog. | | | Create a team that can manage workspaces in that organization. | | | Create a team API token so the integration can use that team's permissions. | | | If using VCS repositories, retrieve the OAuth token IDs and repository identifiers that HCP Terraform uses to identify your VCS repositories. If using a no-code flow, [create a no-code ready module](/terraform/cloud-docs/no-code-provisioning/provisioning) in your organization's private registry. Learn more in [Configure VCS Repositories or No-Code Modules](/terraform/cloud-docs/integrations/service-now/service-catalog-terraform/service-catalog-config#configure-vcs-repositories-or-no-code-modules).| | | Provide the API token, OAuth token ID, repository identifiers, variable definitions, and HCP Terraform hostname to the ServiceNow Admin. | | Install the Terraform integration application from the ServiceNow App Store. | | | Connect the integration application with HCP Terraform. | | | Add the Terraform Service Catalog to ServiceNow. | | | If you are using the VCS flow, configure the VCS repositories in ServiceNow. | | | Configure variable sets for use with the VCS repositories or no-code modules.| | Once these steps are complete, self-serve infrastructure will be available through the ServiceNow Catalog. HCP Terraform will provision and manage requested infrastructure and report the status back to ServiceNow. ## Prerequisites To start using Terraform with the ServiceNow Catalog Integration, you must have: - An administrator account on a Terraform Enterprise instance or within a HCP Terraform organization. - An administrator account on your ServiceNow instance. - If you are using the VCS flow, one or more [supported version control systems](/terraform/cloud-docs/vcs#supported-vcs-providers) (VCSs) with read access to repositories with Terraform configurations. - If you are using no-code provisioning, one or more [no-code modules](/terraform/cloud-docs/no-code-provisioning/provisioning) created in your organization's private registry. Refer to the [no-code module configuration](/terraform/cloud-docs/integrations/service-now/service-catalog-terraform/service-catalog-config#no-code-module-configuration) for information about using no-code modules with the ServiceNow Service Catalog for Terraform. You can use this integration on the following ServiceNow server versions: - Utah - Vancouver - Washington DC - Xanadu It requires the following ServiceNow plugins as dependencies: - Flow Designer support for the Service Catalog (`com.glideapp.servicecatalog.flow_designer`) - ServiceNow IntegrationHub Action Step - Script (`com.glide.hub.action_step.script`) - ServiceNow IntegrationHub Action Step - REST (`com.glide.hub.action_step.rest`) -> **Note:** Dependent plugins are installed on your ServiceNow instance automatically when the app is downloaded from the ServiceNow Store. ## Configure HCP Terraform Before installing the ServiceNow integration, the Terraform Admin will need to perform the following steps to configure and gather information from HCP Terraform. 1. Either [create an organization](/terraform/cloud-docs/users-teams-organizations/organizations#creating-organizations) or choose an existing organization where ServiceNow will create new workspaces. **Save the organization name for later.** 2. [Create a team](/terraform/cloud-docs/users-teams-organizations/teams) for that organization called "ServiceNow", and ensure that it has [permission to manage workspaces](/terraform/cloud-docs/users-teams-organizations/permissions#manage-all-workspaces). You do not need to add any users to this team. [permissions-citation]: #intentionally-unused---keep-for-maintainers 3. On the "ServiceNow" team's settings page, generate a [team API token](/terraform/cloud-docs/users-teams-organizations/api-tokens#team-api-tokens). **Save the team API token for later.** 4. If you are using the [VCS flow](/terraform/cloud-docs/integrations/service-now/service-catalog-terraform/service-catalog-config#vcs-configuration): 1. Ensure your Terraform organization is [connected to a VCS provider](/terraform/cloud-docs/vcs). Repositories that are connectable to HCP Terraform workspaces can also be used as workspace templates in the ServiceNow integration. 2. On your organization's VCS provider settings page (**Settings** > **VCS Providers**), find the OAuth Token ID for the VCS provider(s) that you intend to use with the ServiceNow integration. HCP Terraform uses the OAuth token ID to identify and authorize the VCS provider. **Save the OAuth token ID for later.** 3. Identify the VCS repositories in the VCS provider containing Terraform configurations that the ServiceNow Terraform integration will deploy. Take note of any Terraform or environment variables used by the repositories you select. Save the Terraform and environment variables for later. 5. If using the [no-code flow](/terraform/cloud-docs/integrations/service-now/service-catalog-terraform/service-catalog-config#no-code-module-configuration), create one or more no-code modules in the private registry of your HCP Terraform. **Save the no-code module names for later.** 6. Provide the following information to the ServiceNow Admin: * The organization name * The team API token * The hostname of your Terraform Enterprise instance, or of HCP Terraform. The hostname of HCP Terraform is `app.terraform.io`. * The no-code module name(s) or the OAuth token ID(s) of your VCS provider(s), and the repository identifier for each VCS repository containing Terraform configurations that will be used by the integration. * Any Terraform or environment variables required by the configurations in the given VCS repositories. -> **Note:** Repository identifiers are determined by your VCS provider; they typically use a format like `<ORGANIZATION>/<REPO_NAME>` or `<PROJECT_KEY>/<REPO_NAME>`. Azure DevOps repositories use the format `<ORGANIZATION>/<PROJECT>/_git/<REPO_NAME>`. A GitHub repository hosted at `https://github.com/exampleorg/examplerepo/` would have the repository identifier `exampleorg/examplerepo`. [permissions-citation]: #intentionally-unused---keep-for-maintainers For instance, if you are configuring this integration for your company, `Example Corp`, using two GitHub repositories, you would share values like the following with the ServiceNow Admin. ```markdown Terraform Enterprise Organization Name: `ServiceNowExampleOrg` Team API Token: `q2uPExampleELkQ.atlasv1.A7jGHmvufExampleTeamAPITokenimVYxwunJk0xD8ObVol054` Terraform Enterprise Hostname: `terraform.corp.example` OAuth Token ID (GitHub org: example-corp): `ot-DhjEXAMPLELVtFA` - Repository ID (Developer Environment): `example-corp/developer-repo` - Environment variables: - `AWS_ACCESS_KEY_ID=AKIAEXAMPLEKEY` - `AWS_SECRET_ACCESS_KEY=ZB0ExampleSecretAccessKeyGjUiJh` - `AWS_DEFAULT_REGION=us-west-2` - Terraform variables: - `instance_type=t2.medium` - Repository ID (Testing Environment): `example-corp/testing-repo` - Environment variables: - `AWS_ACCESS_KEY_ID=AKIAEXAMPLEKEY` - `AWS_SECRET_ACCESS_KEY=ZB0ExampleSecretAccessKeyGjUiJh` - `AWS_DEFAULT_REGION=us-west-2` - Terraform variables: - `instance_type=t2.large` ``` ## Install the ServiceNow Integration Before beginning setup, the ServiceNow Admin must install the Terraform ServiceNow Catalog integration software. This can be added to your ServiceNow instance from the [ServiceNow Store](https://store.servicenow.com/sn_appstore_store.do). Search for the "Terraform" integration, published by "HashiCorp Inc". ![Screenshot: ServiceNow Store Page](/img/docs/service-now-store.png "Screenshot of the ServiceNow Store listing for the Terraform Integration") ## Connect ServiceNow to HCP Terraform -> **ServiceNow Roles:** `admin` or `x_terraform.config_user` Once the integration is installed, the ServiceNow Admin can connect your ServiceNow instance to HCP Terraform. Before you begin, you will need the information described in the "Configure HCP Terraform" section from your Terraform Admin. Once you have this information, connect ServiceNow to HCP Terraform with the following steps. 1. Navigate to your ServiceNow Service Management Screen. 1. Using the left-hand navigation, open the configuration table for the integration to manage the HCP Terraform connection. - Terraform > Configs 1. Click on "New" to create a new HCP Terraform connection. - Set Org Name to the HCP Terraform organization name. - Click on the "Lock" icon to set Hostname to the hostname of your Terraform Enterprise instance. If you are using the SaaS version of HCP Terraform, the hostname is `https://app.terraform.io`. Be sure to include "https://" before the hostname. - Set API Team Token to the HCP Terraform team API token. - (Optional) To use the [MID Server](https://docs.servicenow.com/csh?topicname=mid-server-landing.html&version=latest), select the checkbox and type the `name` in the `MID Server Name` field. 1. Click "Submit". ![Screenshot: ServiceNow Terraform Config](/img/docs/service-now-updated-config.png "Screenshot of the ServiceNow Terraform Config New Record page") ## Create and Populate a Service Catalog Now that you have connected ServiceNow to HCP Terraform, you are ready to create a Service Catalog using the VCS repositories or no-code modules provided by the Terraform Admin. Navigate to the [Service Catalog documentation](/terraform/cloud-docs/integrations/service-now/service-catalog-terraform/service-catalog-config) to begin. You can also refer to this documentation whenever you need to add or update request items. ### ServiceNow Developer Reference ServiceNow developers who wish to customize the Terraform integration can refer to the [developer documentation](/terraform/cloud-docs/integrations/service-now/service-catalog-terraform/developer-reference). ### ServiceNow Administrator's Guide. Refer to the [ServiceNow Administrator documentation](/terraform/cloud-docs/integrations/service-now/service-catalog-terraform/admin-guide) for information about configuring the integration. ### Example Customizations Once the ServiceNow integration is installed, you can consult the [example customizations documentation](/terraform/cloud-docs/integrations/service-now/service-catalog-terraform/example-customizations).
terraform
page title Setup Instructions ServiceNow Service Catalog Integration HCP Terraform description ServiceNow integration enables your users to order Terraform built infrastructure from ServiceNow Terraform ServiceNow Service Catalog Integration Setup Instructions Integration version v2 7 0 The Terraform ServiceNow Service Catalog integration enables your end users to provision self serve infrastructure via ServiceNow By connecting ServiceNow to HCP Terraform this integration lets ServiceNow users order Service Items create workspaces and perform Terraform runs using prepared Terraform configurations hosted in VCS repositories or as no code modules terraform cloud docs no code provisioning module design for self service provisioning BEGIN TFC only name pnp callout include tfc package callouts servicenow catalog mdx END TFC only name pnp callout Summary of the Setup Process The integration relies on Terraform ServiceNow Catalog integration software installed within your ServiceNow instance Installing and configuring this integration requires administration in both ServiceNow and HCP Terraform Since administrators of these services within your organization are not necessarily the same person this documentation refers to a ServiceNow Admin and a Terraform Admin First the Terraform Admin configures your HCP Terraform organization with a dedicated team for the ServiceNow integration and obtains a team API token for that team The Terraform Admin provides the following to your ServiceNow admin An Organization name A team API token The hostname of your HCP Terraform instance Any available no code modules or version control repositories containing Terraform configurations Other required variables token the hostname of your HCP Terraform instance and details about no code modules or version control repositories containing Terraform configurations and required variables to the ServiceNow Admin Next the ServiceNow Admin will install the Terraform ServiceNow Catalog integration to your ServiceNow instance and configure it using the team API token and hostname Finally the ServiceNow Admin will create a Service Catalog within ServiceNow for the Terraform integration and configure it using the version control repositories or no code modules and variable definitions provided by the Terraform Admin ServiceNow Admin Terraform Admin Prepare an organization for use with the ServiceNow Catalog Create a team that can manage workspaces in that organization Create a team API token so the integration can use that team s permissions If using VCS repositories retrieve the OAuth token IDs and repository identifiers that HCP Terraform uses to identify your VCS repositories If using a no code flow create a no code ready module terraform cloud docs no code provisioning provisioning in your organization s private registry Learn more in Configure VCS Repositories or No Code Modules terraform cloud docs integrations service now service catalog terraform service catalog config configure vcs repositories or no code modules Provide the API token OAuth token ID repository identifiers variable definitions and HCP Terraform hostname to the ServiceNow Admin Install the Terraform integration application from the ServiceNow App Store Connect the integration application with HCP Terraform Add the Terraform Service Catalog to ServiceNow If you are using the VCS flow configure the VCS repositories in ServiceNow Configure variable sets for use with the VCS repositories or no code modules Once these steps are complete self serve infrastructure will be available through the ServiceNow Catalog HCP Terraform will provision and manage requested infrastructure and report the status back to ServiceNow Prerequisites To start using Terraform with the ServiceNow Catalog Integration you must have An administrator account on a Terraform Enterprise instance or within a HCP Terraform organization An administrator account on your ServiceNow instance If you are using the VCS flow one or more supported version control systems terraform cloud docs vcs supported vcs providers VCSs with read access to repositories with Terraform configurations If you are using no code provisioning one or more no code modules terraform cloud docs no code provisioning provisioning created in your organization s private registry Refer to the no code module configuration terraform cloud docs integrations service now service catalog terraform service catalog config no code module configuration for information about using no code modules with the ServiceNow Service Catalog for Terraform You can use this integration on the following ServiceNow server versions Utah Vancouver Washington DC Xanadu It requires the following ServiceNow plugins as dependencies Flow Designer support for the Service Catalog com glideapp servicecatalog flow designer ServiceNow IntegrationHub Action Step Script com glide hub action step script ServiceNow IntegrationHub Action Step REST com glide hub action step rest Note Dependent plugins are installed on your ServiceNow instance automatically when the app is downloaded from the ServiceNow Store Configure HCP Terraform Before installing the ServiceNow integration the Terraform Admin will need to perform the following steps to configure and gather information from HCP Terraform 1 Either create an organization terraform cloud docs users teams organizations organizations creating organizations or choose an existing organization where ServiceNow will create new workspaces Save the organization name for later 2 Create a team terraform cloud docs users teams organizations teams for that organization called ServiceNow and ensure that it has permission to manage workspaces terraform cloud docs users teams organizations permissions manage all workspaces You do not need to add any users to this team permissions citation intentionally unused keep for maintainers 3 On the ServiceNow team s settings page generate a team API token terraform cloud docs users teams organizations api tokens team api tokens Save the team API token for later 4 If you are using the VCS flow terraform cloud docs integrations service now service catalog terraform service catalog config vcs configuration 1 Ensure your Terraform organization is connected to a VCS provider terraform cloud docs vcs Repositories that are connectable to HCP Terraform workspaces can also be used as workspace templates in the ServiceNow integration 2 On your organization s VCS provider settings page Settings VCS Providers find the OAuth Token ID for the VCS provider s that you intend to use with the ServiceNow integration HCP Terraform uses the OAuth token ID to identify and authorize the VCS provider Save the OAuth token ID for later 3 Identify the VCS repositories in the VCS provider containing Terraform configurations that the ServiceNow Terraform integration will deploy Take note of any Terraform or environment variables used by the repositories you select Save the Terraform and environment variables for later 5 If using the no code flow terraform cloud docs integrations service now service catalog terraform service catalog config no code module configuration create one or more no code modules in the private registry of your HCP Terraform Save the no code module names for later 6 Provide the following information to the ServiceNow Admin The organization name The team API token The hostname of your Terraform Enterprise instance or of HCP Terraform The hostname of HCP Terraform is app terraform io The no code module name s or the OAuth token ID s of your VCS provider s and the repository identifier for each VCS repository containing Terraform configurations that will be used by the integration Any Terraform or environment variables required by the configurations in the given VCS repositories Note Repository identifiers are determined by your VCS provider they typically use a format like ORGANIZATION REPO NAME or PROJECT KEY REPO NAME Azure DevOps repositories use the format ORGANIZATION PROJECT git REPO NAME A GitHub repository hosted at https github com exampleorg examplerepo would have the repository identifier exampleorg examplerepo permissions citation intentionally unused keep for maintainers For instance if you are configuring this integration for your company Example Corp using two GitHub repositories you would share values like the following with the ServiceNow Admin markdown Terraform Enterprise Organization Name ServiceNowExampleOrg Team API Token q2uPExampleELkQ atlasv1 A7jGHmvufExampleTeamAPITokenimVYxwunJk0xD8ObVol054 Terraform Enterprise Hostname terraform corp example OAuth Token ID GitHub org example corp ot DhjEXAMPLELVtFA Repository ID Developer Environment example corp developer repo Environment variables AWS ACCESS KEY ID AKIAEXAMPLEKEY AWS SECRET ACCESS KEY ZB0ExampleSecretAccessKeyGjUiJh AWS DEFAULT REGION us west 2 Terraform variables instance type t2 medium Repository ID Testing Environment example corp testing repo Environment variables AWS ACCESS KEY ID AKIAEXAMPLEKEY AWS SECRET ACCESS KEY ZB0ExampleSecretAccessKeyGjUiJh AWS DEFAULT REGION us west 2 Terraform variables instance type t2 large Install the ServiceNow Integration Before beginning setup the ServiceNow Admin must install the Terraform ServiceNow Catalog integration software This can be added to your ServiceNow instance from the ServiceNow Store https store servicenow com sn appstore store do Search for the Terraform integration published by HashiCorp Inc Screenshot ServiceNow Store Page img docs service now store png Screenshot of the ServiceNow Store listing for the Terraform Integration Connect ServiceNow to HCP Terraform ServiceNow Roles admin or x terraform config user Once the integration is installed the ServiceNow Admin can connect your ServiceNow instance to HCP Terraform Before you begin you will need the information described in the Configure HCP Terraform section from your Terraform Admin Once you have this information connect ServiceNow to HCP Terraform with the following steps 1 Navigate to your ServiceNow Service Management Screen 1 Using the left hand navigation open the configuration table for the integration to manage the HCP Terraform connection Terraform Configs 1 Click on New to create a new HCP Terraform connection Set Org Name to the HCP Terraform organization name Click on the Lock icon to set Hostname to the hostname of your Terraform Enterprise instance If you are using the SaaS version of HCP Terraform the hostname is https app terraform io Be sure to include https before the hostname Set API Team Token to the HCP Terraform team API token Optional To use the MID Server https docs servicenow com csh topicname mid server landing html version latest select the checkbox and type the name in the MID Server Name field 1 Click Submit Screenshot ServiceNow Terraform Config img docs service now updated config png Screenshot of the ServiceNow Terraform Config New Record page Create and Populate a Service Catalog Now that you have connected ServiceNow to HCP Terraform you are ready to create a Service Catalog using the VCS repositories or no code modules provided by the Terraform Admin Navigate to the Service Catalog documentation terraform cloud docs integrations service now service catalog terraform service catalog config to begin You can also refer to this documentation whenever you need to add or update request items ServiceNow Developer Reference ServiceNow developers who wish to customize the Terraform integration can refer to the developer documentation terraform cloud docs integrations service now service catalog terraform developer reference ServiceNow Administrator s Guide Refer to the ServiceNow Administrator documentation terraform cloud docs integrations service now service catalog terraform admin guide for information about configuring the integration Example Customizations Once the ServiceNow integration is installed you can consult the example customizations documentation terraform cloud docs integrations service now service catalog terraform example customizations
terraform page title Troubleshooting tips ServiceNow Service Catalog Integration HCP Terraform HCP Terraform ServiceNow Service Catalog Integration troubleshooting tips It also provides instructions on how to find and read logs to diagnose and resolve issues Troubleshooting tips for ServiceNow Service Catalog Integration This page offers troubleshooting tips for common issues with the ServiceNow Service Catalog Integration for HCP Terraform
--- page_title: Troubleshooting tips - ServiceNow Service Catalog Integration - HCP Terraform description: Troubleshooting tips for ServiceNow Service Catalog Integration. --- # HCP Terraform ServiceNow Service Catalog Integration troubleshooting tips. This page offers troubleshooting tips for common issues with the ServiceNow Service Catalog Integration for HCP Terraform. It also provides instructions on how to find and read logs to diagnose and resolve issues. ## Find logs Logs are crucial for diagnosing issues. You can find logs in ServiceNow in the following places: ### Workflow logs To find workflow logs, click on the RITM number on a failed ticket to open the request item. Scroll down to **Related Links > Workflow Context** and open the **Workflow Log** tab. ### Flow logs To find flow logs, click on the RITM number on a failed ticket to open the request item. Scroll down to **Related Links > Flow Context > Open Context Record** and open the **Flow engine log entries** tab. ### Application logs To find application logs, navigate to **All > System Log > Application Logs.** Set the **Application** filter to "Terraform". Search for logs around the time your issue occurred. Some records include HTTP status codes and detailed error messages. ### Outbound requests ServiceNow logs all outgoing API calls, including calls to HCP Terraform. To view the log of outbound requests, navigate to **All > System Logs > Outbound HTTP Requests.** To customize the table view, add columns like "URL," "URL Path," and "Application scope." Logs from the Catalog app are marked with the `x_325709_terraform` scope. ## Enable email notifications To enable email notifications and receive updates on your requested item tickets: 1. Log in to your ServiceNow instance as an administrator. 1. **Click System Properties > Email Properties**. 1. In the **Outbound Email Configuration** panel, select **Yes** next to the check-box with the email that ServiceNow should send notifications to. To ensure you have relevant notifications configured in your instance: 1. Navigate to **System Notification > Email > Notifications.** 1. Search for "Request Opened" and "Request Item Commented" and ensure they are activated. Reaching out to ServiceNow customer support if you run into any issues with the global configurations.out to ServiceNow customer support if you run into any issues with the global configurations. ## Common problems This section details frequently encountered issues and how they can be resolved. ### Failure to create a workspace If you order the "create a workspace" catalog item and nothing happens in ServiceNow and HCP Terraform does not create a workspace then there are several possible reasons why: Ensure your HCP Terraform token, hostname, and organization name is correct. 1. Make sure to use a **Team API Token**. This can be found in HCP Terraform under "API Tokens". 1. Ensure the team API token has the correct permissions. 1. Double-check your organization name by copying and pasting it from HCP Terraform or Terraform Enterprise. 1. Double-check your host name. 1. Make sure you created your team API token in the same organization you are using 1. Test your configuration. First click **Update** to process any changes then **Test Config to make sure the connection is working. Verify your VCS configuration. 1. The **Identifier** field should not have any spaces. The ServiceNow Service Catalog Integration requires that you format repository names in the `username/repo_name` format. 1. The **Name** can be anything, but it is better to avoid special characters as per naming convention. 1. Double-check the OAuth token ID in your HCP Terraform/Terraform Enterprise settings. To retrieve your OAuth token ID, navigate to your HCP Terraform organization's settings page, then click **Provider** in the left navigation bar under **Version Control**. ### Failure to successfully order any catalog item After placing an order for any catalog item, navigate to the comments section in the newly created RITM ticket. The latest comment will contain a response from HCP Terraform. ### Frequency of comments and outputs When you place an order in the Terraform Catalog, ServiceNow submits and processes the order, then attaches additional comments to the order to indicate whether HCP Terraform successfully created the workspace. By default, ServiceNow polls HCP Terraform every 5 minutes for the latest status of the Terraform run. ServiceNow does not show any comments until the next ping. To configure ServiceNow to poll HCP Terraform more frequently: 1. Navigate to **All > Flow designer**. 1. Set the **Application** filter to **Terraform**. 1. Under the **Name** column click **Worker Poll Run State**. 1. Click on the trigger and adjust the interval to your desired schedule. 1. Click **Done > Save > Activate** to save your changes. ### Using no-code modules feature If ServiceNow fails to deploy a no-code module catalog item, verify the following: 1. Ensure that your HCP Terraform organization has an [HCP Plus tier](https://www.hashicorp.com/products/terraform/pricing) subscription. 1. Ensure the name you enter for your no-code module in the catalog user form matches the no-code module in HCP Terraform. ### Updating no-code workspaces If the “update no-code workspace” catalog item returns the output message “No update has been made to the workspace”, then you have not upgraded your no-code module in HCP Terraform. ### Application Scope If you are making customizations and you encounter unexpected issues, make sure to change the scope from **Global** to **Terraform** and recreate your customized items in the **Terraform scope**. For additional instructions on customizations, refer to the [example customizations](/terraform/cloud-docs/integrations/service-now/service-catalog-terraform/example-customizations) documentation. ### MID server If you are using a MID server in your configuration, check the connectivity by using the **Test Config** button on the configurations page. Additionally, when ServiceNow provisions a MID server, navigate to **MID Servers > Servers** to check if the status is “up” and “validated”. ### Configuration While the app allows multiple config entries, only one should be present as this can interfere with the functionality of the app
terraform
page title Troubleshooting tips ServiceNow Service Catalog Integration HCP Terraform description Troubleshooting tips for ServiceNow Service Catalog Integration HCP Terraform ServiceNow Service Catalog Integration troubleshooting tips This page offers troubleshooting tips for common issues with the ServiceNow Service Catalog Integration for HCP Terraform It also provides instructions on how to find and read logs to diagnose and resolve issues Find logs Logs are crucial for diagnosing issues You can find logs in ServiceNow in the following places Workflow logs To find workflow logs click on the RITM number on a failed ticket to open the request item Scroll down to Related Links Workflow Context and open the Workflow Log tab Flow logs To find flow logs click on the RITM number on a failed ticket to open the request item Scroll down to Related Links Flow Context Open Context Record and open the Flow engine log entries tab Application logs To find application logs navigate to All System Log Application Logs Set the Application filter to Terraform Search for logs around the time your issue occurred Some records include HTTP status codes and detailed error messages Outbound requests ServiceNow logs all outgoing API calls including calls to HCP Terraform To view the log of outbound requests navigate to All System Logs Outbound HTTP Requests To customize the table view add columns like URL URL Path and Application scope Logs from the Catalog app are marked with the x 325709 terraform scope Enable email notifications To enable email notifications and receive updates on your requested item tickets 1 Log in to your ServiceNow instance as an administrator 1 Click System Properties Email Properties 1 In the Outbound Email Configuration panel select Yes next to the check box with the email that ServiceNow should send notifications to To ensure you have relevant notifications configured in your instance 1 Navigate to System Notification Email Notifications 1 Search for Request Opened and Request Item Commented and ensure they are activated Reaching out to ServiceNow customer support if you run into any issues with the global configurations out to ServiceNow customer support if you run into any issues with the global configurations Common problems This section details frequently encountered issues and how they can be resolved Failure to create a workspace If you order the create a workspace catalog item and nothing happens in ServiceNow and HCP Terraform does not create a workspace then there are several possible reasons why Ensure your HCP Terraform token hostname and organization name is correct 1 Make sure to use a Team API Token This can be found in HCP Terraform under API Tokens 1 Ensure the team API token has the correct permissions 1 Double check your organization name by copying and pasting it from HCP Terraform or Terraform Enterprise 1 Double check your host name 1 Make sure you created your team API token in the same organization you are using 1 Test your configuration First click Update to process any changes then Test Config to make sure the connection is working Verify your VCS configuration 1 The Identifier field should not have any spaces The ServiceNow Service Catalog Integration requires that you format repository names in the username repo name format 1 The Name can be anything but it is better to avoid special characters as per naming convention 1 Double check the OAuth token ID in your HCP Terraform Terraform Enterprise settings To retrieve your OAuth token ID navigate to your HCP Terraform organization s settings page then click Provider in the left navigation bar under Version Control Failure to successfully order any catalog item After placing an order for any catalog item navigate to the comments section in the newly created RITM ticket The latest comment will contain a response from HCP Terraform Frequency of comments and outputs When you place an order in the Terraform Catalog ServiceNow submits and processes the order then attaches additional comments to the order to indicate whether HCP Terraform successfully created the workspace By default ServiceNow polls HCP Terraform every 5 minutes for the latest status of the Terraform run ServiceNow does not show any comments until the next ping To configure ServiceNow to poll HCP Terraform more frequently 1 Navigate to All Flow designer 1 Set the Application filter to Terraform 1 Under the Name column click Worker Poll Run State 1 Click on the trigger and adjust the interval to your desired schedule 1 Click Done Save Activate to save your changes Using no code modules feature If ServiceNow fails to deploy a no code module catalog item verify the following 1 Ensure that your HCP Terraform organization has an HCP Plus tier https www hashicorp com products terraform pricing subscription 1 Ensure the name you enter for your no code module in the catalog user form matches the no code module in HCP Terraform Updating no code workspaces If the update no code workspace catalog item returns the output message No update has been made to the workspace then you have not upgraded your no code module in HCP Terraform Application Scope If you are making customizations and you encounter unexpected issues make sure to change the scope from Global to Terraform and recreate your customized items in the Terraform scope For additional instructions on customizations refer to the example customizations terraform cloud docs integrations service now service catalog terraform example customizations documentation MID server If you are using a MID server in your configuration check the connectivity by using the Test Config button on the configurations page Additionally when ServiceNow provisions a MID server navigate to MID Servers Servers to check if the status is up and validated Configuration While the app allows multiple config entries only one should be present as this can interfere with the functionality of the app
terraform When using ServiceNow with the HCP Terraform integration you will configure Service Catalog Configuration page title Service Catalog ServiceNow Service Catalog Integration HCP Terraform provision infrastructure using ServiceNow and HCP Terraform Configure Service Catalogs and VCS repositories to allow end users to
--- page_title: Service Catalog - ServiceNow Service Catalog Integration - HCP Terraform description: |- Configure Service Catalogs and VCS repositories to allow end users to provision infrastructure using ServiceNow and HCP Terraform. --- # Service Catalog Configuration When using ServiceNow with the HCP Terraform integration, you will configure at least one service catalog item. You will also configure one or more version control system (VCS) repositories or no-code modules containing the Terraform configurations which will be used to provision that infrastructure. End users will request infrastructure from the service catalog, and HCP Terraform will fulfill the request by creating a new workspace, applying the configuration, and then reporting the results back to ServiceNow. ## Prerequisites Before configuring a service catalog, you must install and configure the HCP Terraform integration software on your ServiceNow instance. These steps are covered in the [installation documentation](/terraform/cloud-docs/integrations/service-now/service-catalog-terraform). Additionally, you must have have the following information: 1. The no-code module name or the OAuth token ID and repository identifier for each VCS repository that HCP Terraform will use to provision infrastructure. Your Terraform Admin will provide these to you. Learn more in [Configure VCS Repositories or No-Code Modules](/terraform/cloud-docs/integrations/service-now/service-catalog-terraform/service-catalog-config#configure-vcs-repositories-or-no-code-modules). 1. Any Terraform or environment variables required by the configurations in the given VCS repositories or no-code modules. Once these steps are complete, in order for end users to provision infrastructure with ServiceNow and HCP Terraform, the ServiceNow Admin will perform the following steps to make Service Items available to your end users. 1. Add at least one service catalog for use with Terraform. 1. If you are using the VCS flow, configure at least one one VCS repository in ServiceNow. 1. Create variable sets to define Terraform and environment variables to be used by HCP Terraform to provision infrastructure. ## Add the Terraform Service Catalog -> **ServiceNow Role:** `admin` First, add a Service Catalog for use with the Terraform integration. Depending on your organization's needs, you might use a single service catalog, or several. If you already have a Service Catalog to use with Terraform, skip to the next step. 1. In ServiceNow, open the Service Catalog > Catalogs view by searching for "Service Catalog" in the left-hand navigation. 1. Click the plus sign in the top right. 1. Select "Catalogs > Terraform Catalog > Title and Image" and choose a location to add the Service Catalog. 1. Close the "Sections" dialog box by clicking the "x" in the upper right-hand corner. -> **Note:** In step 1, be sure to choose "Catalogs", not "Catalog" from the left-hand navigation. ## Configure VCS Repositories or No-Code Modules -> **ServiceNow Roles:** `admin` or `x_terraform.vcs_repositories_user` Terraform workspaces created through the ServiceNow Service Catalog for Terraform can be associated with a VCS provider repository or be backed by a [no-code module](/terraform/cloud-docs/no-code-provisioning/provisioning) in your organization's private registry. Administrators determine which workspace type end users can request from the Terraform Catalog. Below are the key differences between the version control and no-code approaches. ### VCS configuration To make infrastructure available to your users through version control workspaces, you must add one or more VCS repositories containing Terraform configurations to the Service Catalog for Terraform. 1. In ServiceNow, open the "Terraform > VCS Repositories" table by searching for "Terraform" in the left-hand navigation. 1. Click "New" to add a VCS repository, and fill in the following fields: - Name: The name for this repository. This name will be visible to end users, and does not have to be the same as the repository name as defined by your VCS provider. Ideally it will succinctly describe the infrastructure that will be provisioned by Terraform from the repository. - OAuth Token ID: The OAuth token ID that from your HCP Terraform organization's VCS providers settings. This ID specifies which VCS provider configured in HCP Terraform hosts the desired repository. - Identifier: The VCS repository that contains the Terraform configuration for this workspace template. Repository identifiers are determined by your VCS provider; they typically use a format like `<ORGANIZATION>/<REPO_NAME>` or `<PROJECT KEY>/<REPO_NAME>`. Azure DevOps repositories use the format `<ORGANIZATION>/<PROJECT>/_git/<REPO_NAME>`. - The remaining fields are optional. - Branch: The branch within the repository, if different from the default branch. - Working Directory: The directory within the repository containing Terraform configuration. - Terraform Version: The version of Terraform to use. This will default to the latest version of Terraform supported by your HCP Terraform instance. 1. Click "Submit". ![Screenshot: ServiceNow New VCS Repository](/img/docs/service-now-vcs-repository.png "Screenshot of the ServiceNow Terraform New VCS Repository page") After configuring your repositories in ServiceNow, the names of those repositories will be available in the "VCS Repository" dropdown menu a user orders new workspaces through the following items in the Terraform Catalog: - **Create Workspace** - **Create Workspace with Variables** - **Provision Resources** - **Provision Resources with Variables** ### No-Code Module Configuration In version 2.5.0 and newer, ServiceNow administrators can configure Catalog Items using [no-code modules](/terraform/cloud-docs/no-code-provisioning/provisioning). This release introduces two new additions to the Terraform Catalog - no-code workspace create and update Items. Both utilize no-code modules from the private registry in HCP Terraform to enable end users to request infrastructure without writing code. <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/nocode.mdx' <!-- END: TFC:only name:pnp-callout --> The following Catalog Items allow you to build and manage workspaces with no-code modules: - **Provision No-Code Workspace and Deploy Resources**: creates a new Terraform workspace based on a no-code module of your choice, supplies required variable values, runs and applies Terraform. - **Update No-Code Workspace and Deploy Resources**: Updates an existing no-code workspace to the most recent no-code module version, updates that workspace's attached variable values, and then starts and applies a new Terraform run. Administrators can skip configuring VCS repositories in ServiceNow when using no-code modules. The only input required in the no-code workspace request form is the name of the no-code module. Before utilizing a no-code module, you must publish it to the your organization's private module registry. With this one-time configuration complete, ServiceNow Administrators can then call the modules through Catalog requests without repository management, simplifying the use of infrastructure-as-code. > **Hands On:** Try the [Self-service enablement with HCP Terraform and ServiceNow tutorial](/terraform/tutorials/it-saas/servicenow-no-code). ## Configure a Variable Set Most Terraform configurations can be customized with Terraform variables or environment variables. You can create a Variable Set within ServiceNow to contain the variables needed for a given configuration. Your Terraform Admin should provide these to you. 1. In ServiceNow, open the "Service Catalog > Variable Sets" table by searching for "variable sets" in the left-hand navigation. 1. Click "New" to add a Variable Set. 1. Select "Single-Row Variable Set". - Title: User-visible title for the variable set. - Internal name: The internal name for the variable set. - Order: The order in which the variable set will be displayed. - Type: Should be set to "Single Row" - Application: Should be set to "Terraform" - Display title: Whether the title is displayed to the end user. - Layout: How the variables in the set will be displayed on the screen. - Description: A long description of the variable set. 1. Click "Submit" to create the variable set. 1. Find and click on the title of the new variable set in the Variable Sets table. 1. At the bottom of the variable set details page, click "New" to add a new variable. - Type: Should be "Single Line Text" for most variables, or "Masked" for variables containing sensitive values. - Question: The user-visible question or label for the variable. - Name: The internal name of the variable. This must be derived from the name of the Terraform or environment variable. Consult the table below to determine the proper prefix for each variable name. - Tooltip: A tooltip to display for the variable. - Example Text: Example text to show in the variable's input box. 1. Under the "Default Value" tab, you can set a default value for the variable. 1. Continue to add new variables corresponding to the Terraform and environment variables the configuration requires. When the Terraform integration applies configuration, it will map ServiceNow variables to Terraform and environment variables using the following convention. ServiceNow variables that begin with "sensitive_" will be saved as sensitive variables within HCP Terraform. | ServiceNow Variable Name | HCP Terraform Variable | | -------------------------------- | ---------------------------------------------------------- | | `tf_var_VARIABLE_NAME` | Terraform Variable: `VARIABLE_NAME` | | `tf_env_ENV_NAME` | Environment Variable: `ENV_NAME` | | `sensitive_tf_var_VARIABLE_NAME` | Sensitive Terraform Variable (Write Only): `VARIABLE_NAME` | | `sensitive_tf_env_ENV_NAME` | Sensitive Environment Variable (Write Only): `ENV_NAME` | ## Provision Infrastructure Once you configure the Service Catalog for Terraform, ServiceNow users can request infrastructure to be provisioned by HCP Terraform. These requests will be fulfilled by HCP Terraform, which will: 1. Create a new workspace from the no-code module or the VCS repository provided by ServiceNow. 1. Configure variables for that workspace, also provided by ServiceNow. 1. Plan and apply the change. 1. Report the results, including any outputs from Terraform, to ServiceNow. Once this is complete, ServiceNow will reflect that the Request Item has been provisioned. -> **Note:** The integration creates workspaces with [auto-apply](/terraform/cloud-docs/workspaces/settings#auto-apply-and-manual-apply) enabled. HCP Terraform will queue an apply for these workspaces whenever changes are merged to the associated VCS repositories. This is known as the [VCS-driven run workflow](/terraform/cloud-docs/run/ui). It is important to keep in mind that all of the ServiceNow workspaces connected to a given repository will be updated whenever changes are merged to the associated branch in that repository. ## Execution Mode If using v2.2.0 or above, the Service Catalog app allows you to set an [execution mode](/terraform/cloud-docs/workspaces/settings#execution-mode) for your Terraform workspaces. There are two modes to choose from: - The default value is "Remote", which instructs HCP Terraform to perform runs on its disposable virtual machines. - Selecting "Agent" mode allows you to run Terraform operations on isolated, private, or on-premises infrastructure. This option requires you to create an Agent Pool in your organization beforehand, then provide that Agent Pool's id when you order a new workspace through the Service Catalog. <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/agents.mdx' <!-- END: TFC:only name:pnp-callout --> ## Workspace Name Version 2.4.0 of the Service Catalog for Terraform introduces the ability to set custom names for your Terraform workspaces. You can choose a prefix for your workspace name that the Service Catalog app will append the ServiceNow RITM number to. If you do not define a workspace prefix, ServiceNow will use RITM number as the workspace name. Workspace names can include letters, numbers, dashes (`-`), and underscores (`_`), and should not exceed 90 characters. Refer to the [workspace naming recommendations](/terraform/cloud-docs/workspaces/create#workspace-naming) for best practices. ## Workspace Tags Version 2.4.0 also allows you to add custom tags to your Terraform workspaces. Use the "Workspace Tags" field to provide a comma-separated list of tags that will be parsed and attached to the workspace in HCP Terraform. Tags give you an easier way to categorize, filter, and manage workspaces provisioned through the Service Catalog for Terraform. We recommend that you set naming conventions for tags with your end users to avoid variations such as `ec2`, `aws-ec2`, `aws_ec2`. Workspace tags have a 255 character limit and can contain letters, numbers, colons, hyphens, and underscores. Refer to the [workspace tagging rules](/terraform/cloud-docs/workspaces/create#workspace-tags) for more details.
terraform
page title Service Catalog ServiceNow Service Catalog Integration HCP Terraform description Configure Service Catalogs and VCS repositories to allow end users to provision infrastructure using ServiceNow and HCP Terraform Service Catalog Configuration When using ServiceNow with the HCP Terraform integration you will configure at least one service catalog item You will also configure one or more version control system VCS repositories or no code modules containing the Terraform configurations which will be used to provision that infrastructure End users will request infrastructure from the service catalog and HCP Terraform will fulfill the request by creating a new workspace applying the configuration and then reporting the results back to ServiceNow Prerequisites Before configuring a service catalog you must install and configure the HCP Terraform integration software on your ServiceNow instance These steps are covered in the installation documentation terraform cloud docs integrations service now service catalog terraform Additionally you must have have the following information 1 The no code module name or the OAuth token ID and repository identifier for each VCS repository that HCP Terraform will use to provision infrastructure Your Terraform Admin will provide these to you Learn more in Configure VCS Repositories or No Code Modules terraform cloud docs integrations service now service catalog terraform service catalog config configure vcs repositories or no code modules 1 Any Terraform or environment variables required by the configurations in the given VCS repositories or no code modules Once these steps are complete in order for end users to provision infrastructure with ServiceNow and HCP Terraform the ServiceNow Admin will perform the following steps to make Service Items available to your end users 1 Add at least one service catalog for use with Terraform 1 If you are using the VCS flow configure at least one one VCS repository in ServiceNow 1 Create variable sets to define Terraform and environment variables to be used by HCP Terraform to provision infrastructure Add the Terraform Service Catalog ServiceNow Role admin First add a Service Catalog for use with the Terraform integration Depending on your organization s needs you might use a single service catalog or several If you already have a Service Catalog to use with Terraform skip to the next step 1 In ServiceNow open the Service Catalog Catalogs view by searching for Service Catalog in the left hand navigation 1 Click the plus sign in the top right 1 Select Catalogs Terraform Catalog Title and Image and choose a location to add the Service Catalog 1 Close the Sections dialog box by clicking the x in the upper right hand corner Note In step 1 be sure to choose Catalogs not Catalog from the left hand navigation Configure VCS Repositories or No Code Modules ServiceNow Roles admin or x terraform vcs repositories user Terraform workspaces created through the ServiceNow Service Catalog for Terraform can be associated with a VCS provider repository or be backed by a no code module terraform cloud docs no code provisioning provisioning in your organization s private registry Administrators determine which workspace type end users can request from the Terraform Catalog Below are the key differences between the version control and no code approaches VCS configuration To make infrastructure available to your users through version control workspaces you must add one or more VCS repositories containing Terraform configurations to the Service Catalog for Terraform 1 In ServiceNow open the Terraform VCS Repositories table by searching for Terraform in the left hand navigation 1 Click New to add a VCS repository and fill in the following fields Name The name for this repository This name will be visible to end users and does not have to be the same as the repository name as defined by your VCS provider Ideally it will succinctly describe the infrastructure that will be provisioned by Terraform from the repository OAuth Token ID The OAuth token ID that from your HCP Terraform organization s VCS providers settings This ID specifies which VCS provider configured in HCP Terraform hosts the desired repository Identifier The VCS repository that contains the Terraform configuration for this workspace template Repository identifiers are determined by your VCS provider they typically use a format like ORGANIZATION REPO NAME or PROJECT KEY REPO NAME Azure DevOps repositories use the format ORGANIZATION PROJECT git REPO NAME The remaining fields are optional Branch The branch within the repository if different from the default branch Working Directory The directory within the repository containing Terraform configuration Terraform Version The version of Terraform to use This will default to the latest version of Terraform supported by your HCP Terraform instance 1 Click Submit Screenshot ServiceNow New VCS Repository img docs service now vcs repository png Screenshot of the ServiceNow Terraform New VCS Repository page After configuring your repositories in ServiceNow the names of those repositories will be available in the VCS Repository dropdown menu a user orders new workspaces through the following items in the Terraform Catalog Create Workspace Create Workspace with Variables Provision Resources Provision Resources with Variables No Code Module Configuration In version 2 5 0 and newer ServiceNow administrators can configure Catalog Items using no code modules terraform cloud docs no code provisioning provisioning This release introduces two new additions to the Terraform Catalog no code workspace create and update Items Both utilize no code modules from the private registry in HCP Terraform to enable end users to request infrastructure without writing code BEGIN TFC only name pnp callout include tfc package callouts nocode mdx END TFC only name pnp callout The following Catalog Items allow you to build and manage workspaces with no code modules Provision No Code Workspace and Deploy Resources creates a new Terraform workspace based on a no code module of your choice supplies required variable values runs and applies Terraform Update No Code Workspace and Deploy Resources Updates an existing no code workspace to the most recent no code module version updates that workspace s attached variable values and then starts and applies a new Terraform run Administrators can skip configuring VCS repositories in ServiceNow when using no code modules The only input required in the no code workspace request form is the name of the no code module Before utilizing a no code module you must publish it to the your organization s private module registry With this one time configuration complete ServiceNow Administrators can then call the modules through Catalog requests without repository management simplifying the use of infrastructure as code Hands On Try the Self service enablement with HCP Terraform and ServiceNow tutorial terraform tutorials it saas servicenow no code Configure a Variable Set Most Terraform configurations can be customized with Terraform variables or environment variables You can create a Variable Set within ServiceNow to contain the variables needed for a given configuration Your Terraform Admin should provide these to you 1 In ServiceNow open the Service Catalog Variable Sets table by searching for variable sets in the left hand navigation 1 Click New to add a Variable Set 1 Select Single Row Variable Set Title User visible title for the variable set Internal name The internal name for the variable set Order The order in which the variable set will be displayed Type Should be set to Single Row Application Should be set to Terraform Display title Whether the title is displayed to the end user Layout How the variables in the set will be displayed on the screen Description A long description of the variable set 1 Click Submit to create the variable set 1 Find and click on the title of the new variable set in the Variable Sets table 1 At the bottom of the variable set details page click New to add a new variable Type Should be Single Line Text for most variables or Masked for variables containing sensitive values Question The user visible question or label for the variable Name The internal name of the variable This must be derived from the name of the Terraform or environment variable Consult the table below to determine the proper prefix for each variable name Tooltip A tooltip to display for the variable Example Text Example text to show in the variable s input box 1 Under the Default Value tab you can set a default value for the variable 1 Continue to add new variables corresponding to the Terraform and environment variables the configuration requires When the Terraform integration applies configuration it will map ServiceNow variables to Terraform and environment variables using the following convention ServiceNow variables that begin with sensitive will be saved as sensitive variables within HCP Terraform ServiceNow Variable Name HCP Terraform Variable tf var VARIABLE NAME Terraform Variable VARIABLE NAME tf env ENV NAME Environment Variable ENV NAME sensitive tf var VARIABLE NAME Sensitive Terraform Variable Write Only VARIABLE NAME sensitive tf env ENV NAME Sensitive Environment Variable Write Only ENV NAME Provision Infrastructure Once you configure the Service Catalog for Terraform ServiceNow users can request infrastructure to be provisioned by HCP Terraform These requests will be fulfilled by HCP Terraform which will 1 Create a new workspace from the no code module or the VCS repository provided by ServiceNow 1 Configure variables for that workspace also provided by ServiceNow 1 Plan and apply the change 1 Report the results including any outputs from Terraform to ServiceNow Once this is complete ServiceNow will reflect that the Request Item has been provisioned Note The integration creates workspaces with auto apply terraform cloud docs workspaces settings auto apply and manual apply enabled HCP Terraform will queue an apply for these workspaces whenever changes are merged to the associated VCS repositories This is known as the VCS driven run workflow terraform cloud docs run ui It is important to keep in mind that all of the ServiceNow workspaces connected to a given repository will be updated whenever changes are merged to the associated branch in that repository Execution Mode If using v2 2 0 or above the Service Catalog app allows you to set an execution mode terraform cloud docs workspaces settings execution mode for your Terraform workspaces There are two modes to choose from The default value is Remote which instructs HCP Terraform to perform runs on its disposable virtual machines Selecting Agent mode allows you to run Terraform operations on isolated private or on premises infrastructure This option requires you to create an Agent Pool in your organization beforehand then provide that Agent Pool s id when you order a new workspace through the Service Catalog BEGIN TFC only name pnp callout include tfc package callouts agents mdx END TFC only name pnp callout Workspace Name Version 2 4 0 of the Service Catalog for Terraform introduces the ability to set custom names for your Terraform workspaces You can choose a prefix for your workspace name that the Service Catalog app will append the ServiceNow RITM number to If you do not define a workspace prefix ServiceNow will use RITM number as the workspace name Workspace names can include letters numbers dashes and underscores and should not exceed 90 characters Refer to the workspace naming recommendations terraform cloud docs workspaces create workspace naming for best practices Workspace Tags Version 2 4 0 also allows you to add custom tags to your Terraform workspaces Use the Workspace Tags field to provide a comma separated list of tags that will be parsed and attached to the workspace in HCP Terraform Tags give you an easier way to categorize filter and manage workspaces provisioned through the Service Catalog for Terraform We recommend that you set naming conventions for tags with your end users to avoid variations such as ec2 aws ec2 aws ec2 Workspace tags have a 255 character limit and can contain letters numbers colons hyphens and underscores Refer to the workspace tagging rules terraform cloud docs workspaces create workspace tags for more details
terraform The Terraform ServiceNow integration can be customized by ServiceNow developers Terraform ServiceNow Service Catalog Integration Developer Reference page title Developer Reference ServiceNow Service Catalog Integration HCP Terraform using the information found in this document Developer reference for the ServiceNow Service Catalog Integration
--- page_title: Developer Reference - ServiceNow Service Catalog Integration - HCP Terraform description: Developer reference for the ServiceNow Service Catalog Integration. --- # Terraform ServiceNow Service Catalog Integration Developer Reference The Terraform ServiceNow integration can be customized by ServiceNow developers using the information found in this document. ## Terraform Variables and ServiceNow Variable Sets ServiceNow has the concept of a Variable Set which is a collection of ServiceNow Variables that can be referenced in a Flow from a Service Catalog item. The Terraform Integration codebase can create [Terraform Variables and Terraform Environment Variables](/terraform/cloud-docs/workspaces/variables) via the API using the `tf_variable.createVariablesFromSet()` function. This function looks for variables following these conventions: | ServiceNow Variable Name | HCP Terraform Variable | | -------------------------------- | ---------------------------------------------------------- | | `tf_var_VARIABLE_NAME` | Terraform Variable: `VARIABLE_NAME` | | `tf_env_ENV_NAME` | Environment Variable: `ENV_NAME` | | `sensitive_tf_var_VARIABLE_NAME` | Sensitive Terraform Variable (Write Only): `VARIABLE_NAME` | | `sensitive_tf_env_ENV_NAME` | Sensitive Environment Variable (Write Only): `ENV_NAME` | This function takes the ServiceNow Variable Set and HCP Terraform workspace ID. It will loop through the given variable set collection and create any necessary Terraform variables or environment variables in the workspace. ## Customizing with ServiceNow "Script Includes" Libraries The Terraform/ServiceNow Integration codebase includes [ServiceNow Script Includes Classes](https://docs.servicenow.com/csh?topicname=c_ScriptIncludes.html&version=latest) that are used to interface with HCP Terraform. The codebase also includes example catalog items and flows that implement the interface to the HCP Terraform API. These classes and examples can be used to help create ServiceNow Catalog Items customized to your specific ServiceNow instance and requirements. ### Script Include Classes The ServiceNow Script Include Classes can be found in the ServiceNow Studio > Server Development > Script Include. | Class Name | Description | | --------------------- | ---------------------------------------------------------- | | `tf_config` | Helper to pull values from the SN Terraform Configs Table | | `tf_get_workspace` | Client-callable script to retrieve workspace data | | `tf_http` | ServiceNow HTTP REST wrapper for requests to the Terraform API | | `tf_no_code_workspace`| Resources for Terraform no-code module API requests | | `tf_run` | Resources for Terraform run API requests | | `tf_terraform_record` | Manage ServiceNow Terraform Table Records | | `tf_test_config` | Client-callable script to test Terraform connectivity | | `tf_util` | Miscellaneous helper functions | | `tf_variable` | Resources for Terraform variable API Requests | | `tf_vcs_record` | Manage ServiceNow Terraform VCS repositories table records | | `tf_workspace` | Resources for Terraform workspace API requests | ### Example Service Catalog Flows and Actions The ServiceNow Service Catalog for Terraform provides sample catalog items that use **Flows** and **Workflows** as their primary process engines. **Flows** are a newer solution developed by ServiceNow and are generally preferred over **Workflows**. To see which engine an item is using, open it in the edit mode and navigate to the **Process Engine** tab. For example, **Create Workspace** uses a **Workflow**, whereas **Create Workspace Flow** is built upon a **Flow**. You can access both in the **Studio**. You can also manage **Flows** in the **Flow Designer**. To manage **Workflows**, navigate to **All > Workflow Editor**. You can find the ServiceNow Example Flows for Terraform in the **ServiceNow Studio > Flows** (or **All > Flow Designer**). Search for items that belong to the **Terraform** application. By default, Flows execute when someone submits an order request for a catalog item based on a Flow. Admins can customize the Flows and Actions to add approval flows, set approval rules based on certain conditions, and configure multiple users or roles as approvers for specific catalog items. | Flow Name | Description | | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Create Workspace | Creates a new HCP Terraform workspace from VCS repository. | | Create Workspace with Vars | Creates a new HCP Terraform workspace from VCS repository and creates any variables provided. | | Create Run | Creates and queues a new run in the HCP Terraform workspace. | | Apply Run | Applies a run in the HCP Terraform workspace. | | Provision Resources | Creates a new HCP Terraform workspace (with auto-apply), creates and queues a run, then applies the run when ready. | | Provision Resources with Vars | Creates a new HCP Terraform workspace (with auto-apply), creates any variables, creates/queues a run, applies the run when ready. | Provision No-Code Workspace and Deploy Resources | Creates a new HCP Terraform workspace based on a no-code module configured in the private registry (with auto-apply), creates any variables, creates and queues a run, then applies the run when ready. | | Delete Workspace | Creates a destroy run plan. | | Worker Poll Run State | Polls the HCP Terraform API for the current run state of a workspace. | | Worker Poll Apply Run | Polls the HCP Terraform API and applies any pending Terraform runs. | | Worker Poll Destroy Workspace | Queries ServiceNow Terraform Records for resources marked `is_destroyable`, applies the destroy run to destroy resources, and deletes the corresponding Terraform workspace. | | Update No-Code Workspace and Deploy Resources | Updates an existing no-code workspace to the most recent no-code module version, updates that workspace's attached variable values, and then starts a new Terraform run. | Update Workspace | Updates HCP Terraform workspace configurations, such as VCS repository, description, project, execution mode, and agent pool ID (if applicable). | | Update Workspace with Vars | Allows you to change details about the HCP Terraform workspace configurations and attached variable values. | | Update Resources | Updates HCP Terraform workspace details and starts a new Terraform run with these new values. | | Update Resources with Vars | Updates your existing HCP Terraform workspace and its variables, then starts a Terraform run with these updated values. | ## ServiceNow ACLs Access control lists (ACLs) restrict user access to objects and operations based on permissions granted. This integration includes the following roles that can be used to manage various components. | Access Control Roles | Description | | :---------------------------------- | ----------------------------------------------------------------------------------------------- | | `x_terraform.config_user` | Can manage the connection from the ServiceNow application to your HCP Terraform organization. | | `x_terraform.terraform_user` | Can manage all of the Terraform resources created in ServiceNow. | | `x_terraform.vcs_repositories_user` | Can manage the VCS repositories available for catalog items to be ordered by end-users. | For users who only need to order from the Terraform Catalog, we recommend creating another role with read-only permissions for `x_terraform_vcs_repositories` to view the available repositories for ordering infrastructure. Install the Terraform ServiceNow Service Catalog integration by following [the installation guide](/terraform/cloud-docs/integrations/service-now/service-catalog-terraform).
terraform
page title Developer Reference ServiceNow Service Catalog Integration HCP Terraform description Developer reference for the ServiceNow Service Catalog Integration Terraform ServiceNow Service Catalog Integration Developer Reference The Terraform ServiceNow integration can be customized by ServiceNow developers using the information found in this document Terraform Variables and ServiceNow Variable Sets ServiceNow has the concept of a Variable Set which is a collection of ServiceNow Variables that can be referenced in a Flow from a Service Catalog item The Terraform Integration codebase can create Terraform Variables and Terraform Environment Variables terraform cloud docs workspaces variables via the API using the tf variable createVariablesFromSet function This function looks for variables following these conventions ServiceNow Variable Name HCP Terraform Variable tf var VARIABLE NAME Terraform Variable VARIABLE NAME tf env ENV NAME Environment Variable ENV NAME sensitive tf var VARIABLE NAME Sensitive Terraform Variable Write Only VARIABLE NAME sensitive tf env ENV NAME Sensitive Environment Variable Write Only ENV NAME This function takes the ServiceNow Variable Set and HCP Terraform workspace ID It will loop through the given variable set collection and create any necessary Terraform variables or environment variables in the workspace Customizing with ServiceNow Script Includes Libraries The Terraform ServiceNow Integration codebase includes ServiceNow Script Includes Classes https docs servicenow com csh topicname c ScriptIncludes html version latest that are used to interface with HCP Terraform The codebase also includes example catalog items and flows that implement the interface to the HCP Terraform API These classes and examples can be used to help create ServiceNow Catalog Items customized to your specific ServiceNow instance and requirements Script Include Classes The ServiceNow Script Include Classes can be found in the ServiceNow Studio Server Development Script Include Class Name Description tf config Helper to pull values from the SN Terraform Configs Table tf get workspace Client callable script to retrieve workspace data tf http ServiceNow HTTP REST wrapper for requests to the Terraform API tf no code workspace Resources for Terraform no code module API requests tf run Resources for Terraform run API requests tf terraform record Manage ServiceNow Terraform Table Records tf test config Client callable script to test Terraform connectivity tf util Miscellaneous helper functions tf variable Resources for Terraform variable API Requests tf vcs record Manage ServiceNow Terraform VCS repositories table records tf workspace Resources for Terraform workspace API requests Example Service Catalog Flows and Actions The ServiceNow Service Catalog for Terraform provides sample catalog items that use Flows and Workflows as their primary process engines Flows are a newer solution developed by ServiceNow and are generally preferred over Workflows To see which engine an item is using open it in the edit mode and navigate to the Process Engine tab For example Create Workspace uses a Workflow whereas Create Workspace Flow is built upon a Flow You can access both in the Studio You can also manage Flows in the Flow Designer To manage Workflows navigate to All Workflow Editor You can find the ServiceNow Example Flows for Terraform in the ServiceNow Studio Flows or All Flow Designer Search for items that belong to the Terraform application By default Flows execute when someone submits an order request for a catalog item based on a Flow Admins can customize the Flows and Actions to add approval flows set approval rules based on certain conditions and configure multiple users or roles as approvers for specific catalog items Flow Name Description Create Workspace Creates a new HCP Terraform workspace from VCS repository Create Workspace with Vars Creates a new HCP Terraform workspace from VCS repository and creates any variables provided Create Run Creates and queues a new run in the HCP Terraform workspace Apply Run Applies a run in the HCP Terraform workspace Provision Resources Creates a new HCP Terraform workspace with auto apply creates and queues a run then applies the run when ready Provision Resources with Vars Creates a new HCP Terraform workspace with auto apply creates any variables creates queues a run applies the run when ready Provision No Code Workspace and Deploy Resources Creates a new HCP Terraform workspace based on a no code module configured in the private registry with auto apply creates any variables creates and queues a run then applies the run when ready Delete Workspace Creates a destroy run plan Worker Poll Run State Polls the HCP Terraform API for the current run state of a workspace Worker Poll Apply Run Polls the HCP Terraform API and applies any pending Terraform runs Worker Poll Destroy Workspace Queries ServiceNow Terraform Records for resources marked is destroyable applies the destroy run to destroy resources and deletes the corresponding Terraform workspace Update No Code Workspace and Deploy Resources Updates an existing no code workspace to the most recent no code module version updates that workspace s attached variable values and then starts a new Terraform run Update Workspace Updates HCP Terraform workspace configurations such as VCS repository description project execution mode and agent pool ID if applicable Update Workspace with Vars Allows you to change details about the HCP Terraform workspace configurations and attached variable values Update Resources Updates HCP Terraform workspace details and starts a new Terraform run with these new values Update Resources with Vars Updates your existing HCP Terraform workspace and its variables then starts a Terraform run with these updated values ServiceNow ACLs Access control lists ACLs restrict user access to objects and operations based on permissions granted This integration includes the following roles that can be used to manage various components Access Control Roles Description x terraform config user Can manage the connection from the ServiceNow application to your HCP Terraform organization x terraform terraform user Can manage all of the Terraform resources created in ServiceNow x terraform vcs repositories user Can manage the VCS repositories available for catalog items to be ordered by end users For users who only need to order from the Terraform Catalog we recommend creating another role with read only permissions for x terraform vcs repositories to view the available repositories for ordering infrastructure Install the Terraform ServiceNow Service Catalog integration by following the installation guide terraform cloud docs integrations service now service catalog terraform
terraform page title HCP Terraform Run Tasks Integrations Setup Run Tasks Integration Run tasks allow HCP Terraform to execute tasks in external systems at In addition to using existing technology partners integrations HashiCorp HCP Terraform customers can build their own custom run task integrations Custom integrations have access to plan details in between the plan and apply phase and can display custom messages within the run pipeline as well as prevent a run from continuing to the apply phase specific points in the HCP Terraform run lifecycle
--- page_title: HCP Terraform Run Tasks Integrations Setup description: >- Run tasks allow HCP Terraform to execute tasks in external systems at specific points in the HCP Terraform run lifecycle. --- # Run Tasks Integration In addition to using existing technology partners integrations, HashiCorp HCP Terraform customers can build their own custom run task integrations. Custom integrations have access to plan details in between the plan and apply phase, and can display custom messages within the run pipeline as well as prevent a run from continuing to the apply phase. <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/run-tasks.mdx' <!-- END: TFC:only name:pnp-callout --> ## Prerequisites To build a custom integration, you must have a server capable of receiving requests from HCP Terraform and responding with a status update to a supplied callback URL. When creating a run task, you supply an endpoint url to receive the hook. We send a test POST to the supplied URL, and it must respond with a 200 for the run task to be created. This feature relies heavily on the proper parsing of [plan JSON output](/terraform/internals/json-format). When sending this output to an external system, be certain that system can properly interpret the information provided. ## Available Run Tasks You can view the most up-to-date list of run tasks in the [Terraform Registry](https://registry.terraform.io/browse/run-tasks). ## Integration Details When a run reaches the appropriate phase and a run task is triggered, the supplied URL will receive details about the run in a payload similar to the one below. The server receiving the run task should respond `200 OK`, or Terraform will retry to trigger the run task. Refer to the [Run Task Integration API](/terraform/cloud-docs/api-docs/run-tasks/run-tasks-integration) for the exact payload specification. ```json { "payload_version": 1, "stage": "post_plan", "access_token": "4QEuyyxug1f2rw.atlasv1.iDyxqhXGVZ0ykes53YdQyHyYtFOrdAWNBxcVUgWvzb64NFHjcquu8gJMEdUwoSLRu4Q", "capabilities": { "outcomes": true }, "configuration_version_download_url": "https://app.terraform.io/api/v2/configuration-versions/cv-ntv3HbhJqvFzamy7/download", "configuration_version_id": "cv-ntv3HbhJqvFzamy7", "is_speculative": false, "organization_name": "hashicorp", "plan_json_api_url": "https://app.terraform.io/api/v2/plans/plan-6AFmRJW1PFJ7qbAh/json-output", "run_app_url": "https://app.terraform.io/app/hashicorp/my-workspace/runs/run-i3Df5to9ELvibKpQ", "run_created_at": "2021-09-02T14:47:13.036Z", "run_created_by": "username", "run_id": "run-i3Df5to9ELvibKpQ", "run_message": "Triggered via UI", "task_result_callback_url": "https://app.terraform.io/api/v2/task-results/5ea8d46c-2ceb-42cd-83f2-82e54697bddd/callback", "task_result_enforcement_level": "mandatory", "task_result_id": "taskrs-2nH5dncYoXaMVQmJ", "vcs_branch": "main", "vcs_commit_url": "https://github.com/hashicorp/terraform-random/commit/7d8fb2a2d601edebdb7a59ad2088a96673637d22", "vcs_pull_request_url": null, "vcs_repo_url": "https://github.com/hashicorp/terraform-random", "workspace_app_url": "https://app.terraform.io/app/hashicorp/my-workspace", "workspace_id": "ws-ck4G5bb1Yei5szRh", "workspace_name": "tfr_github_0", "workspace_working_directory": "/terraform" } ``` Once your server receives this payload, HCP Terraform expects you to callback to the supplied `task_result_callback_url` using the `access_token` as an [Authentication Header](/terraform/cloud-docs/api-docs#authentication) with a [jsonapi](/terraform/cloud-docs/api-docs#json-api-formatting) payload of the form: ```json { "data": { "type": "task-results", "attributes": { "status": "running", "message": "Hello task", "url": "https://example.com", "outcomes": [...] } } } ``` HCP Terraform expects this callback within 10 minutes, or the task will be considered to have `errored`. The supplied message attribute will be displayed in HCP Terraform on the run details page. The status can be `running`, `passed` or `failed`. Here's what the data flow looks like: ![Screenshot: a diagram of the user and data flow for an HCP Terraform run task](/img/docs/terraform-cloud-run-tasks-diagram.png) Refer to the [run task integration API](/terraform/cloud-docs/api-docs/run-tasks/run-tasks-integration#structured-results) for the exact payload specifications, and the [run task JSON schema](https://github.com/hashicorp/terraform-docs-common/blob/main/website/public/schema/run-tasks/runtask-result.json) for code generation and payload validation. ## Securing your Run Task When creating your run task, you can supply an HMAC key which HCP Terraform will use to create a signature of the payload in the `X-Tfc-Task-Signature` header when calling your service. The signature is a sha512 sum of the webhook body using the provided HMAC key. The generation of the signature depends on your implementation, however an example of how to generate a signature in bash is provided below. ```bash $ echo -n $WEBHOOK_BODY | openssl dgst -sha512 -hmac "$HMAC_KEY" ``` ## HCP Packer Run Task > **Hands On:** Try the [Set Up HCP Terraform Run Task for HCP Packer](/packer/tutorials/hcp/setup-hcp-terraform-run-task), [Standard tier run task image validation](/packer/tutorials/hcp/run-tasks-data-source-image-validation), and [Plus tier run task image validation](/packer/tutorials/hcp/run-tasks-resource-image-validation) tutorials to set up and test the HCP Terraform Run Task integration end to end. [Packer](https://www.packer.io/) lets you create identical machine images for multiple platforms from a single source template. The [HCP Packer registry](/hcp/docs/packer) lets you track golden images, designate images for test and production environments, and query images to use in Packer and Terraform configurations. The HCP Packer validation run task checks the image artifacts within a Terraform configuration. If the configuration references images marked as unusable (revoked), the run task fails and provides an error message containing the number of revoked artifacts and whether HCP Packer has metadata for newer versions. For HCP Packer Plus registries, run tasks also help you identify hardcoded and untracked images that may not meet security and compliance requirements. To get started, [create an HCP Packer account](https://cloud.hashicorp.com/products/packer) and follow the instructions in the [HCP Packer Run Task](/hcp/docs/packer/manage-image-use/terraform-cloud-run-tasks) documentation.
terraform
page title HCP Terraform Run Tasks Integrations Setup description Run tasks allow HCP Terraform to execute tasks in external systems at specific points in the HCP Terraform run lifecycle Run Tasks Integration In addition to using existing technology partners integrations HashiCorp HCP Terraform customers can build their own custom run task integrations Custom integrations have access to plan details in between the plan and apply phase and can display custom messages within the run pipeline as well as prevent a run from continuing to the apply phase BEGIN TFC only name pnp callout include tfc package callouts run tasks mdx END TFC only name pnp callout Prerequisites To build a custom integration you must have a server capable of receiving requests from HCP Terraform and responding with a status update to a supplied callback URL When creating a run task you supply an endpoint url to receive the hook We send a test POST to the supplied URL and it must respond with a 200 for the run task to be created This feature relies heavily on the proper parsing of plan JSON output terraform internals json format When sending this output to an external system be certain that system can properly interpret the information provided Available Run Tasks You can view the most up to date list of run tasks in the Terraform Registry https registry terraform io browse run tasks Integration Details When a run reaches the appropriate phase and a run task is triggered the supplied URL will receive details about the run in a payload similar to the one below The server receiving the run task should respond 200 OK or Terraform will retry to trigger the run task Refer to the Run Task Integration API terraform cloud docs api docs run tasks run tasks integration for the exact payload specification json payload version 1 stage post plan access token 4QEuyyxug1f2rw atlasv1 iDyxqhXGVZ0ykes53YdQyHyYtFOrdAWNBxcVUgWvzb64NFHjcquu8gJMEdUwoSLRu4Q capabilities outcomes true configuration version download url https app terraform io api v2 configuration versions cv ntv3HbhJqvFzamy7 download configuration version id cv ntv3HbhJqvFzamy7 is speculative false organization name hashicorp plan json api url https app terraform io api v2 plans plan 6AFmRJW1PFJ7qbAh json output run app url https app terraform io app hashicorp my workspace runs run i3Df5to9ELvibKpQ run created at 2021 09 02T14 47 13 036Z run created by username run id run i3Df5to9ELvibKpQ run message Triggered via UI task result callback url https app terraform io api v2 task results 5ea8d46c 2ceb 42cd 83f2 82e54697bddd callback task result enforcement level mandatory task result id taskrs 2nH5dncYoXaMVQmJ vcs branch main vcs commit url https github com hashicorp terraform random commit 7d8fb2a2d601edebdb7a59ad2088a96673637d22 vcs pull request url null vcs repo url https github com hashicorp terraform random workspace app url https app terraform io app hashicorp my workspace workspace id ws ck4G5bb1Yei5szRh workspace name tfr github 0 workspace working directory terraform Once your server receives this payload HCP Terraform expects you to callback to the supplied task result callback url using the access token as an Authentication Header terraform cloud docs api docs authentication with a jsonapi terraform cloud docs api docs json api formatting payload of the form json data type task results attributes status running message Hello task url https example com outcomes HCP Terraform expects this callback within 10 minutes or the task will be considered to have errored The supplied message attribute will be displayed in HCP Terraform on the run details page The status can be running passed or failed Here s what the data flow looks like Screenshot a diagram of the user and data flow for an HCP Terraform run task img docs terraform cloud run tasks diagram png Refer to the run task integration API terraform cloud docs api docs run tasks run tasks integration structured results for the exact payload specifications and the run task JSON schema https github com hashicorp terraform docs common blob main website public schema run tasks runtask result json for code generation and payload validation Securing your Run Task When creating your run task you can supply an HMAC key which HCP Terraform will use to create a signature of the payload in the X Tfc Task Signature header when calling your service The signature is a sha512 sum of the webhook body using the provided HMAC key The generation of the signature depends on your implementation however an example of how to generate a signature in bash is provided below bash echo n WEBHOOK BODY openssl dgst sha512 hmac HMAC KEY HCP Packer Run Task Hands On Try the Set Up HCP Terraform Run Task for HCP Packer packer tutorials hcp setup hcp terraform run task Standard tier run task image validation packer tutorials hcp run tasks data source image validation and Plus tier run task image validation packer tutorials hcp run tasks resource image validation tutorials to set up and test the HCP Terraform Run Task integration end to end Packer https www packer io lets you create identical machine images for multiple platforms from a single source template The HCP Packer registry hcp docs packer lets you track golden images designate images for test and production environments and query images to use in Packer and Terraform configurations The HCP Packer validation run task checks the image artifacts within a Terraform configuration If the configuration references images marked as unusable revoked the run task fails and provides an error message containing the number of revoked artifacts and whether HCP Packer has metadata for newer versions For HCP Packer Plus registries run tasks also help you identify hardcoded and untracked images that may not meet security and compliance requirements To get started create an HCP Packer account https cloud hashicorp com products packer and follow the instructions in the HCP Packer Run Task hcp docs packer manage image use terraform cloud run tasks documentation
terraform Warning Version 1 of the HCP Terraform Operator for Kubernetes is deprecated and no longer maintained If you are installing the operator for the first time refer to Set up the HCP Terraform Operator for Kubernetes terraform cloud docs integrations kubernetes setup for guidance HCP Terraform Operator for Kubernetes v2 Migration Guide Upgrade the Terraform Kubernetes Operator from version 1 to version 2 page title HCP Terraform Operator for Kubernetes v2 Migration Guide
--- page_title: HCP Terraform Operator for Kubernetes v2 Migration Guide description: >- Upgrade the Terraform Kubernetes Operator from version 1 to version 2. --- # HCP Terraform Operator for Kubernetes v2 Migration Guide ~> **Warning**: Version 1 of the HCP Terraform Operator for Kubernetes is **deprecated** and no longer maintained. If you are installing the operator for the first time, refer to [Set up the HCP Terraform Operator for Kubernetes](/terraform/cloud-docs/integrations/kubernetes/setup) for guidance. To upgrade the HCP Terraform Operator for Kubernetes from version 1 to the HCP Terraform Operator for Kubernetes (version 2), there is a one-time process that you need to complete. This process upgrades the operator to the newest version and migrate your custom resources. ## Prerequisites The migration process requires the following tools to be installed locally: - [kubectl](https://kubernetes.io/docs/tasks/tools/#kubectl) - [Helm](https://helm.sh/docs/intro/install/) ## Prepare for the upgrade Configure an environment variable named `RELEASE_NAMESPACE` with the value of the namespace that the Helm chart is installed in. ```shell-session $ export RELEASE_NAMESPACE=<NAMESPACE> ``` Next, create an environment variable named `RELEASE_NAME` with the value of the name that you gave your installation for the Helm chart. ```shell-session $ export RELEASE_NAME=<INSTALLATION_NAME> ``` Before you migrate to HCP Terraform Operator for Kubernetes v2, you must first update v1 of the operator to the latest version, including the custom resource definitions. ```shell-session $ helm upgrade --namespace ${RELEASE_NAMESPACE} ${RELEASE_NAME} hashicorp/terraform ``` Next, backup the workspace resources. ```shell-session $ kubectl get workspace --all-namespaces -o yaml > backup_tfc_operator_v1.yaml ``` ## Manifest schema migration Version 2 of the HCP Terraform Operator for Kubernetes renames and moves many existing fields. When you migrate, you must update your specification to match version 2's field names. ### Workspace controller The table below lists the field mapping of the `Workspace` controller between v1 and v2 of the operator. | Version 1 | Version 2 | Changes between versions | | --- | --- | --- | | `apiVersion: app.terraform.io/v1alpha1` | `apiVersion: app.terraform.io/v1alpha2` | The `apiVersion` is now `v1alpha2`. | | `kind: Workspace` | `kind: Workspace` | None. | | `metadata` | `metadata` | None. | | `spec.organization` | `spec.organization` | None. | | `spec.secretsMountPath` | `spec.token.secretKeyRef` | In v2 the operator keeps the HCP Terraform access token in a Kubernetes Secret. | | `spec.vcs` | `spec.versionControl` | Renamed the `vcs` field to `versionControl`. | | `spec.vcs.token_id` | `spec.versionControl.oAuthTokenID` | Renamed the `token_id` field to `oAuthTokenID`. | | `spec.vcs.repo_identifier` | `spec.versionControl.repository` | Renamed the `repo_identifier` field to `repository`. | | `spec.vcs.branch` | `spec.versionControl.branch` | None. | | `spec.vcs.ingress_submodules` | `spec.workingDirectory` | Moved. | | `spec.variables.[*]` | `spec.environmentVariables.[*]` OR `spec.terraformVariables.[*]` | <a id="workspace-variables"></a>We split variables into two possible places. In v1's CRD, if `spec.variables.environmentVariable` was `true`, migrate those variables to `spec.environmentVariables`. If `false`, migrate those variables to `spec.terraformVariables`. | | `spec.variables.[*]key` | `spec.environmentVariables.[*]name` OR `spec.terraformVariables.[*]name` | Renamed the `key` field as `name`. [Learn more](#workspace-variables).| | `spec.variables.[*]value` | `spec.environmentVariables.[*]value` OR `spec.terraformVariables.[*]value` | [Learn more](#workspace-variables). | | `spec.variables.[*]valueFrom` | `spec.environmentVariables.[*]valueFrom` OR `spec.terraformVariables.[*]valueFrom` | [Learn more](#workspace-variables). | | `spec.variables.[*]hcl` | `spec.environmentVariables.[*]hcl` OR `spec.terraformVariables.[*]hcl` | [Learn more](#workspace-variables). | | `spec.variables.sensitive` | `spec.environmentVariables.[*]sensitive` OR `spec.terraformVariables.[*]sensitive` | [Learn more](#workspace-variables). | | `spec.variables.environmentVariable` | N/A | Removed, variables are split between `spec.environmentVariables` and `spec.terraformVariables`. | | `spec.runTriggers.[*]` | `spec.runTriggers.[*]` | None. | | `spec.runTriggers.[*].sourceableName` | `spec.runTriggers.[*].name` | The `sourceableName` field is now `name`. | | `spec.sshKeyID` | `spec.sshKey.id` | Moved the `sshKeyID` to `spec.sshKey.id`. | | `spec.outputs` | N/A | Removed. | | `spec.terraformVersion` | `spec.terraformVersion` | None. | | `spec.notifications.[*]` | `spec.notifications.[*]` | None. | | `spec.notifications.[*].type` | `spec.notifications.[*].type` | None. | | `spec.notifications.[*].enabled` | `spec.notifications.[*].enabled` | None. | | `spec.notifications.[*].name` | `spec.notifications.[*].name` | None. | | `spec.notifications.[*].url` | `spec.notifications.[*].url` | None. | | `spec.notifications.[*].token` | `spec.notifications.[*].token` | None. | | `spec.notifications.[*].triggers.[*]` | `spec.notifications.[*].triggers.[*]` | None. | | `spec.notifications.[*].recipients.[*]` | `spec.notifications.[*].emailAddresses.[*]` | Renamed the `recipients` field to `emailAddresses`. | | `spec.notifications.[*].users.[*]` | `spec.notifications.[*].emailUsers.[*]` | Renamed the `users` field to `emailUsers`. | | `spec.omitNamespacePrefix` | N/A | Removed. In v1 `spec.omitNamespacePrefix` is a boolean field that affects how the operator generates a workspace name. In v2, you must explicitly set workspace names in `spec.name`. | | `spec.agentPoolID` | `spec.agentPool.id` | Moved the `agentPoolID` field to `spec.agentPool.id`. | | `spec.agentPoolName` | `spec.agentPool.name` | Moved the `agentPoolName` field to `spec.agentPool.name`. | | `spec.module` | N/A | Removed. You now configure modules with a separate `Module` CRD. [Learn more](#module-controller). | Below is an example of configuring a variable in v1 of the operator. <CodeBlockConfig filename="v1.yaml"> ```yaml apiVersion: app.terraform.io/v1alpha1 kind: Workspace metadata: name: migration spec: variables: - key: username value: "user" hcl: true sensitive: false environmentVariable: false - key: SECRET_KEY value: "s3cr3t" hcl: false sensitive: false environmentVariable: true ``` </CodeBlockConfig> In v2 of the operator, you must configure Terraform variables in `spec.terraformVariables` and environment variables `spec.environmentVariables`. <CodeBlockConfig filename="v2.yaml"> ```yaml apiVersion: app.terraform.io/v1alpha2 kind: Workspace metadata: name: migration spec: terraformVariables: - name: username value: "user" hcl: true sensitive: false environmentVariables: - name: SECRET_KEY value: "s3cr3t" hcl: false sensitive: false ``` </CodeBlockConfig> ### Module controller HCP Terraform Operator for Kubernetes v2 configures modules in a new `Module` controller separate from the `Workspace` controller. Below is a template of a custom resource manifest: ```yaml apiVersion: app.terraform.io/v1alpha2 kind: Module metadata: name: <NAME> spec: organization: <ORG-NAME> token: secretKeyRef: name: <SECRET-NAME> key: <KEY-NAME> name: operator ``` The table below describes the mapping between the `Workspace` controller from v1 and the `Module` controller in v2 of the operator. | Version 1 (Workspace CRD) | Version 2 (Module CRD) | Notes | | --- | --- | --- | | `spec.module` | N/A | In v2 of the operator a `Module` is a separate controller with its own CRD. | | N/A | `spec.name: operator` | In v1 of the operator, the name of the generated module is hardcoded to `operator`. In v2, the default name of the generated module is `this`, but you can rename it. | | `spec.module.source` | `spec.module.source` | This supports all Terraform [module sources](/terraform/language/modules/sources). | | `spec.module.version` | `spec.module.version` | Refer to [module sources](/terraform/language/modules/sources) for versioning information for each module source. | | `spec.variables.[*]` | `spec.variables.[*].name` | You should include variable names in the module. This is a reference to variables in the workspace that is executing the module. | | `spec.outputs.[*].key` | `spec.outputs.[*].name` | You should include output names in the module. This is a reference to the output variables produced by the module. | | `status.workspaceID` OR `metadata.namespace-metadata.name` | `spec.workspace.id` OR `spec.workspace.name` | The workspace where the module is executed. The workspace must be in the same organization. | Below is an example migration of a `Module` between v1 and v2 of the operator: <CodeBlockConfig filename="v1.yaml"> ```yaml apiVersion: app.terraform.io/v1alpha1 kind: Workspace metadata: name: migration spec: module: source: app.terraform.io/org-name/module-name/provider version: 0.0.42 variables: - key: username value: "user" hcl: true sensitive: false environmentVariable: false - key: SECRET_KEY value: "s3cr3t" hcl: false sensitive: false environmentVariable: true ``` </CodeBlockConfig> In v2 of the operator, separate controllers manage workspace and modules. <CodeBlockConfig filename="workspace-v2.yaml"> ```yaml apiVersion: app.terraform.io/v1alpha2 kind: Workspace metadata: name: migration spec: terraformVariables: - name: username value: "user" hcl: true sensitive: false environmentVariables: - name: SECRET_KEY value: "s3cr3t" hcl: false sensitive: false ``` </CodeBlockConfig> <CodeBlockConfig filename="module-v2.yaml"> ```yaml apiVersion: app.terraform.io/v1alpha2 kind: Module metadata: name: migration spec: name: operator module: source: app.terraform.io/org-name/module-name/provider version: 0.0.42 workspace: name: migration ``` </CodeBlockConfig> ## Upgrade the operator Download Workspace CRD patch A: ```shell-session $ curl -sO https://raw.githubusercontent.com/hashicorp/hcp-terraform-operator/main/docs/migration/crds/workspaces_patch_a.yaml ``` View the changes that patch A applies to the workspace CRD. ```shell-session $ kubectl diff --filename workspaces_patch_a.yaml ``` Patch the workspace CRD with patch A. This patch adds `app.terraform.io/v1alpha2` support, but excludes `.status.runStatus` because it has a different format in `app.terraform.io/v1alpha1` and causes JSON un-marshalling issues. !> **Upgrade warning**: Once you apply a patch, Kubernetes converts existing `app.terraform.io/v1alpha1` custom resources to `app.terraform.io/v1alpha2` according to the updated schema, meaning that v1 of the operator can no longer serve custom resources. Before patching, update your existing custom resources to satisfy the v2 schema requirements. [Learn more](#manifest-schema-migration). ```shell-session $ kubectl patch crd workspaces.app.terraform.io --patch-file workspaces_patch_a.yaml ``` Install the Operator v2 Helm chart with the `helm install` command. Be sure to set the `operator.watchedNamespaces` value to the list of namespaces your Workspace resources are deployed to. If this value is not provided, the operator will watch all namespaces in the Kubernetes cluster. ```shell-session $ helm install \ ${RELEASE_NAME} hashicorp/hcp-terraform-operator \ --version 2.4.0 \ --namespace ${RELEASE_NAMESPACE} \ --set 'operator.watchedNamespaces={white,blue,red}' \ --set controllers.agentPool.workers=5 \ --set controllers.module.workers=5 \ --set controllers.workspace.workers=5 ``` Next, create a Kubernetes secret to store the HCP Terraform API token following the [Usage Guide](https://github.com/hashicorp/hcp-terraform-operator/blob/main/docs/usage.md#prerequisites). The API token can be copied from the Kubernetes secret that you created for v1 of the operator. By default, this is named `terraformrc`. Use the `kubectl get secret` command to get the API token. ```shell-session $ kubectl --namespace ${RELEASE_NAMESPACE} get secret terraformrc -o json | jq '.data.credentials' | tr -d '"' | base64 -d ``` Update existing custom resources [according to the schema migration guidance](#manifest-schema-migration) and apply your changes. ```shell-session $ kubectl apply --filename <UPDATED_V2_WORKSPACE_MANIFEST.yaml> ``` Download Workspace CRD patch B. ```shell-session $ curl -sO https://raw.githubusercontent.com/hashicorp/hcp-terraform-operator/main/docs/migration/crds/workspaces_patch_b.yaml ``` View the changes that patch B applies to the workspace CRD. ```shell-session $ kubectl diff --filename workspaces_patch_b.yaml ``` Patch the workspace CRD with patch B. This patch adds `.status.runStatus` support, which was excluded in patch A. ```shell-session $ kubectl patch crd workspaces.app.terraform.io --patch-file workspaces_patch_b.yaml ``` The v2 operator will fail to proceed if a custom resource has the v1 finalizer `finalizer.workspace.app.terraform.io`. If you encounter an error, check the logs for more information. ```shell-session $ kubectl logs -f <POD_NAME> ``` Specifically, look for an error message such as the following. ``` ERROR Migration {"workspace": "default/<WORKSPACE_NAME>", "msg": "spec contains old finalizer finalizer.workspace.app.terraform.io"} ``` The `finalizer` exists to provide greater control over the migration process. Verify the custom resource, and when you’re ready to migrate it, use the `kubectl patch` command to update the `finalizer` value. ```shell-session $ kubectl patch workspace migration --type=merge --patch '{"metadata": {"finalizers": ["workspace.app.terraform.io/finalizer"]}}' ``` Review the operator logs once more and verify there are no error messages. ```shell-session $ kubectl logs -f <POD_NAME> ``` The operator reconciles resources during the next sync period. This interval is set by the `operator.syncPeriod` configuration of the operator and defaults to five minutes. If you have any migrated `Module` custom resources, apply them now. ```shell-session $ kubectl apply --filename <MIGRATED_V2_MODULE_MANIFEST.yaml> ``` In v2 of the operator, the `applyMethod` is set to `manual` by default. In this case, a new run in a managed workspace requires manual approval. Run the following command for each `Workspace` resource to change it to `auto` approval. ```shell-session $ kubectl patch workspace <WORKSPACE_NAME> --type=merge --patch '{"spec": {"applyMethod": "auto"}}' ```
terraform
page title HCP Terraform Operator for Kubernetes v2 Migration Guide description Upgrade the Terraform Kubernetes Operator from version 1 to version 2 HCP Terraform Operator for Kubernetes v2 Migration Guide Warning Version 1 of the HCP Terraform Operator for Kubernetes is deprecated and no longer maintained If you are installing the operator for the first time refer to Set up the HCP Terraform Operator for Kubernetes terraform cloud docs integrations kubernetes setup for guidance To upgrade the HCP Terraform Operator for Kubernetes from version 1 to the HCP Terraform Operator for Kubernetes version 2 there is a one time process that you need to complete This process upgrades the operator to the newest version and migrate your custom resources Prerequisites The migration process requires the following tools to be installed locally kubectl https kubernetes io docs tasks tools kubectl Helm https helm sh docs intro install Prepare for the upgrade Configure an environment variable named RELEASE NAMESPACE with the value of the namespace that the Helm chart is installed in shell session export RELEASE NAMESPACE NAMESPACE Next create an environment variable named RELEASE NAME with the value of the name that you gave your installation for the Helm chart shell session export RELEASE NAME INSTALLATION NAME Before you migrate to HCP Terraform Operator for Kubernetes v2 you must first update v1 of the operator to the latest version including the custom resource definitions shell session helm upgrade namespace RELEASE NAMESPACE RELEASE NAME hashicorp terraform Next backup the workspace resources shell session kubectl get workspace all namespaces o yaml backup tfc operator v1 yaml Manifest schema migration Version 2 of the HCP Terraform Operator for Kubernetes renames and moves many existing fields When you migrate you must update your specification to match version 2 s field names Workspace controller The table below lists the field mapping of the Workspace controller between v1 and v2 of the operator Version 1 Version 2 Changes between versions apiVersion app terraform io v1alpha1 apiVersion app terraform io v1alpha2 The apiVersion is now v1alpha2 kind Workspace kind Workspace None metadata metadata None spec organization spec organization None spec secretsMountPath spec token secretKeyRef In v2 the operator keeps the HCP Terraform access token in a Kubernetes Secret spec vcs spec versionControl Renamed the vcs field to versionControl spec vcs token id spec versionControl oAuthTokenID Renamed the token id field to oAuthTokenID spec vcs repo identifier spec versionControl repository Renamed the repo identifier field to repository spec vcs branch spec versionControl branch None spec vcs ingress submodules spec workingDirectory Moved spec variables spec environmentVariables OR spec terraformVariables a id workspace variables a We split variables into two possible places In v1 s CRD if spec variables environmentVariable was true migrate those variables to spec environmentVariables If false migrate those variables to spec terraformVariables spec variables key spec environmentVariables name OR spec terraformVariables name Renamed the key field as name Learn more workspace variables spec variables value spec environmentVariables value OR spec terraformVariables value Learn more workspace variables spec variables valueFrom spec environmentVariables valueFrom OR spec terraformVariables valueFrom Learn more workspace variables spec variables hcl spec environmentVariables hcl OR spec terraformVariables hcl Learn more workspace variables spec variables sensitive spec environmentVariables sensitive OR spec terraformVariables sensitive Learn more workspace variables spec variables environmentVariable N A Removed variables are split between spec environmentVariables and spec terraformVariables spec runTriggers spec runTriggers None spec runTriggers sourceableName spec runTriggers name The sourceableName field is now name spec sshKeyID spec sshKey id Moved the sshKeyID to spec sshKey id spec outputs N A Removed spec terraformVersion spec terraformVersion None spec notifications spec notifications None spec notifications type spec notifications type None spec notifications enabled spec notifications enabled None spec notifications name spec notifications name None spec notifications url spec notifications url None spec notifications token spec notifications token None spec notifications triggers spec notifications triggers None spec notifications recipients spec notifications emailAddresses Renamed the recipients field to emailAddresses spec notifications users spec notifications emailUsers Renamed the users field to emailUsers spec omitNamespacePrefix N A Removed In v1 spec omitNamespacePrefix is a boolean field that affects how the operator generates a workspace name In v2 you must explicitly set workspace names in spec name spec agentPoolID spec agentPool id Moved the agentPoolID field to spec agentPool id spec agentPoolName spec agentPool name Moved the agentPoolName field to spec agentPool name spec module N A Removed You now configure modules with a separate Module CRD Learn more module controller Below is an example of configuring a variable in v1 of the operator CodeBlockConfig filename v1 yaml yaml apiVersion app terraform io v1alpha1 kind Workspace metadata name migration spec variables key username value user hcl true sensitive false environmentVariable false key SECRET KEY value s3cr3t hcl false sensitive false environmentVariable true CodeBlockConfig In v2 of the operator you must configure Terraform variables in spec terraformVariables and environment variables spec environmentVariables CodeBlockConfig filename v2 yaml yaml apiVersion app terraform io v1alpha2 kind Workspace metadata name migration spec terraformVariables name username value user hcl true sensitive false environmentVariables name SECRET KEY value s3cr3t hcl false sensitive false CodeBlockConfig Module controller HCP Terraform Operator for Kubernetes v2 configures modules in a new Module controller separate from the Workspace controller Below is a template of a custom resource manifest yaml apiVersion app terraform io v1alpha2 kind Module metadata name NAME spec organization ORG NAME token secretKeyRef name SECRET NAME key KEY NAME name operator The table below describes the mapping between the Workspace controller from v1 and the Module controller in v2 of the operator Version 1 Workspace CRD Version 2 Module CRD Notes spec module N A In v2 of the operator a Module is a separate controller with its own CRD N A spec name operator In v1 of the operator the name of the generated module is hardcoded to operator In v2 the default name of the generated module is this but you can rename it spec module source spec module source This supports all Terraform module sources terraform language modules sources spec module version spec module version Refer to module sources terraform language modules sources for versioning information for each module source spec variables spec variables name You should include variable names in the module This is a reference to variables in the workspace that is executing the module spec outputs key spec outputs name You should include output names in the module This is a reference to the output variables produced by the module status workspaceID OR metadata namespace metadata name spec workspace id OR spec workspace name The workspace where the module is executed The workspace must be in the same organization Below is an example migration of a Module between v1 and v2 of the operator CodeBlockConfig filename v1 yaml yaml apiVersion app terraform io v1alpha1 kind Workspace metadata name migration spec module source app terraform io org name module name provider version 0 0 42 variables key username value user hcl true sensitive false environmentVariable false key SECRET KEY value s3cr3t hcl false sensitive false environmentVariable true CodeBlockConfig In v2 of the operator separate controllers manage workspace and modules CodeBlockConfig filename workspace v2 yaml yaml apiVersion app terraform io v1alpha2 kind Workspace metadata name migration spec terraformVariables name username value user hcl true sensitive false environmentVariables name SECRET KEY value s3cr3t hcl false sensitive false CodeBlockConfig CodeBlockConfig filename module v2 yaml yaml apiVersion app terraform io v1alpha2 kind Module metadata name migration spec name operator module source app terraform io org name module name provider version 0 0 42 workspace name migration CodeBlockConfig Upgrade the operator Download Workspace CRD patch A shell session curl sO https raw githubusercontent com hashicorp hcp terraform operator main docs migration crds workspaces patch a yaml View the changes that patch A applies to the workspace CRD shell session kubectl diff filename workspaces patch a yaml Patch the workspace CRD with patch A This patch adds app terraform io v1alpha2 support but excludes status runStatus because it has a different format in app terraform io v1alpha1 and causes JSON un marshalling issues Upgrade warning Once you apply a patch Kubernetes converts existing app terraform io v1alpha1 custom resources to app terraform io v1alpha2 according to the updated schema meaning that v1 of the operator can no longer serve custom resources Before patching update your existing custom resources to satisfy the v2 schema requirements Learn more manifest schema migration shell session kubectl patch crd workspaces app terraform io patch file workspaces patch a yaml Install the Operator v2 Helm chart with the helm install command Be sure to set the operator watchedNamespaces value to the list of namespaces your Workspace resources are deployed to If this value is not provided the operator will watch all namespaces in the Kubernetes cluster shell session helm install RELEASE NAME hashicorp hcp terraform operator version 2 4 0 namespace RELEASE NAMESPACE set operator watchedNamespaces white blue red set controllers agentPool workers 5 set controllers module workers 5 set controllers workspace workers 5 Next create a Kubernetes secret to store the HCP Terraform API token following the Usage Guide https github com hashicorp hcp terraform operator blob main docs usage md prerequisites The API token can be copied from the Kubernetes secret that you created for v1 of the operator By default this is named terraformrc Use the kubectl get secret command to get the API token shell session kubectl namespace RELEASE NAMESPACE get secret terraformrc o json jq data credentials tr d base64 d Update existing custom resources according to the schema migration guidance manifest schema migration and apply your changes shell session kubectl apply filename UPDATED V2 WORKSPACE MANIFEST yaml Download Workspace CRD patch B shell session curl sO https raw githubusercontent com hashicorp hcp terraform operator main docs migration crds workspaces patch b yaml View the changes that patch B applies to the workspace CRD shell session kubectl diff filename workspaces patch b yaml Patch the workspace CRD with patch B This patch adds status runStatus support which was excluded in patch A shell session kubectl patch crd workspaces app terraform io patch file workspaces patch b yaml The v2 operator will fail to proceed if a custom resource has the v1 finalizer finalizer workspace app terraform io If you encounter an error check the logs for more information shell session kubectl logs f POD NAME Specifically look for an error message such as the following ERROR Migration workspace default WORKSPACE NAME msg spec contains old finalizer finalizer workspace app terraform io The finalizer exists to provide greater control over the migration process Verify the custom resource and when you re ready to migrate it use the kubectl patch command to update the finalizer value shell session kubectl patch workspace migration type merge patch metadata finalizers workspace app terraform io finalizer Review the operator logs once more and verify there are no error messages shell session kubectl logs f POD NAME The operator reconciles resources during the next sync period This interval is set by the operator syncPeriod configuration of the operator and defaults to five minutes If you have any migrated Module custom resources apply them now shell session kubectl apply filename MIGRATED V2 MODULE MANIFEST yaml In v2 of the operator the applyMethod is set to manual by default In this case a new run in a managed workspace requires manual approval Run the following command for each Workspace resource to change it to auto approval shell session kubectl patch workspace WORKSPACE NAME type merge patch spec applyMethod auto
terraform The HCP Terraform Operator for Kubernetes allows you to provision infrastructure directly from HCP Terraform Operator for Kubernetes overview page title HCP Terraform Operator for Kubernetes The HCP Terraform Operator for Kubernetes https github com hashicorp hcp terraform operator allows you to manage HCP Terraform resources with Kubernetes custom resources You can provision infrastructure internal or external to your Kubernetes cluster directly from the Kubernetes control plane the Kubernetes control plane
--- page_title: HCP Terraform Operator for Kubernetes description: >- The HCP Terraform Operator for Kubernetes allows you to provision infrastructure directly from the Kubernetes control plane. --- # HCP Terraform Operator for Kubernetes overview The [HCP Terraform Operator for Kubernetes](https://github.com/hashicorp/hcp-terraform-operator) allows you to manage HCP Terraform resources with Kubernetes custom resources. You can provision infrastructure internal or external to your Kubernetes cluster directly from the Kubernetes control plane. The operator's CustomResourceDefinitions (CRD) let you dynamically create HCP Terraform workspaces with Terraform modules, populate workspace variables, and provision infrastructure with Terraform runs. ## Key benefits The HCP Terraform Operator for Kubernetes v2 offers several improvements over v1: - **Flexible resource management**: The operator now features multiple custom resources, each with separate controllers for different HCP Terraform resources. This provides additional flexibility and the ability to manage more custom resources concurrently, significantly improving performance for large-scale deployments. - **Namespace management**: The `--namespace` option allows you to tailor the operator's watch scope to specific namespaces, which enables more fine-grained resource management. - **Configurable synchronization**: The `--sync-period` option allows you to configure the synchronization frequency between custom resources and HCP Terraform, ensuring timely updates and smoother operations. ## Supported HCP Terraform features The HCP Terraform Operator for Kubernetes allows you to create agent pools, deploy modules, and manage workspaces through Kubernetes controllers. These controllers enable you to automate and manage HCP Terraform resources using custom resources in Kubernetes. ### Agent pools Agent pools in HCP Terraform manage the execution environment for Terraform runs. The HCP Terraform Operator for Kubernetes allows you to create and manage agent pools as part of your Kubernetes infrastructure. The following example creates a new agent pool with the name `agent-pool-development` and generates an agent token with the name `token-red`. ```yaml --- apiVersion: app.terraform.io/v1alpha2 kind: AgentPool metadata: name: my-agent-pool spec: organization: kubernetes-operator token: secretKeyRef: name: tfc-operator key: token name: agent-pool-development agentTokens: - name: token-red ``` The operator stores the `token-red` agent token in a Kubernetes secret named `my-agent-pool-token-red`. You can also enable agent autoscaling by providing a `.spec.autoscaling` configuration in your `AgentPool` specification. <CodeBlockConfig highlight="17-26"> ```yaml --- apiVersion: app.terraform.io/v1alpha2 kind: AgentPool metadata: name: this spec: organization: kubernetes-operator token: secretKeyRef: name: tfc-operator key: token name: agent-pool-development agentTokens: - name: token-red agentDeployment: replicas: 1 autoscaling: targetWorkspaces: - name: us-west-development - id: ws-NUVHA9feCXzAmPHx - wildcardName: eu-development-* minReplicas: 1 maxReplicas: 3 cooldownPeriod: scaleUpSeconds: 30 scaleDownSeconds: 30 ``` </CodeBlockConfig> In the above example, the operator ensures that at least one agent pod is continuously running and dynamically scales the number of pods up to a maximum of three based on the workload or resource demand. The operator then monitors resource demands by observing the load of the designated workspaces specified by the `name`, `id`, or `wildcardName` patterns. When the workload decreases, the operator downscales the number of agent pods. Refer to the [agent pool API reference](/terraform/cloud-docs/integrations/kubernetes/api-reference#agentpool) for the complete `AgentPool` specification. ### Module The `Module` controller enforces an [API-driven Run workflow](/terraform/cloud-docs/run/api) and lets you deploy Terraform modules within workspaces. The following example deploys version `1.0.0` of the `hashicorp/module/random` module in the `workspace-name` workspace. ```yaml --- apiVersion: app.terraform.io/v1alpha2 kind: Module metadata: name: my-module spec: organization: kubernetes-operator token: secretKeyRef: name: tfc-operator key: token module: source: hashicorp/module/random version: 1.0.0 workspace: name: workspace-name variables: - name: string_length outputs: - name: random_string ``` The operator passes the workspace's `string_length` variable to the module and stores the `random_string` outputs as either a Kubernetes secret or a ConfigMap. If the workspace marks the output as `sensitive`, the operator stores the `random_string` as a Kubernetes secret; otherwise, the operator stores it as a ConfigMap. The variables must be accessible within the workspace as a workspace variable, workspace variable set, or project variable set. Refer to the [module API reference](/terraform/cloud-docs/integrations/kubernetes/api-reference#module) for the complete `Module` specification. ### Project Projects let you organize your workspaces and scope access to workspace resources. The `Project` controller allows you to create, configure, and manage [projects](/terraform/tutorials/cloud/projects) directly from Kubernetes. The following example creates a new project named `testing`. ```yaml --- apiVersion: app.terraform.io/v1alpha2 kind: Project metadata: name: testing spec: organization: kubernetes-operator token: secretKeyRef: name: tfc-operator key: token name: project-demo ``` The `Project` controller allows you to manage team access [permissions](/terraform/cloud-docs/users-teams-organizations/permissions#project-permissions). The following example creates a project named `testing` and grants the `qa` team admin access to the project. <CodeBlockConfig highlight="13-16"> ```yaml --- apiVersion: app.terraform.io/v1alpha2 kind: Project metadata: name: testing spec: organization: kubernetes-operator token: secretKeyRef: name: tfc-operator key: token name: project-demo teamAccess: - team: name: qa access: admin ``` </CodeBlockConfig> Refer to the [project API reference](/terraform/cloud-docs/integrations/kubernetes/api-reference#project) for the complete `Project` specification. ### Workspace HCP Terraform workspaces organize and manage Terraform configurations. The HCP Terraform Operator for Kubernetes allows you to create, configure, and manage workspaces directly from Kubernetes. The following example creates a new workspace named `us-west-development`, configured to use Terraform version `1.6.2`. This workspace has two variables, `nodes` and `rds-secret`. The variable `rds-secret` is treated as sensitive, and the operator reads the value for the variable from a Kubernetes secret named `us-west-development-secrets`. ```yaml --- apiVersion: app.terraform.io/v1alpha2 kind: Workspace metadata: name: us-west-development spec: organization: kubernetes-operator token: secretKeyRef: name: tfc-operator key: token name: us-west-development description: US West development workspace terraformVersion: 1.6.2 applyMethod: auto agentPool: name: ap-us-west-development terraformVariables: - name: nodes value: 2 - name: rds-secret sensitive: true valueFrom: secretKeyRef: name: us-west-development-secrets key: rds-secret runTasks: - name: rt-us-west-development stage: pre_plan ``` In the above example, the `applyMethod` has the value of `auto`, so HCP Terraform automatically applies any changes to this workspace. The specification also configures the workspace to use the `ap-us-west-development` agent pool and run the `rt-us-west-development` run task at the `pre_plan` stage. The operator stores the value of the workspace outputs as Kubernetes secrets or ConfigMaps. If the outputs are marked as `sensitive`, they are stored as Kubernetes secrets, otherwise they are stored as ConfigMaps. -> **Note**: The operator rolls back any external modifications made to the workspace to match the state specified in the custom resource definition. Refer to the [workspace API reference](/terraform/cloud-docs/integrations/kubernetes/api-reference#workspace) for the complete `Workspace` specification.
terraform
page title HCP Terraform Operator for Kubernetes description The HCP Terraform Operator for Kubernetes allows you to provision infrastructure directly from the Kubernetes control plane HCP Terraform Operator for Kubernetes overview The HCP Terraform Operator for Kubernetes https github com hashicorp hcp terraform operator allows you to manage HCP Terraform resources with Kubernetes custom resources You can provision infrastructure internal or external to your Kubernetes cluster directly from the Kubernetes control plane The operator s CustomResourceDefinitions CRD let you dynamically create HCP Terraform workspaces with Terraform modules populate workspace variables and provision infrastructure with Terraform runs Key benefits The HCP Terraform Operator for Kubernetes v2 offers several improvements over v1 Flexible resource management The operator now features multiple custom resources each with separate controllers for different HCP Terraform resources This provides additional flexibility and the ability to manage more custom resources concurrently significantly improving performance for large scale deployments Namespace management The namespace option allows you to tailor the operator s watch scope to specific namespaces which enables more fine grained resource management Configurable synchronization The sync period option allows you to configure the synchronization frequency between custom resources and HCP Terraform ensuring timely updates and smoother operations Supported HCP Terraform features The HCP Terraform Operator for Kubernetes allows you to create agent pools deploy modules and manage workspaces through Kubernetes controllers These controllers enable you to automate and manage HCP Terraform resources using custom resources in Kubernetes Agent pools Agent pools in HCP Terraform manage the execution environment for Terraform runs The HCP Terraform Operator for Kubernetes allows you to create and manage agent pools as part of your Kubernetes infrastructure The following example creates a new agent pool with the name agent pool development and generates an agent token with the name token red yaml apiVersion app terraform io v1alpha2 kind AgentPool metadata name my agent pool spec organization kubernetes operator token secretKeyRef name tfc operator key token name agent pool development agentTokens name token red The operator stores the token red agent token in a Kubernetes secret named my agent pool token red You can also enable agent autoscaling by providing a spec autoscaling configuration in your AgentPool specification CodeBlockConfig highlight 17 26 yaml apiVersion app terraform io v1alpha2 kind AgentPool metadata name this spec organization kubernetes operator token secretKeyRef name tfc operator key token name agent pool development agentTokens name token red agentDeployment replicas 1 autoscaling targetWorkspaces name us west development id ws NUVHA9feCXzAmPHx wildcardName eu development minReplicas 1 maxReplicas 3 cooldownPeriod scaleUpSeconds 30 scaleDownSeconds 30 CodeBlockConfig In the above example the operator ensures that at least one agent pod is continuously running and dynamically scales the number of pods up to a maximum of three based on the workload or resource demand The operator then monitors resource demands by observing the load of the designated workspaces specified by the name id or wildcardName patterns When the workload decreases the operator downscales the number of agent pods Refer to the agent pool API reference terraform cloud docs integrations kubernetes api reference agentpool for the complete AgentPool specification Module The Module controller enforces an API driven Run workflow terraform cloud docs run api and lets you deploy Terraform modules within workspaces The following example deploys version 1 0 0 of the hashicorp module random module in the workspace name workspace yaml apiVersion app terraform io v1alpha2 kind Module metadata name my module spec organization kubernetes operator token secretKeyRef name tfc operator key token module source hashicorp module random version 1 0 0 workspace name workspace name variables name string length outputs name random string The operator passes the workspace s string length variable to the module and stores the random string outputs as either a Kubernetes secret or a ConfigMap If the workspace marks the output as sensitive the operator stores the random string as a Kubernetes secret otherwise the operator stores it as a ConfigMap The variables must be accessible within the workspace as a workspace variable workspace variable set or project variable set Refer to the module API reference terraform cloud docs integrations kubernetes api reference module for the complete Module specification Project Projects let you organize your workspaces and scope access to workspace resources The Project controller allows you to create configure and manage projects terraform tutorials cloud projects directly from Kubernetes The following example creates a new project named testing yaml apiVersion app terraform io v1alpha2 kind Project metadata name testing spec organization kubernetes operator token secretKeyRef name tfc operator key token name project demo The Project controller allows you to manage team access permissions terraform cloud docs users teams organizations permissions project permissions The following example creates a project named testing and grants the qa team admin access to the project CodeBlockConfig highlight 13 16 yaml apiVersion app terraform io v1alpha2 kind Project metadata name testing spec organization kubernetes operator token secretKeyRef name tfc operator key token name project demo teamAccess team name qa access admin CodeBlockConfig Refer to the project API reference terraform cloud docs integrations kubernetes api reference project for the complete Project specification Workspace HCP Terraform workspaces organize and manage Terraform configurations The HCP Terraform Operator for Kubernetes allows you to create configure and manage workspaces directly from Kubernetes The following example creates a new workspace named us west development configured to use Terraform version 1 6 2 This workspace has two variables nodes and rds secret The variable rds secret is treated as sensitive and the operator reads the value for the variable from a Kubernetes secret named us west development secrets yaml apiVersion app terraform io v1alpha2 kind Workspace metadata name us west development spec organization kubernetes operator token secretKeyRef name tfc operator key token name us west development description US West development workspace terraformVersion 1 6 2 applyMethod auto agentPool name ap us west development terraformVariables name nodes value 2 name rds secret sensitive true valueFrom secretKeyRef name us west development secrets key rds secret runTasks name rt us west development stage pre plan In the above example the applyMethod has the value of auto so HCP Terraform automatically applies any changes to this workspace The specification also configures the workspace to use the ap us west development agent pool and run the rt us west development run task at the pre plan stage The operator stores the value of the workspace outputs as Kubernetes secrets or ConfigMaps If the outputs are marked as sensitive they are stored as Kubernetes secrets otherwise they are stored as ConfigMaps Note The operator rolls back any external modifications made to the workspace to match the state specified in the custom resource definition Refer to the workspace API reference terraform cloud docs integrations kubernetes api reference workspace for the complete Workspace specification
terraform API Reference app terraform io v1alpha2 appterraformiov1alpha2 page title HCP Terraform Operator for Kubernetes API reference Packages API reference for the HCP Terraform Operator for Kubernetes
--- page_title: HCP Terraform Operator for Kubernetes API reference description: >- API reference for the HCP Terraform Operator for Kubernetes. --- # API Reference ## Packages - [app.terraform.io/v1alpha2](#appterraformiov1alpha2) ## app.terraform.io/v1alpha2 Package v1alpha2 contains API Schema definitions for the app v1alpha2 API group ### Resource Types - [AgentPool](#agentpool) - [Module](#module) - [Project](#project) - [Workspace](#workspace) #### AgentDeployment _Appears in:_ - [AgentPoolSpec](#agentpoolspec) | Field | Description | | --- | --- | | `replicas` _integer_ | | | `spec` _[PodSpec](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.27/#podspec-v1-core)_ | | | `annotations` _object (keys:string, values:string)_ | The annotations that the operator will apply to the pod template in the deployment. | | `labels` _object (keys:string, values:string)_ | The labels that the operator will apply to the pod template in the deployment. | #### AgentDeploymentAutoscaling AgentDeploymentAutoscaling configures the operator to scale the deployment for an AgentPool up and down to meet demand. _Appears in:_ - [AgentPoolSpec](#agentpoolspec) | Field | Description | | --- | --- | | `maxReplicas` _integer_ | MaxReplicas is the maximum number of replicas for the Agent deployment. | | `minReplicas` _integer_ | MinReplicas is the minimum number of replicas for the Agent deployment. | | `targetWorkspaces` _[TargetWorkspace](#targetworkspace)_ | TargetWorkspaces is a list of HCP Terraform Workspaces which the agent pool should scale up to meet demand. When this field is omitted the autoscaler will target all workspaces that are associated with the AgentPool. | | `cooldownPeriodSeconds` _integer_ | CooldownPeriodSeconds is the time to wait between scaling events. Defaults to 300. | | `cooldownPeriod` _[AgentDeploymentAutoscalingCooldownPeriod](#agentdeploymentautoscalingcooldownperiod)_ | CoolDownPeriod is the period to wait between scaling up and scaling down | #### AgentDeploymentAutoscalingCooldownPeriod AgentDeploymentAutoscalingCooldownPeriod configures the period to wait between scaling up and scaling down. _Appears in:_ - [AgentDeploymentAutoscaling](#agentdeploymentautoscaling) | Field | Description | | --- | --- | | `scaleUpSeconds` _integer_ | ScaleUpSeconds is the time to wait before scaling up. | | `scaleDownSeconds` _integer_ | ScaleDownSeconds is the time to wait before scaling down. | #### AgentDeploymentAutoscalingStatus AgentDeploymentAutoscalingStatus _Appears in:_ - [AgentPoolStatus](#agentpoolstatus) | Field | Description | | --- | --- | | `desiredReplicas` _integer_ | Desired number of agent replicas | | `lastScalingEvent` _[Time](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.27/#time-v1-meta)_ | Last time the agent pool was scaledx | #### AgentPool AgentPool is the Schema for the agentpools API. | Field | Description | | --- | --- | | `apiVersion` _string_ | `app.terraform.io/v1alpha2` | `kind` _string_ | `AgentPool` | `kind` _string_ | Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. [More information](https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds) | | `apiVersion` _string_ | APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. [More information](https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources) | | `metadata` _[ObjectMeta](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.27/#objectmeta-v1-meta)_ | Refer to Kubernetes API documentation for fields of `metadata`. | | `spec` _[AgentPoolSpec](#agentpoolspec)_ | | #### AgentPoolSpec AgentPoolSpec defines the desired state of AgentPool. _Appears in:_ - [AgentPool](#agentpool) | Field | Description | | --- | --- | | `name` _string_ | Agent Pool name. [More information](/terraform/cloud-docs/agents/agent-pools). | | `organization` _string_ | Organization name where the Workspace will be created. [More information](/terraform/cloud-docs/users-teams-organizations/organizations). | | `token` _[Token](#token)_ | API Token to be used for API calls. | | `agentTokens` _[AgentToken](#agenttoken) array_ | List of the agent tokens to generate. | | `agentDeployment` _[AgentDeployment](#agentdeployment)_ | Agent deployment settings | | `autoscaling` _[AgentDeploymentAutoscaling](#agentdeploymentautoscaling)_ | Agent deployment settings | #### AgentToken Terraform uses `AgentTokens` to connect to the Terraform agent pool. Only the field `Name` is allowed in the `spec` list. Use the other fields in the `status` list. [More information](/terraform/cloud-docs/agents). _Appears in:_ - [AgentPoolSpec](#agentpoolspec) - [AgentPoolStatus](#agentpoolstatus) | Field | Description | | --- | --- | | `name` _string_ | Agent Token name. | | `id` _string_ | Agent Token ID. | | `createdAt` _integer_ | Timestamp of when the agent token was created. | | `lastUsedAt` _integer_ | Timestamp of when the agent token was last used. | #### ConfigurationVersionStatus A configuration version is a resource used to reference the uploaded configuration files. More information: - [Configuration versions API](/terraform/cloud-docs/api-docs/configuration-versions) - [The API-driven run workflow](/terraform/cloud-docs/run/api) _Appears in:_ - [ModuleStatus](#modulestatus) | Field | Description | | --- | --- | | `id` _string_ | Configuration Version ID. | #### ConsumerWorkspace ConsumerWorkspace allows access to the state for specific workspaces within the same organization. Only one of the fields `ID` or `Name` is allowed. At least one of the fields `ID` or `Name` is mandatory. [More information](/terraform/cloud-docs/workspaces/state#remote-state-access-controls). _Appears in:_ - [RemoteStateSharing](#remotestatesharing) | Field | Description | | --- | --- | | `id` _string_ | Consumer Workspace ID. Must match pattern: `^ws-[a-zA-Z0-9]+$` | | `name` _string_ | Consumer Workspace name. | #### CustomPermissions Custom permissions let you assign specific, finer-grained permissions to a team than the broader fixed permission sets provide. [More information](/terraform/cloud-docs/users-teams-organizations/permissions#custom-workspace-permissions). _Appears in:_ - [TeamAccess](#teamaccess) | Field | Description | | --- | --- | | `runs` _string_ | Run access. Must be one of the following values: `apply`, `plan`, `read`. Default: `read`. | | `runTasks` _boolean_ | Manage Workspace Run Tasks. Default: `false`. | | `sentinel` _string_ | Download Sentinel mocks. Must be one of the following values: `none`, `read`. Default: `none`. | | `stateVersions` _string_ | State access. Must be one of the following values: `none`, `read`, `read-outputs`, `write`. Default: `none`. | | `variables` _string_ | Variable access. Must be one of the following values: `none`, `read`, `write`. Default: `none`. | | `workspaceLocking` _boolean_ | Lock/unlock workspace. Default: `false`. | #### CustomProjectPermissions Custom permissions let you assign specific, finer-grained permissions to a team than the broader fixed permission sets provide. More information: - [Custom project permissions](/terraform/cloud-docs/users-teams-organizations/permissions#custom-project-permissions) - [General workspace permissions](/terraform/cloud-docs/users-teams-organizations/permissions#general-workspace-permissions) _Appears in:_ - [ProjectTeamAccess](#projectteamaccess) | Field | Description | | --- | --- | | `projectAccess` _[ProjectSettingsPermissionType](#projectsettingspermissiontype)_ | Project access. Must be one of the following values: `delete`, `read`, `update`. Default: `read`. | | `teamManagement` _[ProjectTeamsPermissionType](#projectteamspermissiontype)_ | Team management. Must be one of the following values: `manage`, `none`, `read`. Default: `none`. | | `createWorkspace` _boolean_ | Allow users to create workspaces in the project. This grants read access to all workspaces in the project. Default: `false`. | | `deleteWorkspace` _boolean_ | Allows users to delete workspaces in the project. Default: `false`. | | `moveWorkspace` _boolean_ | Allows users to move workspaces out of the project. A user must have this permission on both the source and destination project to successfully move a workspace from one project to another. Default: `false`. | | `lockWorkspace` _boolean_ | Allows users to manually lock the workspace to temporarily prevent runs. When a workspace's execution mode is set to "local", users must have this permission to perform local CLI runs using the workspace's state. Default: `false`. | | `runs` _[WorkspaceRunsPermissionType](#workspacerunspermissiontype)_ | Run access. Must be one of the following values: `apply`, `plan`, `read`. Default: `read`. | | `runTasks` _boolean_ | Manage Workspace Run Tasks. Default: `false`. | | `sentinelMocks` _[WorkspaceSentinelMocksPermissionType](#workspacesentinelmockspermissiontype)_ | Download Sentinel mocks. Must be one of the following values: `none`, `read`. Default: `none`. | | `stateVersions` _[WorkspaceStateVersionsPermissionType](#workspacestateversionspermissiontype)_ | State access. Must be one of the following values: `none`, `read`, `read-outputs`, `write`. Default: `none`. | | `variables` _[WorkspaceVariablesPermissionType](#workspacevariablespermissiontype)_ | Variable access. Must be one of the following values: `none`, `read`, `write`. Default: `none`. | #### DeletionPolicy _Underlying type:_ _string_ DeletionPolicy defines the strategy the Kubernetes operator uses when you delete a resource, either manually or by a system event. You must use one of the following values: - `retain`: When you delete the custom resource, the operator does not delete the workspace. - `soft`: Attempts to delete the associated workspace only if it does not contain any managed resources. - `destroy`: Executes a destroy operation to remove all resources managed by the associated workspace. Once the destruction of these resources is successful, the operator deletes the workspace, and then deletes the custom resource. - `force`: Forcefully and immediately deletes the workspace and the custom resource. _Appears in:_ - [WorkspaceSpec](#workspacespec) #### Module Module is the Schema for the modules API Module implements the API-driven Run Workflow. [More information](/terraform/cloud-docs/run/api). | Field | Description | | --- | --- | | `apiVersion` _string_ | `app.terraform.io/v1alpha2` | `kind` _string_ | `Module` | `kind` _string_ | Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. [More information](https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds) | | `apiVersion` _string_ | APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. [More information](https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources) | | `metadata` _[ObjectMeta](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.27/#objectmeta-v1-meta)_ | Refer to Kubernetes API documentation for fields of `metadata`. | | `spec` _[ModuleSpec](#modulespec)_ | | #### ModuleOutput Module outputs to store in ConfigMap(non-sensitive) or Secret(sensitive). _Appears in:_ - [ModuleSpec](#modulespec) | Field | Description | | --- | --- | | `name` _string_ | Output name must match with the module output. | | `sensitive` _boolean_ | Specify whether or not the output is sensitive. Default: `false`. | #### ModuleSource Module source and version to execute. _Appears in:_ - [ModuleSpec](#modulespec) | Field | Description | | --- | --- | | `source` _string_ | Non local Terraform module source. [More information](/terraform/language/modules/sources). | | `version` _string_ | Terraform module version. | #### ModuleSpec ModuleSpec defines the desired state of Module. _Appears in:_ - [Module](#module) | Field | Description | | --- | --- | | `organization` _string_ | Organization name where the Workspace will be created. [More information](/terraform/cloud-docs/users-teams-organizations/organizations). | | `token` _[Token](#token)_ | API Token to be used for API calls. | | `module` _[ModuleSource](#modulesource)_ | Module source and version to execute. | | `workspace` _[ModuleWorkspace](#moduleworkspace)_ | Workspace to execute the module. | | `name` _string_ | Name of the module that will be uploaded and executed. Default: `this`. | | `variables` _[ModuleVariable](#modulevariable) array_ | Variables to pass to the module, they must exist in the Workspace. | | `outputs` _[ModuleOutput](#moduleoutput) array_ | Module outputs to store in ConfigMap(non-sensitive) or Secret(sensitive). | | `destroyOnDeletion` _boolean_ | Specify whether or not to execute a Destroy run when the object is deleted from the Kubernetes. Default: `false`. | | `restartedAt` _string_ | Allows executing a new Run without changing any Workspace or Module attributes. Example: ``kubectl patch KIND NAME --type=merge --patch '{"spec": {"restartedAt": "'\`date -u -Iseconds\`'"}}'`` | #### ModuleVariable Variables to pass to the module. _Appears in:_ - [ModuleSpec](#modulespec) | Field | Description | | --- | --- | | `name` _string_ | Variable name must exist in the Workspace. | #### ModuleWorkspace Workspace to execute the module. Only one of the fields `ID` or `Name` is allowed. At least one of the fields `ID` or `Name` is mandatory. _Appears in:_ - [ModuleSpec](#modulespec) | Field | Description | | --- | --- | | `id` _string_ | Module Workspace ID. Must match pattern: `^ws-[a-zA-Z0-9]+$` | | `name` _string_ | Module Workspace Name. | #### Notification Notifications allow you to send messages to other applications based on run and workspace events. [More information](/terraform/cloud-docs/workspaces/settings/notifications). _Appears in:_ - [WorkspaceSpec](#workspacespec) | Field | Description | | --- | --- | | `name` _string_ | Notification name. | | `type` _[NotificationDestinationType](#notificationdestinationtype)_ | The type of the notification. Must be one of the following values: `email`, `generic`, `microsoft-teams`, `slack`. | | `enabled` _boolean_ | Whether the notification configuration should be enabled or not. Default: `true`. | | `token` _string_ | The token of the notification. | | `triggers` _[NotificationTrigger](#notificationtrigger) array_ | The list of run events that trigger notifications. Triggers are notifications that Terraform sends when a run transitions to a different state. <br/><br/>The following triggers notify you about health events: `assessment:check_failure`, `assessment:drifted`, `assessment:failed`. <br/><br/>The following triggers notify you about run events: `run:applying`, `run:completed`, `run:created`, `run:errored`, `run:needs_attention`, `run:planning`. | | `url` _string_ | The URL of the notification. Must match pattern: `^https?://.*` | | `emailAddresses` _string array_ | The list of email addresses that will receive notification emails. It is only available for Terraform Enterprise users. It is not available in HCP Terraform. | | `emailUsers` _string array_ | The list of users belonging to the organization that will receive notification emails. | #### NotificationTrigger _Underlying type:_ _string_ NotificationTrigger represents the notifications Terraform sends when a run transitions to a different state. This resource must align with `go-tfe` type `NotificationTriggerType`. You must use one of the following values: `run:applying`, `assessment:check_failure`, `run:completed`, `run:created`, `assessment:drifted`, `run:errored`, `assessment:failed`, `run:needs_attention`, `run:planning`. _Appears in:_ - [Notification](#notification) #### OutputStatus Outputs status. _Appears in:_ - [ModuleStatus](#modulestatus) | Field | Description | | --- | --- | | `runID` _string_ | Run ID of the latest run that updated the outputs. | #### PlanStatus _Appears in:_ - [WorkspaceStatus](#workspacestatus) | Field | Description | | --- | --- | | `id` _string_ | Latest plan-only/speculative plan HCP Terraform run ID. | | `terraformVersion` _string_ | The version of Terraform to use for this run. | #### Project Project is the Schema for the projects API | Field | Description | | --- | --- | | `apiVersion` _string_ | `app.terraform.io/v1alpha2` | `kind` _string_ | `Project` | `kind` _string_ | Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. [More information](https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds) | | `apiVersion` _string_ | APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. [More information](https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources) | | `metadata` _[ObjectMeta](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.27/#objectmeta-v1-meta)_ | Refer to Kubernetes API documentation for fields of `metadata`. | | `spec` _[ProjectSpec](#projectspec)_ | | #### ProjectSpec ProjectSpec defines the desired state of Project. [More information](/terraform/cloud-docs/workspaces/organize-workspaces-with-projects). _Appears in:_ - [Project](#project) | Field | Description | | --- | --- | | `organization` _string_ | Organization name where the Workspace will be created. [More information](/terraform/cloud-docs/users-teams-organizations/organizations). | | `token` _[Token](#token)_ | API Token to be used for API calls. | | `name` _string_ | Name of the Project. | | `teamAccess` _[ProjectTeamAccess](#projectteamaccess) array_ | HCP Terraform's access model is team-based. In order to perform an action within a HCP Terraform organization, users must belong to a team that has been granted the appropriate permissions. You can assign project-specific permissions to teams. More information: <br /> [Project permissions](/terraform/cloud-docs/workspaces/organize-workspaces-with-projects#permissions) - [Team project permissions](/terraform/cloud-docs/users-teams-organizations/permissions#project-permissions) | #### ProjectTeamAccess HCP Terraform's access model is team-based. In order to perform an action within a HCP Terraform organization, users must belong to a team that has been granted the appropriate permissions. You can assign project-specific permissions to teams. More information: - [Project permissions API](/terraform/cloud-docs/workspaces/organize-workspaces-with-projects#permissions) - [Project permissions](/terraform/cloud-docs/users-teams-organizations/permissions#project-permissions) _Appears in:_ - [ProjectSpec](#projectspec) | Field | Description | | --- | --- | | `team` _[Team](#team)_ | Team to grant access. [More information](/terraform/cloud-docs/users-teams-organizations/teams). | | `access` _[TeamProjectAccessType](#teamprojectaccesstype)_ | There are two ways to choose which permissions a given team has on a project: fixed permission sets, and custom permissions. Must be one of the following values: `admin`, `custom`, `maintain`, `read`, `write`. More information: <br /> - [Project permissions](/terraform/cloud-docs/users-teams-organizations/permissions#project-permissions) <br />- [General project permissions](/terraform/cloud-docs/users-teams-organizations/permissions#general-project-permissions) | | `custom` _[CustomProjectPermissions](#customprojectpermissions)_ | Custom permissions let you assign specific, finer-grained permissions to a team than the broader fixed permission sets provide. [More information](/terraform/cloud-docs/users-teams-organizations/permissions#custom-project-permissions). | #### RemoteStateSharing RemoteStateSharing allows remote state access between workspaces. By default, new workspaces in HCP Terraform do not allow other workspaces to access their state. [More information](/terraform/cloud-docs/workspaces/state#accessing-state-from-other-workspaces). _Appears in:_ - [WorkspaceSpec](#workspacespec) | Field | Description | | --- | --- | | `allWorkspaces` _boolean_ | Allow access to the state for all workspaces within the same organization. Default: `false`. | | `workspaces` _[ConsumerWorkspace](#consumerworkspace) array_ | Allow access to the state for specific workspaces within the same organization. | #### RunStatus _Appears in:_ - [ModuleStatus](#modulestatus) - [WorkspaceStatus](#workspacestatus) | Field | Description | | --- | --- | | `id` _string_ | Current(both active and finished) HCP Terraform run ID. | | `configurationVersion` _string_ | The configuration version of this run. | | `outputRunID` _string_ | Run ID of the latest run that could update the outputs. | #### RunTrigger RunTrigger allows you to connect this workspace to one or more source workspaces. These connections allow runs to queue automatically in this workspace on successful apply of runs in any of the source workspaces. Only one of the fields `ID` or `Name` is allowed. At least one of the fields `ID` or `Name` is mandatory. [More information](/terraform/cloud-docs/workspaces/settings/run-triggers). _Appears in:_ - [WorkspaceSpec](#workspacespec) | Field | Description | | --- | --- | | `id` _string_ | Source Workspace ID. Must match pattern: `^ws-[a-zA-Z0-9]+$` | | `name` _string_ | Source Workspace Name. | #### SSHKey SSH key used to clone Terraform modules. Only one of the fields `ID` or `Name` is allowed. At least one of the fields `ID` or `Name` is mandatory. [More information](/terraform/cloud-docs/workspaces/settings/ssh-keys). _Appears in:_ - [WorkspaceSpec](#workspacespec) | Field | Description | | --- | --- | | `id` _string_ | SSH key ID. Must match pattern: `^sshkey-[a-zA-Z0-9]+$` | | `name` _string_ | SSH key name. | #### Tag _Underlying type:_ _string_ Tags allows you to correlate, organize, and even filter workspaces based on the assigned tags. Tags must be one or more characters; can include letters, numbers, colons, hyphens, and underscores; and must begin and end with a letter or number. Must match pattern: `^[A-Za-z0-9][A-Za-z0-9:_-]*$` _Appears in:_ - [WorkspaceSpec](#workspacespec) #### TargetWorkspace TargetWorkspace is the name or ID of the workspace you want autoscale against. _Appears in:_ - [AgentDeploymentAutoscaling](#agentdeploymentautoscaling) | Field | Description | | --- | --- | | `id` _string_ | Workspace ID | | `name` _string_ | Workspace Name | | `wildcardName` _string_ | Wildcard Name to match match workspace names using `*` on name suffix, prefix, or both. | #### Team Teams are groups of HCP Terraform users within an organization. If a user belongs to at least one team in an organization, they are considered a member of that organization. Only one of the fields `ID` or `Name` is allowed. At least one of the fields `ID` or `Name` is mandatory. [More information](/terraform/cloud-docs/users-teams-organizations/teams). _Appears in:_ - [ProjectTeamAccess](#projectteamaccess) - [TeamAccess](#teamaccess) | Field | Description | | --- | --- | | `id` _string_ | Team ID. Must match pattern: `^team-[a-zA-Z0-9]+$` | | `name` _string_ | Team name. | #### TeamAccess HCP Terraform workspaces can only be accessed by users with the correct permissions. You can manage permissions for a workspace on a per-team basis. When a workspace is created, only the owners team and teams with the "manage workspaces" permission can access it, with full admin permissions. These teams' access can't be removed from a workspace.[More information](/terraform/cloud-docs/workspaces/settings/access). _Appears in:_ - [WorkspaceSpec](#workspacespec) | Field | Description | | --- | --- | | `team` _[Team](#team)_ | Team to grant access. [More information](/terraform/cloud-docs/users-teams-organizations/teams). | | `access` _string_ | There are two ways to choose which permissions a given team has on a workspace: fixed permission sets, and custom permissions. Must be one of the following values: `admin`, `custom`, `plan`, `read`, `write`. [More information](/terraform/cloud-docs/users-teams-organizations/permissions#workspace-permissions). | | `custom` _[CustomPermissions](#custompermissions)_ | Custom permissions let you assign specific, finer-grained permissions to a team than the broader fixed permission sets provide. [More information](/terraform/cloud-docs/users-teams-organizations/permissions#custom-workspace-permissions). | #### Token Token refers to a Kubernetes Secret object within the same namespace as the Workspace object _Appears in:_ - [AgentPoolSpec](#agentpoolspec) - [ModuleSpec](#modulespec) - [ProjectSpec](#projectspec) - [WorkspaceSpec](#workspacespec) | Field | Description | | --- | --- | | `secretKeyRef` _[SecretKeySelector](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.27/#secretkeyselector-v1-core)_ | Selects a key of a secret in the workspace's namespace | #### ValueFrom ValueFrom source for the variable's value. Cannot be used if value is not empty. _Appears in:_ - [Variable](#variable) | Field | Description | | --- | --- | | `configMapKeyRef` _[ConfigMapKeySelector](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.27/#configmapkeyselector-v1-core)_ | Selects a key of a ConfigMap. | | `secretKeyRef` _[SecretKeySelector](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.27/#secretkeyselector-v1-core)_ | Selects a key of a Secret. | #### Variable Variables let you customize configurations, modify Terraform's behavior, and store information like provider credentials. [More information](/terraform/cloud-docs/workspaces/variables). _Appears in:_ - [WorkspaceSpec](#workspacespec) | Field | Description | | --- | --- | | `name` _string_ | Name of the variable. | | `description` _string_ | Description of the variable. | | `hcl` _boolean_ | Parse this field as HashiCorp Configuration Language (HCL). This allows you to interpolate values at runtime. Default: `false`. | | `sensitive` _boolean_ | Sensitive variables are never shown in the UI or API. They may appear in Terraform logs if your configuration is designed to output them. Default: `false`. | | `value` _string_ | Value of the variable. | | `valueFrom` _[ValueFrom](#valuefrom)_ | Source for the variable's value. Cannot be used if value is not empty. | #### VariableStatus _Appears in:_ - [WorkspaceStatus](#workspacestatus) | Field | Description | | --- | --- | | `name` _string_ | Name of the variable. | | `id` _string_ | ID of the variable. | | `versionID` _string_ | VersionID is a hash of the variable on the HCP Terraform end. | | `valueID` _string_ | ValueID is a hash of the variable on the CRD end. | | `category` _string_ | Category of the variable. | #### VersionControl VersionControl settings for the workspace's VCS repository, enabling the UI/VCS-driven run workflow. Omit this argument to utilize the CLI-driven and API-driven workflows, where runs are not driven by webhooks on your VCS provider. More information: - [The UI- and VCS-driven run workflow](/terraform/cloud-docs/run/ui) - [Connecting VCS providers to HCP Terraform](/terraform/cloud-docs/vcs) _Appears in:_ - [WorkspaceSpec](#workspacespec) | Field | Description | | --- | --- | | `oAuthTokenID` _string_ | The VCS Connection (OAuth Connection + Token) to use. Must match pattern: `^ot-[a-zA-Z0-9]+$` | | `repository` _string_ | A reference to your VCS repository in the format `<organization>/<repository>` where `<organization>` and `<repository>` refer to the organization and repository in your VCS provider. | | `branch` _string_ | The repository branch that Run will execute from. This defaults to the repository's default branch (e.g. main). | | `speculativePlans` _boolean_ | Whether this workspace allows automatic speculative plans on PR. Default: `true`. More information: <br />- [Speculative plans on pull requests](/terraform/cloud-docs/run/ui#speculative-plans-on-pull-requests) <br />- [Speculative plans](/terraform/cloud-docs/run/remote-operations#speculative-plans) | #### Workspace Workspace is the Schema for the workspaces API | Field | Description | | --- | --- | | `apiVersion` _string_ | `app.terraform.io/v1alpha2` | `kind` _string_ | `Workspace` | `kind` _string_ | Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. [More information](https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds) | | `apiVersion` _string_ | APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. [More information](https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources) | | `metadata` _[ObjectMeta](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.27/#objectmeta-v1-meta)_ | Refer to Kubernetes API documentation for fields of `metadata`. | | `spec` _[WorkspaceSpec](#workspacespec)_ | | #### WorkspaceAgentPool AgentPool allows HCP Terraform to communicate with isolated, private, or on-premises infrastructure. Only one of the fields `ID` or `Name` is allowed. At least one of the fields `ID` or `Name` is mandatory. [More information](/terraform/cloud-docs/agents). _Appears in:_ - [WorkspaceSpec](#workspacespec) | Field | Description | | --- | --- | | `id` _string_ | Agent Pool ID. Must match pattern: `^apool-[a-zA-Z0-9]+$` | | `name` _string_ | Agent Pool name. | #### WorkspaceProject Projects let you organize your workspaces into groups. Only one of the fields `ID` or `Name` is allowed. At least one of the fields `ID` or `Name` is mandatory. [More information](/terraform/tutorials/cloud/projects). _Appears in:_ - [WorkspaceSpec](#workspacespec) | Field | Description | | --- | --- | | `id` _string_ | Project ID. Must match pattern: `^prj-[a-zA-Z0-9]+$` | | `name` _string_ | Project name. | #### WorkspaceRunTask Run tasks allow HCP Terraform to interact with external systems at specific points in the HCP Terraform run lifecycle. Only one of the fields `ID` or `Name` is allowed. At least one of the fields `ID` or `Name` is mandatory. [More information](/terraform/cloud-docs/workspaces/settings/run-tasks). _Appears in:_ - [WorkspaceSpec](#workspacespec) | Field | Description | | --- | --- | | `id` _string_ | Run Task ID. Must match pattern: `^task-[a-zA-Z0-9]+$` | | `name` _string_ | Run Task Name. | | `enforcementLevel` _string_ | Run Task Enforcement Level. Can be one of `advisory` or `mandatory`. Default: `advisory`. Must be one of the following values: `advisory`, `mandatory` Default: `advisory`. | | `stage` _string_ | Run Task Stage. Must be one of the following values: `pre_apply`, `pre_plan`, `post_plan`. Default: `post_plan`. | #### WorkspaceSpec WorkspaceSpec defines the desired state of Workspace. _Appears in:_ - [Workspace](#workspace) | Field | Description | | --- | --- | | `name` _string_ | Workspace name. | | `organization` _string_ | Organization name where the Workspace will be created. [More information](/terraform/cloud-docs/users-teams-organizations/organizations). | | `token` _[Token](#token)_ | API Token to be used for API calls. | | `applyMethod` _string_ | Define either change will be applied automatically(auto) or require an operator to confirm(manual). Must be one of the following values: `auto`, `manual`. Default: `manual`. [More information](/terraform/cloud-docs/workspaces/settings#auto-apply-and-manual-apply). | | `allowDestroyPlan` _boolean_ | Allows a destroy plan to be created and applied. Default: `true`. [More information](/terraform/cloud-docs/workspaces/settings#destruction-and-deletion). | | `description` _string_ | Workspace description. | | `agentPool` _[WorkspaceAgentPool](#workspaceagentpool)_ | HCP Terraform Agents allow HCP Terraform to communicate with isolated, private, or on-premises infrastructure. [More information](/terraform/cloud-docs/agents). | | `executionMode` _string_ | Define where the Terraform code will be executed. Must be one of the following values: `agent`, `local`, `remote`. Default: `remote`. [More information](/terraform/cloud-docs/workspaces/settings#execution-mode). | | `runTasks` _[WorkspaceRunTask](#workspaceruntask) array_ | Run tasks allow HCP Terraform to interact with external systems at specific points in the HCP Terraform run lifecycle. [More information](/terraform/cloud-docs/workspaces/settings/run-tasks). | | `tags` _[Tag](#tag) array_ | Workspace tags are used to help identify and group together workspaces. Tags must be one or more characters; can include letters, numbers, colons, hyphens, and underscores; and must begin and end with a letter or number. | | `teamAccess` _[TeamAccess](#teamaccess) array_ | HCP Terraform workspaces can only be accessed by users with the correct permissions. You can manage permissions for a workspace on a per-team basis. When a workspace is created, only the owners team and teams with the "manage workspaces" permission can access it, with full admin permissions. These teams' access can't be removed from a workspace. [More information](/terraform/cloud-docs/workspaces/settings/access). | | `terraformVersion` _string_ | The version of Terraform to use for this workspace. If not specified, the latest available version will be used. Must match pattern: `^\\d{1}\\.\\d{1,2}\\.\\d{1,2}$` More information: - /cloud-docs/workspaces/settings#terraform-version | | `workingDirectory` _string_ | The directory where Terraform will execute, specified as a relative path from the root of the configuration directory. More information: - /cloud-docs/workspaces/settings#terraform-working-directory | | `environmentVariables` _[Variable](#variable) array_ | Terraform Environment variables for all plans and applies in this workspace. Variables defined within a workspace always overwrite variables from variable sets that have the same type and the same key. More information: <br /> - [Workspace variables](/terraform/cloud-docs/workspaces/variables) <br /> - [Environment variables](/terraform/cloud-docs/workspaces/variables#environment-variables) | | `terraformVariables` _[Variable](#variable) array_ | Terraform variables for all plans and applies in this workspace. Variables defined within a workspace always overwrite variables from variable sets that have the same type and the same key. [More information: <br /> - [Workspace variables](/terraform/cloud-docs/workspaces/variables) <br />- [Terraform variables](/terraform/cloud-docs/workspaces/variables#terraform-variables) | | `remoteStateSharing` _[RemoteStateSharing](#remotestatesharing)_ | Remote state access between workspaces. By default, new workspaces in HCP Terraform do not allow other workspaces to access their state. [More information](/terraform/cloud-docs/workspaces/state#accessing-state-from-other-workspaces). | | `runTriggers` _[RunTrigger](#runtrigger) array_ | Run triggers allow you to connect this workspace to one or more source workspaces. These connections allow runs to queue automatically in this workspace on successful apply of runs in any of the source workspaces. [More information](/terraform/cloud-docs/workspaces/settings/run-triggers). | | `versionControl` _[VersionControl](#versioncontrol)_ | Settings for the workspace's VCS repository, enabling the UI/VCS-driven run workflow. Omit this argument to utilize the CLI-driven and API-driven workflows, where runs are not driven by webhooks on your VCS provider. More information: - /cloud-docs/run/ui - /cloud-docs/vcs | | `sshKey` _[SSHKey](#sshkey)_ | SSH key used to clone Terraform modules. [More information](/terraform/cloud-docs/workspaces/settings/ssh-keys). | | `notifications` _[Notification](#notification) array_ | Notifications allow you to send messages to other applications based on run and workspace events. [More information](/terraform/cloud-docs/workspaces/settings/notifications). | | `project` _[WorkspaceProject](#workspaceproject)_ | Projects let you organize your workspaces into groups. Default: default organization project. [More information](/terraform/tutorials/cloud/projects). | | `deletionPolicy` _[DeletionPolicy](#deletionpolicy)_ | The Deletion Policy specifies the behavior of the custom resource and its associated workspace when the custom resource is deleted.<br />- `retain`: When you delete the custom resource, the operator does not delete the workspace.<br />- `soft`: Attempts to delete the associated workspace only if it does not contain any managed resources.<br />- `destroy`: Executes a destroy operation to remove all resources managed by the associated workspace. Once the destruction of these resources is successful, the operator deletes the workspace, and then deletes the custom resource.<br />- `force`: Forcefully and immediately deletes the workspace and the custom resource.<br />Default: `retain`. |
terraform
page title HCP Terraform Operator for Kubernetes API reference description API reference for the HCP Terraform Operator for Kubernetes API Reference Packages app terraform io v1alpha2 appterraformiov1alpha2 app terraform io v1alpha2 Package v1alpha2 contains API Schema definitions for the app v1alpha2 API group Resource Types AgentPool agentpool Module module Project project Workspace workspace AgentDeployment Appears in AgentPoolSpec agentpoolspec Field Description replicas integer spec PodSpec https kubernetes io docs reference generated kubernetes api v1 27 podspec v1 core annotations object keys string values string The annotations that the operator will apply to the pod template in the deployment labels object keys string values string The labels that the operator will apply to the pod template in the deployment AgentDeploymentAutoscaling AgentDeploymentAutoscaling configures the operator to scale the deployment for an AgentPool up and down to meet demand Appears in AgentPoolSpec agentpoolspec Field Description maxReplicas integer MaxReplicas is the maximum number of replicas for the Agent deployment minReplicas integer MinReplicas is the minimum number of replicas for the Agent deployment targetWorkspaces TargetWorkspace targetworkspace TargetWorkspaces is a list of HCP Terraform Workspaces which the agent pool should scale up to meet demand When this field is omitted the autoscaler will target all workspaces that are associated with the AgentPool cooldownPeriodSeconds integer CooldownPeriodSeconds is the time to wait between scaling events Defaults to 300 cooldownPeriod AgentDeploymentAutoscalingCooldownPeriod agentdeploymentautoscalingcooldownperiod CoolDownPeriod is the period to wait between scaling up and scaling down AgentDeploymentAutoscalingCooldownPeriod AgentDeploymentAutoscalingCooldownPeriod configures the period to wait between scaling up and scaling down Appears in AgentDeploymentAutoscaling agentdeploymentautoscaling Field Description scaleUpSeconds integer ScaleUpSeconds is the time to wait before scaling up scaleDownSeconds integer ScaleDownSeconds is the time to wait before scaling down AgentDeploymentAutoscalingStatus AgentDeploymentAutoscalingStatus Appears in AgentPoolStatus agentpoolstatus Field Description desiredReplicas integer Desired number of agent replicas lastScalingEvent Time https kubernetes io docs reference generated kubernetes api v1 27 time v1 meta Last time the agent pool was scaledx AgentPool AgentPool is the Schema for the agentpools API Field Description apiVersion string app terraform io v1alpha2 kind string AgentPool kind string Kind is a string value representing the REST resource this object represents Servers may infer this from the endpoint the client submits requests to Cannot be updated In CamelCase More information https git k8s io community contributors devel sig architecture api conventions md types kinds apiVersion string APIVersion defines the versioned schema of this representation of an object Servers should convert recognized schemas to the latest internal value and may reject unrecognized values More information https git k8s io community contributors devel sig architecture api conventions md resources metadata ObjectMeta https kubernetes io docs reference generated kubernetes api v1 27 objectmeta v1 meta Refer to Kubernetes API documentation for fields of metadata spec AgentPoolSpec agentpoolspec AgentPoolSpec AgentPoolSpec defines the desired state of AgentPool Appears in AgentPool agentpool Field Description name string Agent Pool name More information terraform cloud docs agents agent pools organization string Organization name where the Workspace will be created More information terraform cloud docs users teams organizations organizations token Token token API Token to be used for API calls agentTokens AgentToken agenttoken array List of the agent tokens to generate agentDeployment AgentDeployment agentdeployment Agent deployment settings autoscaling AgentDeploymentAutoscaling agentdeploymentautoscaling Agent deployment settings AgentToken Terraform uses AgentTokens to connect to the Terraform agent pool Only the field Name is allowed in the spec list Use the other fields in the status list More information terraform cloud docs agents Appears in AgentPoolSpec agentpoolspec AgentPoolStatus agentpoolstatus Field Description name string Agent Token name id string Agent Token ID createdAt integer Timestamp of when the agent token was created lastUsedAt integer Timestamp of when the agent token was last used ConfigurationVersionStatus A configuration version is a resource used to reference the uploaded configuration files More information Configuration versions API terraform cloud docs api docs configuration versions The API driven run workflow terraform cloud docs run api Appears in ModuleStatus modulestatus Field Description id string Configuration Version ID ConsumerWorkspace ConsumerWorkspace allows access to the state for specific workspaces within the same organization Only one of the fields ID or Name is allowed At least one of the fields ID or Name is mandatory More information terraform cloud docs workspaces state remote state access controls Appears in RemoteStateSharing remotestatesharing Field Description id string Consumer Workspace ID Must match pattern ws a zA Z0 9 name string Consumer Workspace name CustomPermissions Custom permissions let you assign specific finer grained permissions to a team than the broader fixed permission sets provide More information terraform cloud docs users teams organizations permissions custom workspace permissions Appears in TeamAccess teamaccess Field Description runs string Run access Must be one of the following values apply plan read Default read runTasks boolean Manage Workspace Run Tasks Default false sentinel string Download Sentinel mocks Must be one of the following values none read Default none stateVersions string State access Must be one of the following values none read read outputs write Default none variables string Variable access Must be one of the following values none read write Default none workspaceLocking boolean Lock unlock workspace Default false CustomProjectPermissions Custom permissions let you assign specific finer grained permissions to a team than the broader fixed permission sets provide More information Custom project permissions terraform cloud docs users teams organizations permissions custom project permissions General workspace permissions terraform cloud docs users teams organizations permissions general workspace permissions Appears in ProjectTeamAccess projectteamaccess Field Description projectAccess ProjectSettingsPermissionType projectsettingspermissiontype Project access Must be one of the following values delete read update Default read teamManagement ProjectTeamsPermissionType projectteamspermissiontype Team management Must be one of the following values manage none read Default none createWorkspace boolean Allow users to create workspaces in the project This grants read access to all workspaces in the project Default false deleteWorkspace boolean Allows users to delete workspaces in the project Default false moveWorkspace boolean Allows users to move workspaces out of the project A user must have this permission on both the source and destination project to successfully move a workspace from one project to another Default false lockWorkspace boolean Allows users to manually lock the workspace to temporarily prevent runs When a workspace s execution mode is set to local users must have this permission to perform local CLI runs using the workspace s state Default false runs WorkspaceRunsPermissionType workspacerunspermissiontype Run access Must be one of the following values apply plan read Default read runTasks boolean Manage Workspace Run Tasks Default false sentinelMocks WorkspaceSentinelMocksPermissionType workspacesentinelmockspermissiontype Download Sentinel mocks Must be one of the following values none read Default none stateVersions WorkspaceStateVersionsPermissionType workspacestateversionspermissiontype State access Must be one of the following values none read read outputs write Default none variables WorkspaceVariablesPermissionType workspacevariablespermissiontype Variable access Must be one of the following values none read write Default none DeletionPolicy Underlying type string DeletionPolicy defines the strategy the Kubernetes operator uses when you delete a resource either manually or by a system event You must use one of the following values retain When you delete the custom resource the operator does not delete the workspace soft Attempts to delete the associated workspace only if it does not contain any managed resources destroy Executes a destroy operation to remove all resources managed by the associated workspace Once the destruction of these resources is successful the operator deletes the workspace and then deletes the custom resource force Forcefully and immediately deletes the workspace and the custom resource Appears in WorkspaceSpec workspacespec Module Module is the Schema for the modules API Module implements the API driven Run Workflow More information terraform cloud docs run api Field Description apiVersion string app terraform io v1alpha2 kind string Module kind string Kind is a string value representing the REST resource this object represents Servers may infer this from the endpoint the client submits requests to Cannot be updated In CamelCase More information https git k8s io community contributors devel sig architecture api conventions md types kinds apiVersion string APIVersion defines the versioned schema of this representation of an object Servers should convert recognized schemas to the latest internal value and may reject unrecognized values More information https git k8s io community contributors devel sig architecture api conventions md resources metadata ObjectMeta https kubernetes io docs reference generated kubernetes api v1 27 objectmeta v1 meta Refer to Kubernetes API documentation for fields of metadata spec ModuleSpec modulespec ModuleOutput Module outputs to store in ConfigMap non sensitive or Secret sensitive Appears in ModuleSpec modulespec Field Description name string Output name must match with the module output sensitive boolean Specify whether or not the output is sensitive Default false ModuleSource Module source and version to execute Appears in ModuleSpec modulespec Field Description source string Non local Terraform module source More information terraform language modules sources version string Terraform module version ModuleSpec ModuleSpec defines the desired state of Module Appears in Module module Field Description organization string Organization name where the Workspace will be created More information terraform cloud docs users teams organizations organizations token Token token API Token to be used for API calls module ModuleSource modulesource Module source and version to execute workspace ModuleWorkspace moduleworkspace Workspace to execute the module name string Name of the module that will be uploaded and executed Default this variables ModuleVariable modulevariable array Variables to pass to the module they must exist in the Workspace outputs ModuleOutput moduleoutput array Module outputs to store in ConfigMap non sensitive or Secret sensitive destroyOnDeletion boolean Specify whether or not to execute a Destroy run when the object is deleted from the Kubernetes Default false restartedAt string Allows executing a new Run without changing any Workspace or Module attributes Example kubectl patch KIND NAME type merge patch spec restartedAt date u Iseconds ModuleVariable Variables to pass to the module Appears in ModuleSpec modulespec Field Description name string Variable name must exist in the Workspace ModuleWorkspace Workspace to execute the module Only one of the fields ID or Name is allowed At least one of the fields ID or Name is mandatory Appears in ModuleSpec modulespec Field Description id string Module Workspace ID Must match pattern ws a zA Z0 9 name string Module Workspace Name Notification Notifications allow you to send messages to other applications based on run and workspace events More information terraform cloud docs workspaces settings notifications Appears in WorkspaceSpec workspacespec Field Description name string Notification name type NotificationDestinationType notificationdestinationtype The type of the notification Must be one of the following values email generic microsoft teams slack enabled boolean Whether the notification configuration should be enabled or not Default true token string The token of the notification triggers NotificationTrigger notificationtrigger array The list of run events that trigger notifications Triggers are notifications that Terraform sends when a run transitions to a different state br br The following triggers notify you about health events assessment check failure assessment drifted assessment failed br br The following triggers notify you about run events run applying run completed run created run errored run needs attention run planning url string The URL of the notification Must match pattern https emailAddresses string array The list of email addresses that will receive notification emails It is only available for Terraform Enterprise users It is not available in HCP Terraform emailUsers string array The list of users belonging to the organization that will receive notification emails NotificationTrigger Underlying type string NotificationTrigger represents the notifications Terraform sends when a run transitions to a different state This resource must align with go tfe type NotificationTriggerType You must use one of the following values run applying assessment check failure run completed run created assessment drifted run errored assessment failed run needs attention run planning Appears in Notification notification OutputStatus Outputs status Appears in ModuleStatus modulestatus Field Description runID string Run ID of the latest run that updated the outputs PlanStatus Appears in WorkspaceStatus workspacestatus Field Description id string Latest plan only speculative plan HCP Terraform run ID terraformVersion string The version of Terraform to use for this run Project Project is the Schema for the projects API Field Description apiVersion string app terraform io v1alpha2 kind string Project kind string Kind is a string value representing the REST resource this object represents Servers may infer this from the endpoint the client submits requests to Cannot be updated In CamelCase More information https git k8s io community contributors devel sig architecture api conventions md types kinds apiVersion string APIVersion defines the versioned schema of this representation of an object Servers should convert recognized schemas to the latest internal value and may reject unrecognized values More information https git k8s io community contributors devel sig architecture api conventions md resources metadata ObjectMeta https kubernetes io docs reference generated kubernetes api v1 27 objectmeta v1 meta Refer to Kubernetes API documentation for fields of metadata spec ProjectSpec projectspec ProjectSpec ProjectSpec defines the desired state of Project More information terraform cloud docs workspaces organize workspaces with projects Appears in Project project Field Description organization string Organization name where the Workspace will be created More information terraform cloud docs users teams organizations organizations token Token token API Token to be used for API calls name string Name of the Project teamAccess ProjectTeamAccess projectteamaccess array HCP Terraform s access model is team based In order to perform an action within a HCP Terraform organization users must belong to a team that has been granted the appropriate permissions You can assign project specific permissions to teams More information br Project permissions terraform cloud docs workspaces organize workspaces with projects permissions Team project permissions terraform cloud docs users teams organizations permissions project permissions ProjectTeamAccess HCP Terraform s access model is team based In order to perform an action within a HCP Terraform organization users must belong to a team that has been granted the appropriate permissions You can assign project specific permissions to teams More information Project permissions API terraform cloud docs workspaces organize workspaces with projects permissions Project permissions terraform cloud docs users teams organizations permissions project permissions Appears in ProjectSpec projectspec Field Description team Team team Team to grant access More information terraform cloud docs users teams organizations teams access TeamProjectAccessType teamprojectaccesstype There are two ways to choose which permissions a given team has on a project fixed permission sets and custom permissions Must be one of the following values admin custom maintain read write More information br Project permissions terraform cloud docs users teams organizations permissions project permissions br General project permissions terraform cloud docs users teams organizations permissions general project permissions custom CustomProjectPermissions customprojectpermissions Custom permissions let you assign specific finer grained permissions to a team than the broader fixed permission sets provide More information terraform cloud docs users teams organizations permissions custom project permissions RemoteStateSharing RemoteStateSharing allows remote state access between workspaces By default new workspaces in HCP Terraform do not allow other workspaces to access their state More information terraform cloud docs workspaces state accessing state from other workspaces Appears in WorkspaceSpec workspacespec Field Description allWorkspaces boolean Allow access to the state for all workspaces within the same organization Default false workspaces ConsumerWorkspace consumerworkspace array Allow access to the state for specific workspaces within the same organization RunStatus Appears in ModuleStatus modulestatus WorkspaceStatus workspacestatus Field Description id string Current both active and finished HCP Terraform run ID configurationVersion string The configuration version of this run outputRunID string Run ID of the latest run that could update the outputs RunTrigger RunTrigger allows you to connect this workspace to one or more source workspaces These connections allow runs to queue automatically in this workspace on successful apply of runs in any of the source workspaces Only one of the fields ID or Name is allowed At least one of the fields ID or Name is mandatory More information terraform cloud docs workspaces settings run triggers Appears in WorkspaceSpec workspacespec Field Description id string Source Workspace ID Must match pattern ws a zA Z0 9 name string Source Workspace Name SSHKey SSH key used to clone Terraform modules Only one of the fields ID or Name is allowed At least one of the fields ID or Name is mandatory More information terraform cloud docs workspaces settings ssh keys Appears in WorkspaceSpec workspacespec Field Description id string SSH key ID Must match pattern sshkey a zA Z0 9 name string SSH key name Tag Underlying type string Tags allows you to correlate organize and even filter workspaces based on the assigned tags Tags must be one or more characters can include letters numbers colons hyphens and underscores and must begin and end with a letter or number Must match pattern A Za z0 9 A Za z0 9 Appears in WorkspaceSpec workspacespec TargetWorkspace TargetWorkspace is the name or ID of the workspace you want autoscale against Appears in AgentDeploymentAutoscaling agentdeploymentautoscaling Field Description id string Workspace ID name string Workspace Name wildcardName string Wildcard Name to match match workspace names using on name suffix prefix or both Team Teams are groups of HCP Terraform users within an organization If a user belongs to at least one team in an organization they are considered a member of that organization Only one of the fields ID or Name is allowed At least one of the fields ID or Name is mandatory More information terraform cloud docs users teams organizations teams Appears in ProjectTeamAccess projectteamaccess TeamAccess teamaccess Field Description id string Team ID Must match pattern team a zA Z0 9 name string Team name TeamAccess HCP Terraform workspaces can only be accessed by users with the correct permissions You can manage permissions for a workspace on a per team basis When a workspace is created only the owners team and teams with the manage workspaces permission can access it with full admin permissions These teams access can t be removed from a workspace More information terraform cloud docs workspaces settings access Appears in WorkspaceSpec workspacespec Field Description team Team team Team to grant access More information terraform cloud docs users teams organizations teams access string There are two ways to choose which permissions a given team has on a workspace fixed permission sets and custom permissions Must be one of the following values admin custom plan read write More information terraform cloud docs users teams organizations permissions workspace permissions custom CustomPermissions custompermissions Custom permissions let you assign specific finer grained permissions to a team than the broader fixed permission sets provide More information terraform cloud docs users teams organizations permissions custom workspace permissions Token Token refers to a Kubernetes Secret object within the same namespace as the Workspace object Appears in AgentPoolSpec agentpoolspec ModuleSpec modulespec ProjectSpec projectspec WorkspaceSpec workspacespec Field Description secretKeyRef SecretKeySelector https kubernetes io docs reference generated kubernetes api v1 27 secretkeyselector v1 core Selects a key of a secret in the workspace s namespace ValueFrom ValueFrom source for the variable s value Cannot be used if value is not empty Appears in Variable variable Field Description configMapKeyRef ConfigMapKeySelector https kubernetes io docs reference generated kubernetes api v1 27 configmapkeyselector v1 core Selects a key of a ConfigMap secretKeyRef SecretKeySelector https kubernetes io docs reference generated kubernetes api v1 27 secretkeyselector v1 core Selects a key of a Secret Variable Variables let you customize configurations modify Terraform s behavior and store information like provider credentials More information terraform cloud docs workspaces variables Appears in WorkspaceSpec workspacespec Field Description name string Name of the variable description string Description of the variable hcl boolean Parse this field as HashiCorp Configuration Language HCL This allows you to interpolate values at runtime Default false sensitive boolean Sensitive variables are never shown in the UI or API They may appear in Terraform logs if your configuration is designed to output them Default false value string Value of the variable valueFrom ValueFrom valuefrom Source for the variable s value Cannot be used if value is not empty VariableStatus Appears in WorkspaceStatus workspacestatus Field Description name string Name of the variable id string ID of the variable versionID string VersionID is a hash of the variable on the HCP Terraform end valueID string ValueID is a hash of the variable on the CRD end category string Category of the variable VersionControl VersionControl settings for the workspace s VCS repository enabling the UI VCS driven run workflow Omit this argument to utilize the CLI driven and API driven workflows where runs are not driven by webhooks on your VCS provider More information The UI and VCS driven run workflow terraform cloud docs run ui Connecting VCS providers to HCP Terraform terraform cloud docs vcs Appears in WorkspaceSpec workspacespec Field Description oAuthTokenID string The VCS Connection OAuth Connection Token to use Must match pattern ot a zA Z0 9 repository string A reference to your VCS repository in the format organization repository where organization and repository refer to the organization and repository in your VCS provider branch string The repository branch that Run will execute from This defaults to the repository s default branch e g main speculativePlans boolean Whether this workspace allows automatic speculative plans on PR Default true More information br Speculative plans on pull requests terraform cloud docs run ui speculative plans on pull requests br Speculative plans terraform cloud docs run remote operations speculative plans Workspace Workspace is the Schema for the workspaces API Field Description apiVersion string app terraform io v1alpha2 kind string Workspace kind string Kind is a string value representing the REST resource this object represents Servers may infer this from the endpoint the client submits requests to Cannot be updated In CamelCase More information https git k8s io community contributors devel sig architecture api conventions md types kinds apiVersion string APIVersion defines the versioned schema of this representation of an object Servers should convert recognized schemas to the latest internal value and may reject unrecognized values More information https git k8s io community contributors devel sig architecture api conventions md resources metadata ObjectMeta https kubernetes io docs reference generated kubernetes api v1 27 objectmeta v1 meta Refer to Kubernetes API documentation for fields of metadata spec WorkspaceSpec workspacespec WorkspaceAgentPool AgentPool allows HCP Terraform to communicate with isolated private or on premises infrastructure Only one of the fields ID or Name is allowed At least one of the fields ID or Name is mandatory More information terraform cloud docs agents Appears in WorkspaceSpec workspacespec Field Description id string Agent Pool ID Must match pattern apool a zA Z0 9 name string Agent Pool name WorkspaceProject Projects let you organize your workspaces into groups Only one of the fields ID or Name is allowed At least one of the fields ID or Name is mandatory More information terraform tutorials cloud projects Appears in WorkspaceSpec workspacespec Field Description id string Project ID Must match pattern prj a zA Z0 9 name string Project name WorkspaceRunTask Run tasks allow HCP Terraform to interact with external systems at specific points in the HCP Terraform run lifecycle Only one of the fields ID or Name is allowed At least one of the fields ID or Name is mandatory More information terraform cloud docs workspaces settings run tasks Appears in WorkspaceSpec workspacespec Field Description id string Run Task ID Must match pattern task a zA Z0 9 name string Run Task Name enforcementLevel string Run Task Enforcement Level Can be one of advisory or mandatory Default advisory Must be one of the following values advisory mandatory Default advisory stage string Run Task Stage Must be one of the following values pre apply pre plan post plan Default post plan WorkspaceSpec WorkspaceSpec defines the desired state of Workspace Appears in Workspace workspace Field Description name string Workspace name organization string Organization name where the Workspace will be created More information terraform cloud docs users teams organizations organizations token Token token API Token to be used for API calls applyMethod string Define either change will be applied automatically auto or require an operator to confirm manual Must be one of the following values auto manual Default manual More information terraform cloud docs workspaces settings auto apply and manual apply allowDestroyPlan boolean Allows a destroy plan to be created and applied Default true More information terraform cloud docs workspaces settings destruction and deletion description string Workspace description agentPool WorkspaceAgentPool workspaceagentpool HCP Terraform Agents allow HCP Terraform to communicate with isolated private or on premises infrastructure More information terraform cloud docs agents executionMode string Define where the Terraform code will be executed Must be one of the following values agent local remote Default remote More information terraform cloud docs workspaces settings execution mode runTasks WorkspaceRunTask workspaceruntask array Run tasks allow HCP Terraform to interact with external systems at specific points in the HCP Terraform run lifecycle More information terraform cloud docs workspaces settings run tasks tags Tag tag array Workspace tags are used to help identify and group together workspaces Tags must be one or more characters can include letters numbers colons hyphens and underscores and must begin and end with a letter or number teamAccess TeamAccess teamaccess array HCP Terraform workspaces can only be accessed by users with the correct permissions You can manage permissions for a workspace on a per team basis When a workspace is created only the owners team and teams with the manage workspaces permission can access it with full admin permissions These teams access can t be removed from a workspace More information terraform cloud docs workspaces settings access terraformVersion string The version of Terraform to use for this workspace If not specified the latest available version will be used Must match pattern d 1 d 1 2 d 1 2 More information cloud docs workspaces settings terraform version workingDirectory string The directory where Terraform will execute specified as a relative path from the root of the configuration directory More information cloud docs workspaces settings terraform working directory environmentVariables Variable variable array Terraform Environment variables for all plans and applies in this workspace Variables defined within a workspace always overwrite variables from variable sets that have the same type and the same key More information br Workspace variables terraform cloud docs workspaces variables br Environment variables terraform cloud docs workspaces variables environment variables terraformVariables Variable variable array Terraform variables for all plans and applies in this workspace Variables defined within a workspace always overwrite variables from variable sets that have the same type and the same key More information br Workspace variables terraform cloud docs workspaces variables br Terraform variables terraform cloud docs workspaces variables terraform variables remoteStateSharing RemoteStateSharing remotestatesharing Remote state access between workspaces By default new workspaces in HCP Terraform do not allow other workspaces to access their state More information terraform cloud docs workspaces state accessing state from other workspaces runTriggers RunTrigger runtrigger array Run triggers allow you to connect this workspace to one or more source workspaces These connections allow runs to queue automatically in this workspace on successful apply of runs in any of the source workspaces More information terraform cloud docs workspaces settings run triggers versionControl VersionControl versioncontrol Settings for the workspace s VCS repository enabling the UI VCS driven run workflow Omit this argument to utilize the CLI driven and API driven workflows where runs are not driven by webhooks on your VCS provider More information cloud docs run ui cloud docs vcs sshKey SSHKey sshkey SSH key used to clone Terraform modules More information terraform cloud docs workspaces settings ssh keys notifications Notification notification array Notifications allow you to send messages to other applications based on run and workspace events More information terraform cloud docs workspaces settings notifications project WorkspaceProject workspaceproject Projects let you organize your workspaces into groups Default default organization project More information terraform tutorials cloud projects deletionPolicy DeletionPolicy deletionpolicy The Deletion Policy specifies the behavior of the custom resource and its associated workspace when the custom resource is deleted br retain When you delete the custom resource the operator does not delete the workspace br soft Attempts to delete the associated workspace only if it does not contain any managed resources br destroy Executes a destroy operation to remove all resources managed by the associated workspace Once the destruction of these resources is successful the operator deletes the workspace and then deletes the custom resource br force Forcefully and immediately deletes the workspace and the custom resource br Default retain
terraform Learn how to automatically migrate state to HCP Terraform or Terraform Enterprise using the Terraform migrate CLI tool page title Terraform migrate HCP Terraform Terraform migrate Terraform migrate automatically migrates your Terraform Community Edition state to HCP Terraform or Terraform Enterprise It also updates your local configuration with any necessary changes and optionally creates a pull request to update your code repository
--- page_title: Terraform migrate - HCP Terraform description: >- Learn how to automatically migrate state to HCP Terraform or Terraform Enterprise using the Terraform migrate CLI tool --- # Terraform migrate Terraform migrate automatically migrates your Terraform Community Edition state to HCP Terraform or Terraform Enterprise. It also updates your local configuration with any necessary changes and optionally creates a pull request to update your code repository. ## Overview Complete the following steps to migrate Terraform state using the CLI: 1. Download and install `tf-migrate`: You can manually download and install or use Homebrew if you are on macOS. 1. `tf-migrate prepare`: This step scans the current working directory and generates Terraform configuration to migrate your state. The generated migration plan depends on the structure of your configuration. For more information, refer to [tf-migrate prepare](/terraform/cloud-docs/migrate/tf-migrate/reference/prepare). 1. `tf-migrate execute`: This step directs Terraform to run the `init`, `plan`, and `apply` commands to perform the migration to HCP Terraform or Terraform Enterprise. At the end of the migration, `tf-migrate` displays a summary of what it migrated, links to the workspaces it created, and, if configured, a link to the pull request it created. For more information, refer to [tf-migrate execute](/terraform/cloud-docs/migrate/tf-migrate/reference/execute). ## Install <Tabs> <Tab heading="Manual installation"> HashiCorp distributes Terraform migrate as a binary package. To install Terraform migrate, find the [appropriate binary](https://releases.hashicorp.com/tf-migrate/) for your operating system and download it as a zip archive. After you download Terraform migrate, unzip the archive. Terraform migrate runs as a single binary named `tf-migrate`. Finally, make sure that the `tf-migrate` binary is available in a directory that is in your system's `PATH`. ### Verify the installation Every build of Terraform migrate includes a `SHA256SUMS` and a `SHA256SUMS.sig` file to validate your downloaded binary. Refer to the [verify HashiCorp binary downloads tutorial](https://developer.hashicorp.com/well-architected-framework/operational-excellence/verify-hashicorp-binary) for more information. </Tab> <Tab heading="Homebrew of macOS"> [Homebrew](https://brew.sh/) is a free and open-source package management system for macOS. You can install the official [Terraform migrate](https://github.com/hashicorp/homebrew-tap) formula from the terminal. First, install the HashiCorp tap, a repository of all our Homebrew packages. ``` $ brew tap hashicorp/tap ``` Now, install Terraform migrate with the `hashicorp/tap/tf-migrate` formula. ``` $ brew install hashicorp/tap/tf-migrate ``` </Tab> </Tabs> ## Authentication Terraform migrate uses your locally configured Terraform CLI API token. If you have not authenticated your local Terraform installation with HCP Terraform, use the `terraform login` command to create an authentication token. ``` $ terraform login Terraform will request an API token for app.terraform.io using your browser. If login is successful, Terraform will store the token in plain text in the following file for use by subsequent commands: /Users/redacted/.terraform.d/credentials.tfrc.json Do you want to proceed? Only 'yes' will be accepted to confirm. Enter a value: yes ``` Terraform opens a browser to the HCP Terraform login screen. Enter a token name in the web UI, or leave the default name. Click **Create API token** to generate the authentication token. HCP Terraform only displays your token once. Copy this token, then when the Terraform CLI prompts you, paste the user token exactly once into your terminal. Press **Enter** to complete the authentication process. Terraform migrate uses the GitHub API to create a pull request to update your configuration. Set the `GITHUB_TOKEN` environment variable to provide your GitHub API token. Your token must have the `repo` scope. ``` $ export GITHUB_TOKEN=<TOKEN> ``` ## Logging You can enable detailed logging by setting the `TF_MIGRATE_ENABLE_LOG` environment variable to `true`. When you enable this setting, Terraform migrate writes the logs to the following locations, depending on your operating system: | Platform | Location | | -------- | -------- | | macOS/Linux | `/Users/<username>/.tf-migrate/logs/<commandName>/<date>.log` | | Windows | `C:\Users\<username>\.tf-migrate\logs\<commandName>\<date>.log` | You can set the `TF_MIGRATE_LOG_LEVEL` environment variable to one of the following values to change the verbosity of the logs (in order of decreasing verbosity): - `TRACE` - `DEBUG` - `INFO` - `WARN` - `ERROR
terraform
page title Terraform migrate HCP Terraform description Learn how to automatically migrate state to HCP Terraform or Terraform Enterprise using the Terraform migrate CLI tool Terraform migrate Terraform migrate automatically migrates your Terraform Community Edition state to HCP Terraform or Terraform Enterprise It also updates your local configuration with any necessary changes and optionally creates a pull request to update your code repository Overview Complete the following steps to migrate Terraform state using the CLI 1 Download and install tf migrate You can manually download and install or use Homebrew if you are on macOS 1 tf migrate prepare This step scans the current working directory and generates Terraform configuration to migrate your state The generated migration plan depends on the structure of your configuration For more information refer to tf migrate prepare terraform cloud docs migrate tf migrate reference prepare 1 tf migrate execute This step directs Terraform to run the init plan and apply commands to perform the migration to HCP Terraform or Terraform Enterprise At the end of the migration tf migrate displays a summary of what it migrated links to the workspaces it created and if configured a link to the pull request it created For more information refer to tf migrate execute terraform cloud docs migrate tf migrate reference execute Install Tabs Tab heading Manual installation HashiCorp distributes Terraform migrate as a binary package To install Terraform migrate find the appropriate binary https releases hashicorp com tf migrate for your operating system and download it as a zip archive After you download Terraform migrate unzip the archive Terraform migrate runs as a single binary named tf migrate Finally make sure that the tf migrate binary is available in a directory that is in your system s PATH Verify the installation Every build of Terraform migrate includes a SHA256SUMS and a SHA256SUMS sig file to validate your downloaded binary Refer to the verify HashiCorp binary downloads tutorial https developer hashicorp com well architected framework operational excellence verify hashicorp binary for more information Tab Tab heading Homebrew of macOS Homebrew https brew sh is a free and open source package management system for macOS You can install the official Terraform migrate https github com hashicorp homebrew tap formula from the terminal First install the HashiCorp tap a repository of all our Homebrew packages brew tap hashicorp tap Now install Terraform migrate with the hashicorp tap tf migrate formula brew install hashicorp tap tf migrate Tab Tabs Authentication Terraform migrate uses your locally configured Terraform CLI API token If you have not authenticated your local Terraform installation with HCP Terraform use the terraform login command to create an authentication token terraform login Terraform will request an API token for app terraform io using your browser If login is successful Terraform will store the token in plain text in the following file for use by subsequent commands Users redacted terraform d credentials tfrc json Do you want to proceed Only yes will be accepted to confirm Enter a value yes Terraform opens a browser to the HCP Terraform login screen Enter a token name in the web UI or leave the default name Click Create API token to generate the authentication token HCP Terraform only displays your token once Copy this token then when the Terraform CLI prompts you paste the user token exactly once into your terminal Press Enter to complete the authentication process Terraform migrate uses the GitHub API to create a pull request to update your configuration Set the GITHUB TOKEN environment variable to provide your GitHub API token Your token must have the repo scope export GITHUB TOKEN TOKEN Logging You can enable detailed logging by setting the TF MIGRATE ENABLE LOG environment variable to true When you enable this setting Terraform migrate writes the logs to the following locations depending on your operating system Platform Location macOS Linux Users username tf migrate logs commandName date log Windows C Users username tf migrate logs commandName date log You can set the TF MIGRATE LOG LEVEL environment variable to one of the following values to change the verbosity of the logs in order of decreasing verbosity TRACE DEBUG INFO WARN ERROR
terraform tf migrate prepare page title tf migrate prepare Terraform migrate HCP Terraform Gather information and create a plan to migrate your Terraform Community Edition state The tf migrate prepare command recursively scans the current directory for Terraform state files then generates new Terraform configuration to migrate the state to HCP Terraform or Terraform Enterprise
--- page_title: tf-migrate prepare - Terraform migrate - HCP Terraform description: >- Gather information and create a plan to migrate your Terraform Community Edition state. --- # tf-migrate prepare The `tf-migrate prepare` command recursively scans the current directory for Terraform state files, then generates new Terraform configuration to migrate the state to HCP Terraform or Terraform Enterprise. ## Usage ``` $ tf-migrate prepare [options] ``` ## Description The `tf-migrate prepare` command prompts you for the following information: - The HCP Terraform or Terraform Enterprise organization to migrate your state to. - If you would like to create a new branch named `hcp-migrate-main`. - If you would like it to automatically create a pull request with the updated code change when the migration is complete. After you run the `prepare` command, Terraform migrate generates a new Terraform configuration in the `hcp-migrate-config` directory to perform the migration. This configuration creates the following resources: - One workspace per state file - One project to store all workspaces - A new local git branch if you responded to the prompt to create a new branch with `yes`. - A new pull request in the remote git repository if you responded to the prompt to create a pull request with `yes`. The `tf-migrate` CLI tool adds the generated configuration to the `.gitignore` file so that the configuration is not committed to source control. Terraform migrate creates the following structure in HCP Terraform or Terraform Enterprise depending on your local configuration: | Source | Result | | :---- | :---- | | Single configuration, single state | Single HCP workspace | | Single configuration, multiple states for each Community Edition workspace | One HCP workspace per state | | Multiple configurations, one state per configuration | One HCP workspace per configuration | | Multiple configurations, multiple states per configuration | One HCP workspace per combination of configuration and state | ## Example The following configuration uses the AWS S3 backend and has a single state file. <CodeBlockConfig hideClipboard> ``` . ├── LICENSE ├── README.md └── main.tf ``` </CodeBlockConfig> The `tf-migrate prepare` command generates the configuration to migrate this state to a single HCP Terraform workspace. <CodeBlockConfig hideClipboard> ``` $ tf-migrate prepare ✓ Current working directory: /tmp/backend-test/learn-terraform-migrate ✓ Environment readiness checks completed ✓ Found 3 HCP Terraform organizations ┌────────────────────────────┐ │ Available Orgs │ ├────────────────────────────┤ │ my-org-1 │ │ my-org-2 │ │ my-org-3 │ └────────────────────────────┘ Enter the name of the HCP Terraform organization to migrate to: my-org-1 ✓ You have selected organization my-org-1 for migration ✓ Found 1 directories with Terraform files ┌────────────────────────────────┐ │ Terraform File Directories │ ├────────────────────────────────┤ │ learn-terraform-migrate │ └────────────────────────────────┘ Create a local branch named hcp-migrate-main from the current branch main: ... ? Only 'yes or no' will be accepted as input. Type 'yes' to approve the step Type 'no' to to skip Enter a value: yes ✓ Successfully created branch hcp-migrate-main Do you want to open a pull request from hcp-migrate-main ... ? Only 'yes or no' will be accepted as input. Type 'yes' to approve the step Type 'no' to to skip Enter a value: yes ✓ Migration config generation completed ``` </CodeBlockConfig> ## Available options You can include the following flags when you run the `tf-migrate prepare` command: | Option | Description | Default | Required | | ------ | ----------- | ------- | -------- | | `-hostname` | The hostname of your Terraform Enterprise server. If you do not provide a hostname, Terraform migrate defaults to HCP Terraform. | `app.terraform.io` | No
terraform
page title tf migrate prepare Terraform migrate HCP Terraform description Gather information and create a plan to migrate your Terraform Community Edition state tf migrate prepare The tf migrate prepare command recursively scans the current directory for Terraform state files then generates new Terraform configuration to migrate the state to HCP Terraform or Terraform Enterprise Usage tf migrate prepare options Description The tf migrate prepare command prompts you for the following information The HCP Terraform or Terraform Enterprise organization to migrate your state to If you would like to create a new branch named hcp migrate main If you would like it to automatically create a pull request with the updated code change when the migration is complete After you run the prepare command Terraform migrate generates a new Terraform configuration in the hcp migrate config directory to perform the migration This configuration creates the following resources One workspace per state file One project to store all workspaces A new local git branch if you responded to the prompt to create a new branch with yes A new pull request in the remote git repository if you responded to the prompt to create a pull request with yes The tf migrate CLI tool adds the generated configuration to the gitignore file so that the configuration is not committed to source control Terraform migrate creates the following structure in HCP Terraform or Terraform Enterprise depending on your local configuration Source Result Single configuration single state Single HCP workspace Single configuration multiple states for each Community Edition workspace One HCP workspace per state Multiple configurations one state per configuration One HCP workspace per configuration Multiple configurations multiple states per configuration One HCP workspace per combination of configuration and state Example The following configuration uses the AWS S3 backend and has a single state file CodeBlockConfig hideClipboard LICENSE README md main tf CodeBlockConfig The tf migrate prepare command generates the configuration to migrate this state to a single HCP Terraform workspace CodeBlockConfig hideClipboard tf migrate prepare Current working directory tmp backend test learn terraform migrate Environment readiness checks completed Found 3 HCP Terraform organizations Available Orgs my org 1 my org 2 my org 3 Enter the name of the HCP Terraform organization to migrate to my org 1 You have selected organization my org 1 for migration Found 1 directories with Terraform files Terraform File Directories learn terraform migrate Create a local branch named hcp migrate main from the current branch main Only yes or no will be accepted as input Type yes to approve the step Type no to to skip Enter a value yes Successfully created branch hcp migrate main Do you want to open a pull request from hcp migrate main Only yes or no will be accepted as input Type yes to approve the step Type no to to skip Enter a value yes Migration config generation completed CodeBlockConfig Available options You can include the following flags when you run the tf migrate prepare command Option Description Default Required hostname The hostname of your Terraform Enterprise server If you do not provide a hostname Terraform migrate defaults to HCP Terraform app terraform io No
terraform private module registry terraform cloud docs registry policy sets terraform cloud docs policy enforcement manage policy sets tfc only true page title GitHub com GitHub App VCS Providers HCP Terraform Learn how to use GitHub com repositories with workspaces and private registry modules without requiring an organization owner to configure an OAuth connection
--- page_title: GitHub.com (GitHub App) - VCS Providers - HCP Terraform tfc_only: true description: >- Learn how to use GitHub.com repositories with workspaces and private registry modules, without requiring an organization owner to configure an OAuth connection. --- [private module registry]: /terraform/cloud-docs/registry [policy sets]: /terraform/cloud-docs/policy-enforcement/manage-policy-sets [vcs settings]: /terraform/cloud-docs/workspaces/settings/vcs [create]: /terraform/cloud-docs/workspaces/create [owners]: /terraform/cloud-docs/users-teams-organizations/teams#the-owners-team # Configuration-Free GitHub Usage These instructions are for using repositories from GitHub.com with HCP Terraform workspaces and private registry modules, without requiring an organization owner to configure an OAuth connection. This method uses a preconfigured GitHub App, and only works with GitHub.com. There are separate instructions for connecting to [GitHub.com via OAuth](/terraform/cloud-docs/vcs/github), connecting to [GitHub Enterprise](/terraform/cloud-docs/vcs/github-enterprise), and connecting to [other supported VCS providers.](/terraform/cloud-docs/vcs) -> **Note:** This VCS Provider is only available on HCP Terraform. If you are using Terraform Enterprise, you can follow the instructions for creating [GitHub App for TFE](/terraform/enterprise/admin/application/github-app-integration) or connecting to [GitHub.com via OAuth](/terraform/cloud-docs/vcs/github). ## Using GitHub Repositories Choose "GitHub.com" on the "Connect to a version control provider" screen, which is shown when [creating a new workspace][create] or [changing a workspace's VCS connection][vcs settings]. Authorize access to GitHub if necessary. On the next screen, select a GitHub account or organization from the drop-down menu (or add a new organization) and choose a repository from the list. The controls on the "Connect to a version control provider" screen can vary, depending on your permissions and your organization's settings: - In organizations with no VCS connections configured: - Users with permission to manage VCS settings ([more about permissions](/terraform/cloud-docs/users-teams-organizations/permissions)) will see several drop-down menus, sorted by product family. Choose "GitHub.com" (_not_ "GitHub.com (Custom)") from the GitHub menu. - Other users will see a "GitHub" button. - In organizations with an existing VCS connection, only the connected providers are shown. Click the "Connect to a different VCS" link to reveal the provider menus (if you can manage VCS settings) or the GitHub button (others). [permissions-citation]: #intentionally-unused---keep-for-maintainers ## GitHub Permissions When using the Terraform Cloud GitHub App, each HCP Terraform user authenticates individually, and can use GitHub resources within HCP Terraform according to their own GitHub organization memberships and access permissions. -> **Note:** This is different from OAuth connections, where an HCP Terraform organization always acts as one particular GitHub user. To enable this personalized access, HCP Terraform requests two kinds of permissions: - **Per user:** Each HCP Terraform user must _authorize_ HCP Terraform for their own GitHub account. This lets HCP Terraform determine which organizations and repositories they have access to. - **Per GitHub organization:** Each GitHub organization (or personal account) must _install_ the Terraform Cloud app, either globally or for specific repositories. This allows HCP Terraform to access repository contents and events. Individual HCP Terraform users can access GitHub repositories where both of the following are true: - The user has at least read access to that repository on GitHub. - The repository's owner has installed the Terraform Cloud app and allowed it to access that repository. This means that different HCP Terraform users within the same organization can see different sets of repositories available for their workspaces. ### Authorizing HCP Terraform requests GitHub authorization from each user, displaying a pop-up window the first time they choose GitHub on the "Connect to a version control provider" screen. ![Screenshot: GitHub asking whether you want to authorize "Terraform Cloud by HashiCorp".](/img/docs/gh-app-authorize.png) Once you authorize the app, you can use GitHub in any of your HCP Terraform organizations without needing to re-authorize. After installing the GitHub App and creating your VCS provider instance, you cannot reinstall the application again. However, you can modify your existing GitHub App configuration. If you are a repository owner, you can adjust an existing Github App configuration by: 1. Click a repository's **Settings** tab. 1. Select **GitHub Apps** in the sidebar. 1. Next to **Terraform Cloud**, click **Configure**. 1. Underneath **Repository access**, adjust the repositories your GitHub app can access. Now that your Github app has access to your desired repository, you can [create a new workspace](/terraform/cloud-docs/workspaces/create#create-a-workspace) with your existing, newly updated GitHub App connection. You can also adjust your GitHub App's access within HCP Terraform itself. Whenever you create a new workspace, you can choose which organizations or repositories to install the GitHub App into. To adjust your GitHub App's configuration, create a new workspace: 1. Click **Workspaces** in the sidebar. 1. Click **New**, then select **Workspace**. 1. Choose the project where you want to create your workspace, then click **Create**. 1. Click **Version Control Workflow**, then choose the **GitHub App**. 1. Click on your GitHub organization's name to reveal a dropdown, then select **Add another organization** to configure the resources your GitHub app has access to. #### Deauthorizing You can use GitHub's web interface to deauthorize HCP Terraform for your GitHub account. Open your GitHub personal settings, then go to the "Applications" section and the "Authorized GitHub Apps" tab. (Or, browse directly to `https://github.com/settings/apps/authorizations`.) Click the **Revoke** button for HCP Terraform to deauthorize it. After deauthorizing, you won't be able to connect GitHub repositories to HCP Terraform workspaces until you authorize again. Existing connections will still work. ### Installing HCP Terraform requests installation when a user chooses "Add another organization" from the repository list's organization menu. The installation interface is a pop-up GitHub window, which lists your personal account and the organizations you can access. Note that installing an app for a GitHub organization requires appropriate organization permissions; see [GitHub's permissions documentation](https://help.github.com/en/github/setting-up-and-managing-organizations-and-teams/permission-levels-for-an-organization#github-app-managers) for details. ![Screenshot: GitHub asking which organization or account to install the Terraform Cloud app in](/img/docs/gh-app-install-pick.png) For a given organization or account, the app can be installed globally or only for specific repositories. Once the application is installed for an organization (or a subset of its repositories), its members can select any affected repositories they have access to when using HCP Terraform. Access is not restricted to a specific HCP Terraform organization; members of a GitHub organization can use its repositories in any HCP Terraform organization they belong to. #### Configuring and Uninstalling You can use GitHub's web interface to configure or uninstall HCP Terraform for an organization or account. Open your GitHub personal settings or organization settings, then go to the **Applications** section and the *Installed GitHub Apps** tab. Click the **Configure** button for HCP Terraform to change its settings. In the app's settings you can change which repositories HCP Terraform has access to, or uninstall it entirely. If you disallow access to a repository that is currently connected to any HCP Terraform workspaces, those workspaces will be unable to retrieve configuration versions until you change their VCS settings and connect them to an allowed repository. ## Feature Limitations You can use the Terraform Cloud GitHub App to create workspaces and private registry modules from the UI, the API, or the TFE Terraform provider. The following tools can use any version of HCP Terraform to access these features, but require a minimum version of Terraform Enterprise: - For the UI, use Terraform Enterprise v202302-1 or above. - For the API, use Terraform Enterprise v202303-1 or above. - Using at least v1.19.0 of [`go_tfe`](https://github.com/hashicorp/go-tfe), use Terraform Enterprise v202303-1 and above. - Using at least v0.43.0 of [`tfe_provider`](https://registry.terraform.io/providers/hashicorp/tfe/latest/docs), use Terraform Enterprise v202303-1 and above. Once you decide to start using these other features, a user with permission to manage VCS settings can configure [GitHub OAuth access](/terraform/cloud-docs/vcs/github) for your organization. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) [permissions-citation]: #intentionally-unused---keep-for-maintainers
terraform
page title GitHub com GitHub App VCS Providers HCP Terraform tfc only true description Learn how to use GitHub com repositories with workspaces and private registry modules without requiring an organization owner to configure an OAuth connection private module registry terraform cloud docs registry policy sets terraform cloud docs policy enforcement manage policy sets vcs settings terraform cloud docs workspaces settings vcs create terraform cloud docs workspaces create owners terraform cloud docs users teams organizations teams the owners team Configuration Free GitHub Usage These instructions are for using repositories from GitHub com with HCP Terraform workspaces and private registry modules without requiring an organization owner to configure an OAuth connection This method uses a preconfigured GitHub App and only works with GitHub com There are separate instructions for connecting to GitHub com via OAuth terraform cloud docs vcs github connecting to GitHub Enterprise terraform cloud docs vcs github enterprise and connecting to other supported VCS providers terraform cloud docs vcs Note This VCS Provider is only available on HCP Terraform If you are using Terraform Enterprise you can follow the instructions for creating GitHub App for TFE terraform enterprise admin application github app integration or connecting to GitHub com via OAuth terraform cloud docs vcs github Using GitHub Repositories Choose GitHub com on the Connect to a version control provider screen which is shown when creating a new workspace create or changing a workspace s VCS connection vcs settings Authorize access to GitHub if necessary On the next screen select a GitHub account or organization from the drop down menu or add a new organization and choose a repository from the list The controls on the Connect to a version control provider screen can vary depending on your permissions and your organization s settings In organizations with no VCS connections configured Users with permission to manage VCS settings more about permissions terraform cloud docs users teams organizations permissions will see several drop down menus sorted by product family Choose GitHub com not GitHub com Custom from the GitHub menu Other users will see a GitHub button In organizations with an existing VCS connection only the connected providers are shown Click the Connect to a different VCS link to reveal the provider menus if you can manage VCS settings or the GitHub button others permissions citation intentionally unused keep for maintainers GitHub Permissions When using the Terraform Cloud GitHub App each HCP Terraform user authenticates individually and can use GitHub resources within HCP Terraform according to their own GitHub organization memberships and access permissions Note This is different from OAuth connections where an HCP Terraform organization always acts as one particular GitHub user To enable this personalized access HCP Terraform requests two kinds of permissions Per user Each HCP Terraform user must authorize HCP Terraform for their own GitHub account This lets HCP Terraform determine which organizations and repositories they have access to Per GitHub organization Each GitHub organization or personal account must install the Terraform Cloud app either globally or for specific repositories This allows HCP Terraform to access repository contents and events Individual HCP Terraform users can access GitHub repositories where both of the following are true The user has at least read access to that repository on GitHub The repository s owner has installed the Terraform Cloud app and allowed it to access that repository This means that different HCP Terraform users within the same organization can see different sets of repositories available for their workspaces Authorizing HCP Terraform requests GitHub authorization from each user displaying a pop up window the first time they choose GitHub on the Connect to a version control provider screen Screenshot GitHub asking whether you want to authorize Terraform Cloud by HashiCorp img docs gh app authorize png Once you authorize the app you can use GitHub in any of your HCP Terraform organizations without needing to re authorize After installing the GitHub App and creating your VCS provider instance you cannot reinstall the application again However you can modify your existing GitHub App configuration If you are a repository owner you can adjust an existing Github App configuration by 1 Click a repository s Settings tab 1 Select GitHub Apps in the sidebar 1 Next to Terraform Cloud click Configure 1 Underneath Repository access adjust the repositories your GitHub app can access Now that your Github app has access to your desired repository you can create a new workspace terraform cloud docs workspaces create create a workspace with your existing newly updated GitHub App connection You can also adjust your GitHub App s access within HCP Terraform itself Whenever you create a new workspace you can choose which organizations or repositories to install the GitHub App into To adjust your GitHub App s configuration create a new workspace 1 Click Workspaces in the sidebar 1 Click New then select Workspace 1 Choose the project where you want to create your workspace then click Create 1 Click Version Control Workflow then choose the GitHub App 1 Click on your GitHub organization s name to reveal a dropdown then select Add another organization to configure the resources your GitHub app has access to Deauthorizing You can use GitHub s web interface to deauthorize HCP Terraform for your GitHub account Open your GitHub personal settings then go to the Applications section and the Authorized GitHub Apps tab Or browse directly to https github com settings apps authorizations Click the Revoke button for HCP Terraform to deauthorize it After deauthorizing you won t be able to connect GitHub repositories to HCP Terraform workspaces until you authorize again Existing connections will still work Installing HCP Terraform requests installation when a user chooses Add another organization from the repository list s organization menu The installation interface is a pop up GitHub window which lists your personal account and the organizations you can access Note that installing an app for a GitHub organization requires appropriate organization permissions see GitHub s permissions documentation https help github com en github setting up and managing organizations and teams permission levels for an organization github app managers for details Screenshot GitHub asking which organization or account to install the Terraform Cloud app in img docs gh app install pick png For a given organization or account the app can be installed globally or only for specific repositories Once the application is installed for an organization or a subset of its repositories its members can select any affected repositories they have access to when using HCP Terraform Access is not restricted to a specific HCP Terraform organization members of a GitHub organization can use its repositories in any HCP Terraform organization they belong to Configuring and Uninstalling You can use GitHub s web interface to configure or uninstall HCP Terraform for an organization or account Open your GitHub personal settings or organization settings then go to the Applications section and the Installed GitHub Apps tab Click the Configure button for HCP Terraform to change its settings In the app s settings you can change which repositories HCP Terraform has access to or uninstall it entirely If you disallow access to a repository that is currently connected to any HCP Terraform workspaces those workspaces will be unable to retrieve configuration versions until you change their VCS settings and connect them to an allowed repository Feature Limitations You can use the Terraform Cloud GitHub App to create workspaces and private registry modules from the UI the API or the TFE Terraform provider The following tools can use any version of HCP Terraform to access these features but require a minimum version of Terraform Enterprise For the UI use Terraform Enterprise v202302 1 or above For the API use Terraform Enterprise v202303 1 or above Using at least v1 19 0 of go tfe https github com hashicorp go tfe use Terraform Enterprise v202303 1 and above Using at least v0 43 0 of tfe provider https registry terraform io providers hashicorp tfe latest docs use Terraform Enterprise v202303 1 and above Once you decide to start using these other features a user with permission to manage VCS settings can configure GitHub OAuth access terraform cloud docs vcs github for your organization More about permissions terraform cloud docs users teams organizations permissions permissions citation intentionally unused keep for maintainers
terraform page title GitLab com VCS Providers HCP Terraform These instructions are for using GitLab com for HCP Terraform s VCS features GitLab CE and GitLab EE have separate instructions terraform cloud docs vcs gitlab eece as do the other supported VCS providers terraform cloud docs vcs Learn how to use GitLab com for VCS features Configuring GitLab com Access
--- page_title: GitLab.com - VCS Providers - HCP Terraform description: >- Learn how to use GitLab.com for VCS features. --- # Configuring GitLab.com Access These instructions are for using GitLab.com for HCP Terraform's VCS features. [GitLab CE and GitLab EE have separate instructions,](/terraform/cloud-docs/vcs/gitlab-eece) as do the [other supported VCS providers.](/terraform/cloud-docs/vcs) Configuring a new VCS provider requires permission to manage VCS settings for the organization. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) [permissions-citation]: #intentionally-unused---keep-for-maintainers Connecting HCP Terraform to your VCS involves four steps: | On your VCS | On HCP Terraform | | ------------------------------------------------------------------------------ | --------------------------------------------------------------------------- | |   | Create a new connection in HCP Terraform. Get redirect URI. | | Register your HCP Terraform organization as a new app. Provide redirect URI. |   | |   | Provide HCP Terraform with application ID and secret. Request VCS access. | | Approve access request. |   | The rest of this page explains the GitLab.com versions of these steps. -> **Note:** Alternately, you can skip the OAuth configuration process and authenticate with a personal access token. This requires using HCP Terraform's API. For details, see [the OAuth Clients API page](/terraform/cloud-docs/api-docs/oauth-clients). ## Step 1: On HCP Terraform, Begin Adding a New VCS Provider 1. Go to your organization's settings and then click **Providers**. The **VCS Providers** page appears. 1. Click **Add VCS Provider**. The **VCS Providers** page appears. 1. Select **GitLab** and then select **GitLab.com** from the menu. The page moves to the next step. 1. Locate the "Redirect URI" and copy it to your clipboard; you'll paste it in the next step. Leave the page open in a browser tab. In the next step you will copy values from this page, and in later steps you will continue configuring HCP Terraform. ## Step 2: On GitLab, Create a New Application 1. In a new browser tab, open [gitlab.com](https://gitlab.com) and log in as whichever account you want HCP Terraform to act as. For most organizations this should be a dedicated service user, but a personal account will also work. ~> **Important:** The account you use for connecting HCP Terraform **must have Maintainer access** to any shared repositories of Terraform configurations, since creating webhooks requires Maintainer permissions. Refer to [the GitLab documentation](https://docs.gitlab.com/ee/user/permissions.html#project-members-permissions) for details. 1. Navigate to GitLab's [User Settings > Applications](https://gitlab.com/-/profile/applications) page. This page is located at <https://gitlab.com/-/profile/applications>. You can also reach it through GitLab's menus: - Click your profile picture and choose "Settings." - Click "Applications." 1. This page has a list of applications and a form for adding new ones. The form has two text fields and some checkboxes. Fill out the fields and checkboxes with the corresponding values currently displayed in your HCP Terraform browser tab. HCP Terraform lists the values in the order they appear, and includes controls for copying values to your clipboard. Fill out the form as follows: | Field | Value | | ----------------------- | ------------------------------------------------------------------------------------------------ | | Name | HCP Terraform (`<YOUR ORGANIZATION NAME>`) | | Redirect URI | `https://app.terraform.io/<YOUR CALLBACK URL>`, the redirect URI you copied from HCP Terraform | | Confidential (checkbox) | ✔️ (enabled) | | Scopes (all checkboxes) | api | 1. Click the "Save application" button, which creates the application and takes you to its page. 1. Leave this page open in a browser tab. In the next step, you will copy and paste the unique **Application ID** and **Secret.** ## Step 3: On HCP Terraform, Set up Your Provider 1. Enter the **Application ID** and **Secret** from the previous step, as well as an option **Name** for this VCS connection. 1. Click **Connect and continue.** This takes you to a page on GitLab.com, which asks if you want to authorize the app. 1. Click the green **Authorize** button at the bottom of the authorization page. ## Step 4: On HCP Terraform, Configure Advanced Settings (Optional) The settings in this section are optional. The Advanced Settings you can configure are: - **Scope of VCS Provider** - You can configure which workspaces can use repositories from this VCS provider. By default the **All Projects** option is selected, meaning this VCS provider is available to be used by all workspaces in the organization. - **Set up SSH Keypair** - Most organizations will not need to add an SSH key. However, if the organization repositories include Git submodules that can only be accessed via SSH, an SSH key can be added along with the OAuth credentials. You can add or update the SSH key at a later time. ### If You Don't Need to Configure Advanced Settings: 1. Click the **Skip and Finish** button. This returns you to HCP Terraform's VCS Provider page, which now includes your new GitLab client. ### If You Need to Limit the Scope of this VCS Provider: 1. Select the **Selected Projects** option and use the text field that appears to search for and select projects to enable. All current and future workspaces for any selected projects can use repositories from this VCS Provider. 1. Click the **Update VCS Provider** button to save your selections. ### If You Do Need an SSH Keypair: #### Important Notes - SSH will only be used to clone Git submodules. All other Git operations will still use HTTPS. - Do not use your personal SSH key to connect HCP Terraform and GitLab; generate a new one or use an existing key reserved for service access. - In the following steps, you must provide HCP Terraform with the private key. Although HCP Terraform does not display the text of the key to users after it is entered, it retains it and will use it when authenticating to GitLab. - **Protect this private key carefully.** It can push code to the repositories you use to manage your infrastructure. Take note of your organization's policies for protecting important credentials and be sure to follow them. 1. On a secure workstation, create an SSH keypair that HCP Terraform can use to connect to GitLab.com. The exact command depends on your OS, but is usually something like: `ssh-keygen -t rsa -m PEM -f "/Users/<NAME>/.ssh/service_terraform" -C "service_terraform_enterprise"` This creates a `service_terraform` file with the private key, and a `service_terraform.pub` file with the public key. This SSH key **must have an empty passphrase**. HCP Terraform cannot use SSH keys that require a passphrase. 1. While logged into the GitLab.com account you want HCP Terraform to act as, navigate to the SSH Keys settings page, add a new SSH key and paste the value of the SSH public key you just created. 1. In HCP Terraform's **Add VCS Provider** page, paste the text of the **SSH private key** you just created, and click the **Add SSH Key** button. ## Finished At this point, GitLab.com access for HCP Terraform is fully configured, and you can create Terraform workspaces based on your organization's shared repositories.
terraform
page title GitLab com VCS Providers HCP Terraform description Learn how to use GitLab com for VCS features Configuring GitLab com Access These instructions are for using GitLab com for HCP Terraform s VCS features GitLab CE and GitLab EE have separate instructions terraform cloud docs vcs gitlab eece as do the other supported VCS providers terraform cloud docs vcs Configuring a new VCS provider requires permission to manage VCS settings for the organization More about permissions terraform cloud docs users teams organizations permissions permissions citation intentionally unused keep for maintainers Connecting HCP Terraform to your VCS involves four steps On your VCS On HCP Terraform Create a new connection in HCP Terraform Get redirect URI Register your HCP Terraform organization as a new app Provide redirect URI Provide HCP Terraform with application ID and secret Request VCS access Approve access request The rest of this page explains the GitLab com versions of these steps Note Alternately you can skip the OAuth configuration process and authenticate with a personal access token This requires using HCP Terraform s API For details see the OAuth Clients API page terraform cloud docs api docs oauth clients Step 1 On HCP Terraform Begin Adding a New VCS Provider 1 Go to your organization s settings and then click Providers The VCS Providers page appears 1 Click Add VCS Provider The VCS Providers page appears 1 Select GitLab and then select GitLab com from the menu The page moves to the next step 1 Locate the Redirect URI and copy it to your clipboard you ll paste it in the next step Leave the page open in a browser tab In the next step you will copy values from this page and in later steps you will continue configuring HCP Terraform Step 2 On GitLab Create a New Application 1 In a new browser tab open gitlab com https gitlab com and log in as whichever account you want HCP Terraform to act as For most organizations this should be a dedicated service user but a personal account will also work Important The account you use for connecting HCP Terraform must have Maintainer access to any shared repositories of Terraform configurations since creating webhooks requires Maintainer permissions Refer to the GitLab documentation https docs gitlab com ee user permissions html project members permissions for details 1 Navigate to GitLab s User Settings Applications https gitlab com profile applications page This page is located at https gitlab com profile applications You can also reach it through GitLab s menus Click your profile picture and choose Settings Click Applications 1 This page has a list of applications and a form for adding new ones The form has two text fields and some checkboxes Fill out the fields and checkboxes with the corresponding values currently displayed in your HCP Terraform browser tab HCP Terraform lists the values in the order they appear and includes controls for copying values to your clipboard Fill out the form as follows Field Value Name HCP Terraform YOUR ORGANIZATION NAME Redirect URI https app terraform io YOUR CALLBACK URL the redirect URI you copied from HCP Terraform Confidential checkbox enabled Scopes all checkboxes api 1 Click the Save application button which creates the application and takes you to its page 1 Leave this page open in a browser tab In the next step you will copy and paste the unique Application ID and Secret Step 3 On HCP Terraform Set up Your Provider 1 Enter the Application ID and Secret from the previous step as well as an option Name for this VCS connection 1 Click Connect and continue This takes you to a page on GitLab com which asks if you want to authorize the app 1 Click the green Authorize button at the bottom of the authorization page Step 4 On HCP Terraform Configure Advanced Settings Optional The settings in this section are optional The Advanced Settings you can configure are Scope of VCS Provider You can configure which workspaces can use repositories from this VCS provider By default the All Projects option is selected meaning this VCS provider is available to be used by all workspaces in the organization Set up SSH Keypair Most organizations will not need to add an SSH key However if the organization repositories include Git submodules that can only be accessed via SSH an SSH key can be added along with the OAuth credentials You can add or update the SSH key at a later time If You Don t Need to Configure Advanced Settings 1 Click the Skip and Finish button This returns you to HCP Terraform s VCS Provider page which now includes your new GitLab client If You Need to Limit the Scope of this VCS Provider 1 Select the Selected Projects option and use the text field that appears to search for and select projects to enable All current and future workspaces for any selected projects can use repositories from this VCS Provider 1 Click the Update VCS Provider button to save your selections If You Do Need an SSH Keypair Important Notes SSH will only be used to clone Git submodules All other Git operations will still use HTTPS Do not use your personal SSH key to connect HCP Terraform and GitLab generate a new one or use an existing key reserved for service access In the following steps you must provide HCP Terraform with the private key Although HCP Terraform does not display the text of the key to users after it is entered it retains it and will use it when authenticating to GitLab Protect this private key carefully It can push code to the repositories you use to manage your infrastructure Take note of your organization s policies for protecting important credentials and be sure to follow them 1 On a secure workstation create an SSH keypair that HCP Terraform can use to connect to GitLab com The exact command depends on your OS but is usually something like ssh keygen t rsa m PEM f Users NAME ssh service terraform C service terraform enterprise This creates a service terraform file with the private key and a service terraform pub file with the public key This SSH key must have an empty passphrase HCP Terraform cannot use SSH keys that require a passphrase 1 While logged into the GitLab com account you want HCP Terraform to act as navigate to the SSH Keys settings page add a new SSH key and paste the value of the SSH public key you just created 1 In HCP Terraform s Add VCS Provider page paste the text of the SSH private key you just created and click the Add SSH Key button Finished At this point GitLab com access for HCP Terraform is fully configured and you can create Terraform workspaces based on your organization s shared repositories
terraform page title GitHub Enterprise VCS Providers HCP Terraform These instructions are for using a self hosted installation of GitHub Enterprise for HCP Terraform s VCS features GitHub com has separate instructions terraform cloud docs vcs github enterprise as do the other supported VCS providers terraform cloud docs vcs Learn how to use an on premise installation of GitHub Enterprise for VCS features Configuring GitHub Enterprise Access
--- page_title: GitHub Enterprise - VCS Providers - HCP Terraform description: >- Learn how to use an on-premise installation of GitHub Enterprise for VCS features. --- # Configuring GitHub Enterprise Access These instructions are for using a self-hosted installation of GitHub Enterprise for HCP Terraform's VCS features. [GitHub.com has separate instructions,](/terraform/cloud-docs/vcs/github-enterprise) as do the [other supported VCS providers.](/terraform/cloud-docs/vcs) Configuring a new VCS provider requires permission to manage VCS settings for the organization. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) [permissions-citation]: #intentionally-unused---keep-for-maintainers Connecting HCP Terraform to your VCS involves four steps: | On your VCS | On HCP Terraform | | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | |   | Create a new connection in HCP Terraform. Get callback URL. | | Register your HCP Terraform organization as a new app. Provide callback URL. Get ID and key. |   | |   | Provide HCP Terraform with ID and key. Request VCS access. | | Approve access request. |   | The rest of this page explains the GitHub Enterprise versions of these steps. ~> **Important:** HCP Terraform needs to contact your GitHub Enterprise instance during setup and during normal operation. For the SaaS version of HCP Terraform, this means GitHub Enterprise must be internet-accessible; for Terraform Enterprise, you must have network connectivity between your Terraform Enterprise and GitHub Enterprise instances. -> **Note:** Alternately, you can skip the OAuth configuration process and authenticate with a personal access token. This requires using HCP Terraform's API. For details, see [the OAuth Clients API page](/terraform/cloud-docs/api-docs/oauth-clients). ## Step 1: On HCP Terraform, begin adding a new VCS provider 1. Go to your organization's settings and then click **Providers** in the Version Control section. The **VCS Providers** page appears. 1. Click **Add a VCS provider**. The **Add VCS Provider** page appears. 1. Select **GitHub** and then select **GitHub Enterprise** from the menu. The page moves to the next step. 1. In the "Set up provider" step, fill in the **HTTP URL** and **API URL** of your GitHub Enterprise instance, as well as an optional **Name** for this VCS connection. | Field | Value | | -------- | ------------------------------------------- | | HTTP URL | `https://<GITHUB INSTANCE HOSTNAME>` | | API URL | `https://<GITHUB INSTANCE HOSTNAME>/api/v3` | Leave the page open in a browser tab. In the next step you will copy values from this page, and in later steps you will continue configuring HCP Terraform. ## Step 2: On GitHub, create a new OAuth application 1. In a new browser tab, open your GitHub Enterprise instance and log in as whichever account you want HCP Terraform to act as. For most organizations this should be a dedicated service user, but a personal account will also work. ~> **Important:** The account you use for connecting HCP Terraform **must have admin access** to any shared repositories of Terraform configurations, since creating webhooks requires admin permissions. 1. Navigate to GitHub's Register a New OAuth Application page. This page is located at `https://<GITHUB INSTANCE HOSTNAME>/settings/applications/new`. You can also reach it through GitHub's menus: - Click your profile picture and choose "Settings." - Click "OAuth Apps" (under the "Developer settings" section). - Click the "Register a new application" button. 1. This page has a form with four text fields. Fill out the fields with the corresponding values currently displayed in your HCP Terraform browser tab. HCP Terraform lists the values in the order they appear, and includes controls for copying values to your clipboard. Fill out the text fields as follows: | Field name | Value | | -------------------------- | ----------------------------------------------------------------------------- | | Application Name | HCP Terraform (`<YOUR ORGANIZATION NAME>`) | | Homepage URL | `https://app.terraform.io` (or the URL of your Terraform Enterprise instance) | | Application Description | Any description of your choice. | | Authorization callback URL | `https://app.terraform.io/<YOUR CALLBACK URL>` | 1. Click the "Register application" button, which creates the application and takes you to its page. 1. <a href="https://content.hashicorp.com/api/assets?product=terraform-docs-common&version=main&asset=website/img/docs/hcp-terraform-logo-on-white.png" download>Download this image of the HCP Terraform logo</a> and upload it with the "Upload new logo" button or the drag-and-drop target. This optional step helps you identify HCP Terraform's pull request checks at a glance. 1. Click the "Generate a new client secret" button. You will need this secret in the next step. 1. Leave this page open in a browser tab. In the next step, you will copy and paste the unique **Client ID** and **Client Secret.** ## Step 3: On HCP Terraform, set up your provider 1. Enter the **Client ID** and **Client Secret** from the previous step. 1. Click "Connect and continue." This takes you to a page on your GitHub Enterprise instance, asking whether you want to authorize the app. 1. The authorization page lists any GitHub organizations this account belongs to. If there is a **Request** button next to the organization that owns your Terraform code repositories, click it now. Note that you need to do this even if you are only connecting workspaces to private forks of repositories in those organizations since those forks are subject to the organization's access restrictions. See [About OAuth App access restrictions](https://docs.github.com/en/organizations/managing-oauth-access-to-your-organizations-data/about-oauth-app-access-restrictions). If it results in a 500 error, it usually means HCP Terraform was unable to reach your GitHub Enterprise instance. 1. Click the green "Authorize `<GITHUB USER>`" button at the bottom of the authorization page. GitHub might request your password or multi-factor token to confirm the operation. ## Step 4: On HCP Terraform, configure advanced settings (optional) The settings in this section are optional. The Advanced Settings you can configure are: - **Scope of VCS Provider** - You can configure which workspaces can use repositories from this VCS provider. By default the **All Projects** option is selected, meaning this VCS provider is available to be used by all workspaces in the organization. - **Set up SSH Keypair** - Most organizations will not need to add an SSH key. However, if the organization repositories include Git submodules that can only be accessed via SSH, an SSH key can be added along with the OAuth credentials. You can add or update the SSH key at a later time. ### If you don't need to configure advanced settings: 1. Click the **Skip and finish** button. This returns you to HCP Terraform's VCS Providers page, which now includes your new GitHub Enterprise client. ### If you need to limit the scope of this VCS provider: 1. Select the **Selected Projects** option and use the text field that appears to search for and select projects to enable. All current and future workspaces for any selected projects can use repositories from this VCS Provider. 1. Click the **Update VCS Provider** button to save your selections. ### If you need an SSH keypair: #### Important notes - SSH will only be used to clone Git submodules. All other Git operations will still use HTTPS. - Do not use your personal SSH key to connect HCP Terraform and GitHub Enterprise; generate a new one or use an existing key reserved for service access. - In the following steps, you must provide HCP Terraform with the private key. Although HCP Terraform does not display the text of the key to users after it is entered, it retains it and will use it when authenticating to GitHub Enterprise. - **Protect this private key carefully.** It can push code to the repositories you use to manage your infrastructure. Take note of your organization's policies for protecting important credentials and be sure to follow them. 1. On a secure workstation, create an SSH keypair that HCP Terraform can use to connect to Github Enterprise. The exact command depends on your OS, but is usually something like: `ssh-keygen -t rsa -m PEM -f "/Users/<NAME>/.ssh/service_terraform" -C "service_terraform_enterprise"` This creates a `service_terraform` file with the private key, and a `service_terraform.pub` file with the public key. This SSH key **must have an empty passphrase**. HCP Terraform cannot use SSH keys that require a passphrase. 1. While logged into the GitHub Enterprise account you want HCP Terraform to act as, navigate to the SSH Keys settings page, add a new SSH key and paste the value of the SSH public key you just created. 1. In HCP Terraform's **Add VCS Provider** page, paste the text of the **SSH private key** you just created, and click the **Add SSH Key** button. ## Step 5: Contact Your GitHub organization admins If your organization uses OAuth app access restrictions, you had to click a **Request** button when authorizing HCP Terraform, which sent an automated email to the administrators of your GitHub organization. An administrator must approve the request before HCP Terraform can access your organization's shared repositories. If you're a GitHub administrator, check your email now and respond to the request; otherwise, contact whoever is responsible for GitHub accounts in your organization, and wait for confirmation that they've approved your request. ## Finished At this point, GitHub access for HCP Terraform is fully configured, and you can create Terraform workspaces based on your organization's shared GitHub Enterprise repositories.
terraform
page title GitHub Enterprise VCS Providers HCP Terraform description Learn how to use an on premise installation of GitHub Enterprise for VCS features Configuring GitHub Enterprise Access These instructions are for using a self hosted installation of GitHub Enterprise for HCP Terraform s VCS features GitHub com has separate instructions terraform cloud docs vcs github enterprise as do the other supported VCS providers terraform cloud docs vcs Configuring a new VCS provider requires permission to manage VCS settings for the organization More about permissions terraform cloud docs users teams organizations permissions permissions citation intentionally unused keep for maintainers Connecting HCP Terraform to your VCS involves four steps On your VCS On HCP Terraform Create a new connection in HCP Terraform Get callback URL Register your HCP Terraform organization as a new app Provide callback URL Get ID and key Provide HCP Terraform with ID and key Request VCS access Approve access request The rest of this page explains the GitHub Enterprise versions of these steps Important HCP Terraform needs to contact your GitHub Enterprise instance during setup and during normal operation For the SaaS version of HCP Terraform this means GitHub Enterprise must be internet accessible for Terraform Enterprise you must have network connectivity between your Terraform Enterprise and GitHub Enterprise instances Note Alternately you can skip the OAuth configuration process and authenticate with a personal access token This requires using HCP Terraform s API For details see the OAuth Clients API page terraform cloud docs api docs oauth clients Step 1 On HCP Terraform begin adding a new VCS provider 1 Go to your organization s settings and then click Providers in the Version Control section The VCS Providers page appears 1 Click Add a VCS provider The Add VCS Provider page appears 1 Select GitHub and then select GitHub Enterprise from the menu The page moves to the next step 1 In the Set up provider step fill in the HTTP URL and API URL of your GitHub Enterprise instance as well as an optional Name for this VCS connection Field Value HTTP URL https GITHUB INSTANCE HOSTNAME API URL https GITHUB INSTANCE HOSTNAME api v3 Leave the page open in a browser tab In the next step you will copy values from this page and in later steps you will continue configuring HCP Terraform Step 2 On GitHub create a new OAuth application 1 In a new browser tab open your GitHub Enterprise instance and log in as whichever account you want HCP Terraform to act as For most organizations this should be a dedicated service user but a personal account will also work Important The account you use for connecting HCP Terraform must have admin access to any shared repositories of Terraform configurations since creating webhooks requires admin permissions 1 Navigate to GitHub s Register a New OAuth Application page This page is located at https GITHUB INSTANCE HOSTNAME settings applications new You can also reach it through GitHub s menus Click your profile picture and choose Settings Click OAuth Apps under the Developer settings section Click the Register a new application button 1 This page has a form with four text fields Fill out the fields with the corresponding values currently displayed in your HCP Terraform browser tab HCP Terraform lists the values in the order they appear and includes controls for copying values to your clipboard Fill out the text fields as follows Field name Value Application Name HCP Terraform YOUR ORGANIZATION NAME Homepage URL https app terraform io or the URL of your Terraform Enterprise instance Application Description Any description of your choice Authorization callback URL https app terraform io YOUR CALLBACK URL 1 Click the Register application button which creates the application and takes you to its page 1 a href https content hashicorp com api assets product terraform docs common version main asset website img docs hcp terraform logo on white png download Download this image of the HCP Terraform logo a and upload it with the Upload new logo button or the drag and drop target This optional step helps you identify HCP Terraform s pull request checks at a glance 1 Click the Generate a new client secret button You will need this secret in the next step 1 Leave this page open in a browser tab In the next step you will copy and paste the unique Client ID and Client Secret Step 3 On HCP Terraform set up your provider 1 Enter the Client ID and Client Secret from the previous step 1 Click Connect and continue This takes you to a page on your GitHub Enterprise instance asking whether you want to authorize the app 1 The authorization page lists any GitHub organizations this account belongs to If there is a Request button next to the organization that owns your Terraform code repositories click it now Note that you need to do this even if you are only connecting workspaces to private forks of repositories in those organizations since those forks are subject to the organization s access restrictions See About OAuth App access restrictions https docs github com en organizations managing oauth access to your organizations data about oauth app access restrictions If it results in a 500 error it usually means HCP Terraform was unable to reach your GitHub Enterprise instance 1 Click the green Authorize GITHUB USER button at the bottom of the authorization page GitHub might request your password or multi factor token to confirm the operation Step 4 On HCP Terraform configure advanced settings optional The settings in this section are optional The Advanced Settings you can configure are Scope of VCS Provider You can configure which workspaces can use repositories from this VCS provider By default the All Projects option is selected meaning this VCS provider is available to be used by all workspaces in the organization Set up SSH Keypair Most organizations will not need to add an SSH key However if the organization repositories include Git submodules that can only be accessed via SSH an SSH key can be added along with the OAuth credentials You can add or update the SSH key at a later time If you don t need to configure advanced settings 1 Click the Skip and finish button This returns you to HCP Terraform s VCS Providers page which now includes your new GitHub Enterprise client If you need to limit the scope of this VCS provider 1 Select the Selected Projects option and use the text field that appears to search for and select projects to enable All current and future workspaces for any selected projects can use repositories from this VCS Provider 1 Click the Update VCS Provider button to save your selections If you need an SSH keypair Important notes SSH will only be used to clone Git submodules All other Git operations will still use HTTPS Do not use your personal SSH key to connect HCP Terraform and GitHub Enterprise generate a new one or use an existing key reserved for service access In the following steps you must provide HCP Terraform with the private key Although HCP Terraform does not display the text of the key to users after it is entered it retains it and will use it when authenticating to GitHub Enterprise Protect this private key carefully It can push code to the repositories you use to manage your infrastructure Take note of your organization s policies for protecting important credentials and be sure to follow them 1 On a secure workstation create an SSH keypair that HCP Terraform can use to connect to Github Enterprise The exact command depends on your OS but is usually something like ssh keygen t rsa m PEM f Users NAME ssh service terraform C service terraform enterprise This creates a service terraform file with the private key and a service terraform pub file with the public key This SSH key must have an empty passphrase HCP Terraform cannot use SSH keys that require a passphrase 1 While logged into the GitHub Enterprise account you want HCP Terraform to act as navigate to the SSH Keys settings page add a new SSH key and paste the value of the SSH public key you just created 1 In HCP Terraform s Add VCS Provider page paste the text of the SSH private key you just created and click the Add SSH Key button Step 5 Contact Your GitHub organization admins If your organization uses OAuth app access restrictions you had to click a Request button when authorizing HCP Terraform which sent an automated email to the administrators of your GitHub organization An administrator must approve the request before HCP Terraform can access your organization s shared repositories If you re a GitHub administrator check your email now and respond to the request otherwise contact whoever is responsible for GitHub accounts in your organization and wait for confirmation that they ve approved your request Finished At this point GitHub access for HCP Terraform is fully configured and you can create Terraform workspaces based on your organization s shared GitHub Enterprise repositories
terraform These instructions are for using dev azure com for HCP Terraform s VCS features Other supported VCS providers terraform cloud docs vcs have separate instructions page title Azure DevOps Services VCS Providers HCP Terraform Configuring Azure DevOps Services Access Learn how to use Azure DevOps Services dev azure com for VCS features
--- page_title: Azure DevOps Services - VCS Providers - HCP Terraform description: >- Learn how to use Azure DevOps Services (dev.azure.com) for VCS features. --- # Configuring Azure DevOps Services Access These instructions are for using `dev.azure.com` for HCP Terraform's VCS features. [Other supported VCS providers](/terraform/cloud-docs/vcs) have separate instructions. This page explains the four main steps required to connect HCP Terraform to your Azure DevOps Services VCS: 1. Create a new connection in HCP Terraform and get the callback URL. 1. On your VCS, register your HCP Terraform organization as a new application. Provide the callback URL and get the application ID and key. 1. Provide HCP Terraform with the application ID and key. Then, request VCS access. 1. On your VCS, approve the access request from HCP Terraform. ~> **Important:** HCP Terraform only supports Azure DevOps connections that use the `dev.azure.com` domain. If your Azure DevOps project uses the older `visualstudio.com` domain, you must migrate using the [steps in the Microsoft documentation](https://docs.microsoft.com/en-us/azure/devops/release-notes/2018/sep-10-azure-devops-launch#switch-existing-organizations-to-use-the-new-domain-name-url). ## Requirements Configuring a new VCS provider requires permission to [manage VCS settings](/terraform/cloud-docs/users-teams-organizations/permissions#manage-vcs-settings) for the organization. [permissions-citation]: #intentionally-unused---keep-for-maintainers Before you begin, enable `Third-party application access via OAuth` in Azure DevOps Services settings. 1. Log in to [Azure DevOps Services](https://dev.azure.com/). 1. Click **Organization settings**. 1. Click **Policies** under **Security**. 1. Enable the **Third-party application access via OAuth** setting. ![Azure DevOps Services Screenshot: Policies Third-party application access via Oauth](/img/docs/azure-devops-services-oauth-policies.png) ## Step 1: On HCP Terraform, Begin Adding a New VCS Provider 1. Go to your organization's settings and then click **Providers**. The **VCS Providers** page appears. 1. Click **Add VCS Provider**. The **VCS Providers** page appears. 1. Select **Azure DevOps** and then select **Azure DevOps Services** from the menu. The page moves to the next step. Leave this page open in a browser tab. You will copy values from this page into Azure DevOps in the next step, and in later steps you will continue configuring HCP Terraform. ## Step 2: From your Azure DevOps Services Profile, Create a New Application 1. In a new browser tab, open your [Azure DevOps Services Profile](https://aex.dev.azure.com), and log in to your Azure DevOps Services account if necessary. A page with a list of your organizations appears. ~> **Important:** The Azure DevOps Services account you use for connecting HCP Terraform must have Project Collection Administrator access to any projects containing repositories of Terraform configurations, since creating webhooks requires admin permissions. It is not possible to create custom access roles with lower levels of privilege, as Microsoft does not currently allow delegation of this capability. If you're unable to load the link above, you can create a new application for the next step at one of the following links: `https://aex.dev.azure.com/app/register?mkt=en-US` or `https://app.vsaex.visualstudio.com/app/register?mkt=en-US`. 1. Go into your preferred organization. 1. Click your user icon and then click the **ellipses (...) ** and select **User settings**. 1. From the User settings menu, click **Profile**. Your profile page appears. 1. Click **Authorizations**. The Authorized OAuth Apps page appears. 1. Click the link to register a new app. A form appears asking for your company and application information. 1. Fill out the fields and checkboxes with the corresponding values currently displayed in your HCP Terraform browser tab. HCP Terraform lists the values in the order they appear and includes controls for copying values to your clipboard. Here is an example: | Field name | Value | | -------------------------- | ----------------------------------------------------------------------------- | | Company name | HashiCorp | | Application Name | HCP Terraform (`<YOUR ORGANIZATION NAME>`) | | Application website | `https://app.terraform.io` (or the URL of your Terraform Enterprise instance) | | Authorization callback URL | `https://app.terraform.io/<YOUR CALLBACK URL>` | In the **Authorized scopes** section, select only **Code (read)** and **Code (status)** and then click **Create Application.** ![Azure DevOps Services Screenshot: Required permissions when creating a new application in your Azure DevOps Services Profile](/img/docs/azure-devops-services-application-permissions.png) ~> **Important:** Do not add any additional scopes beyond **Code (read)** and **Code (status),** as this can prevent HCP Terraform from connecting. Note that these authorized scopes cannot be updated after the application is created; to fix incorrect scopes you must delete and re-create the application. 1. After creating the application, the next page displays its details. Leave this page open in a browser tab. In the next step, you will copy and paste the unique **App ID** and **Client Secret** from this page. If you accidentally close this details page and need to find it later, you can reach it from the **Applications and Services** links in your profile. ## Step 3: On HCP Terraform, Set up Your Provider 1. (Optional) Enter a **Name** for this VCS connection. 1. Enter your Azure DevOps Services application's **App ID** and **Client Secret**. These can be found in the application's details, which should still be open in the browser tab from Step 2. 1. Click **Connect and continue.** This takes you to a page on Azure DevOps Services, asking whether you want to authorize the app. Click the **Accept** button and you'll be redirected back to HCP Terraform. -> **Note:** If you receive a 404 error from Azure DevOps Services, it likely means your callback URL has not been configured correctly. ## Step 4: On HCP Terraform, Configure Advanced Settings (Optional) The settings in this section are optional. The Advanced Settings you can configure are: - **Scope of VCS Provider** - You can configure which workspaces can use repositories from this VCS provider. By default the **All Projects** option is selected, meaning this VCS provider is available to be used by all workspaces in the organization. - **Set up SSH Keypair** - Most organizations will not need to add an SSH key. However, if the organization repositories include Git submodules that can only be accessed via SSH, an SSH key can be added along with the OAuth credentials. You can add or update the SSH key at a later time. ### If You Don't Need to Configure Advanced Settings: 1. Click the **Skip and Finish** button. This returns you to HCP Terraform's VCS Provider page, which now includes your new Azure DevOps Services client. ### If You Need to Limit the Scope of this VCS Provider: 1. Select the **Selected Projects** option and use the text field that appears to search for and select projects to enable. All current and future workspaces for any selected projects can use repositories from this VCS Provider. 1. Click the **Update VCS Provider** button to save your selections. ### If You Do Need an SSH Keypair: #### Important Notes - SSH will only be used to clone Git submodules. All other Git operations will still use HTTPS. - Do not use your personal SSH key to connect HCP Terraform and Azure DevOps Services; generate a new one or use an existing key reserved for service access. - In the following steps, you must provide HCP Terraform with the private key. Although HCP Terraform does not display the text of the key to users after it is entered, it retains it and will use it when authenticating to Azure DevOps Services. - **Protect this private key carefully.** It can push code to the repositories you use to manage your infrastructure. Take note of your organization's policies for protecting important credentials and be sure to follow them. 1. On a secure workstation, create an SSH keypair that HCP Terraform can use to connect to Azure DevOps Services.com. The exact command depends on your OS, but is usually something like: `ssh-keygen -t rsa -m PEM -f "/Users/<NAME>/.ssh/service_terraform" -C "service_terraform_enterprise"` This creates a `service_terraform` file with the private key, and a `service_terraform.pub` file with the public key. This SSH key **must have an empty passphrase**. HCP Terraform cannot use SSH keys that require a passphrase. 1. While logged into the Azure DevOps Services account you want HCP Terraform to act as, navigate to the SSH Keys settings page, add a new SSH key and paste the value of the SSH public key you just created. 1. In HCP Terraform's **Add VCS Provider** page, paste the text of the **SSH private key** you just created, and click the **Add SSH Key** button. ## Finished At this point, Azure DevOps Services access for HCP Terraform is fully configured, and you can create Terraform workspaces based on your organization's repositories.
terraform
page title Azure DevOps Services VCS Providers HCP Terraform description Learn how to use Azure DevOps Services dev azure com for VCS features Configuring Azure DevOps Services Access These instructions are for using dev azure com for HCP Terraform s VCS features Other supported VCS providers terraform cloud docs vcs have separate instructions This page explains the four main steps required to connect HCP Terraform to your Azure DevOps Services VCS 1 Create a new connection in HCP Terraform and get the callback URL 1 On your VCS register your HCP Terraform organization as a new application Provide the callback URL and get the application ID and key 1 Provide HCP Terraform with the application ID and key Then request VCS access 1 On your VCS approve the access request from HCP Terraform Important HCP Terraform only supports Azure DevOps connections that use the dev azure com domain If your Azure DevOps project uses the older visualstudio com domain you must migrate using the steps in the Microsoft documentation https docs microsoft com en us azure devops release notes 2018 sep 10 azure devops launch switch existing organizations to use the new domain name url Requirements Configuring a new VCS provider requires permission to manage VCS settings terraform cloud docs users teams organizations permissions manage vcs settings for the organization permissions citation intentionally unused keep for maintainers Before you begin enable Third party application access via OAuth in Azure DevOps Services settings 1 Log in to Azure DevOps Services https dev azure com 1 Click Organization settings 1 Click Policies under Security 1 Enable the Third party application access via OAuth setting Azure DevOps Services Screenshot Policies Third party application access via Oauth img docs azure devops services oauth policies png Step 1 On HCP Terraform Begin Adding a New VCS Provider 1 Go to your organization s settings and then click Providers The VCS Providers page appears 1 Click Add VCS Provider The VCS Providers page appears 1 Select Azure DevOps and then select Azure DevOps Services from the menu The page moves to the next step Leave this page open in a browser tab You will copy values from this page into Azure DevOps in the next step and in later steps you will continue configuring HCP Terraform Step 2 From your Azure DevOps Services Profile Create a New Application 1 In a new browser tab open your Azure DevOps Services Profile https aex dev azure com and log in to your Azure DevOps Services account if necessary A page with a list of your organizations appears Important The Azure DevOps Services account you use for connecting HCP Terraform must have Project Collection Administrator access to any projects containing repositories of Terraform configurations since creating webhooks requires admin permissions It is not possible to create custom access roles with lower levels of privilege as Microsoft does not currently allow delegation of this capability If you re unable to load the link above you can create a new application for the next step at one of the following links https aex dev azure com app register mkt en US or https app vsaex visualstudio com app register mkt en US 1 Go into your preferred organization 1 Click your user icon and then click the ellipses and select User settings 1 From the User settings menu click Profile Your profile page appears 1 Click Authorizations The Authorized OAuth Apps page appears 1 Click the link to register a new app A form appears asking for your company and application information 1 Fill out the fields and checkboxes with the corresponding values currently displayed in your HCP Terraform browser tab HCP Terraform lists the values in the order they appear and includes controls for copying values to your clipboard Here is an example Field name Value Company name HashiCorp Application Name HCP Terraform YOUR ORGANIZATION NAME Application website https app terraform io or the URL of your Terraform Enterprise instance Authorization callback URL https app terraform io YOUR CALLBACK URL In the Authorized scopes section select only Code read and Code status and then click Create Application Azure DevOps Services Screenshot Required permissions when creating a new application in your Azure DevOps Services Profile img docs azure devops services application permissions png Important Do not add any additional scopes beyond Code read and Code status as this can prevent HCP Terraform from connecting Note that these authorized scopes cannot be updated after the application is created to fix incorrect scopes you must delete and re create the application 1 After creating the application the next page displays its details Leave this page open in a browser tab In the next step you will copy and paste the unique App ID and Client Secret from this page If you accidentally close this details page and need to find it later you can reach it from the Applications and Services links in your profile Step 3 On HCP Terraform Set up Your Provider 1 Optional Enter a Name for this VCS connection 1 Enter your Azure DevOps Services application s App ID and Client Secret These can be found in the application s details which should still be open in the browser tab from Step 2 1 Click Connect and continue This takes you to a page on Azure DevOps Services asking whether you want to authorize the app Click the Accept button and you ll be redirected back to HCP Terraform Note If you receive a 404 error from Azure DevOps Services it likely means your callback URL has not been configured correctly Step 4 On HCP Terraform Configure Advanced Settings Optional The settings in this section are optional The Advanced Settings you can configure are Scope of VCS Provider You can configure which workspaces can use repositories from this VCS provider By default the All Projects option is selected meaning this VCS provider is available to be used by all workspaces in the organization Set up SSH Keypair Most organizations will not need to add an SSH key However if the organization repositories include Git submodules that can only be accessed via SSH an SSH key can be added along with the OAuth credentials You can add or update the SSH key at a later time If You Don t Need to Configure Advanced Settings 1 Click the Skip and Finish button This returns you to HCP Terraform s VCS Provider page which now includes your new Azure DevOps Services client If You Need to Limit the Scope of this VCS Provider 1 Select the Selected Projects option and use the text field that appears to search for and select projects to enable All current and future workspaces for any selected projects can use repositories from this VCS Provider 1 Click the Update VCS Provider button to save your selections If You Do Need an SSH Keypair Important Notes SSH will only be used to clone Git submodules All other Git operations will still use HTTPS Do not use your personal SSH key to connect HCP Terraform and Azure DevOps Services generate a new one or use an existing key reserved for service access In the following steps you must provide HCP Terraform with the private key Although HCP Terraform does not display the text of the key to users after it is entered it retains it and will use it when authenticating to Azure DevOps Services Protect this private key carefully It can push code to the repositories you use to manage your infrastructure Take note of your organization s policies for protecting important credentials and be sure to follow them 1 On a secure workstation create an SSH keypair that HCP Terraform can use to connect to Azure DevOps Services com The exact command depends on your OS but is usually something like ssh keygen t rsa m PEM f Users NAME ssh service terraform C service terraform enterprise This creates a service terraform file with the private key and a service terraform pub file with the public key This SSH key must have an empty passphrase HCP Terraform cannot use SSH keys that require a passphrase 1 While logged into the Azure DevOps Services account you want HCP Terraform to act as navigate to the SSH Keys settings page add a new SSH key and paste the value of the SSH public key you just created 1 In HCP Terraform s Add VCS Provider page paste the text of the SSH private key you just created and click the Add SSH Key button Finished At this point Azure DevOps Services access for HCP Terraform is fully configured and you can create Terraform workspaces based on your organization s repositories
terraform Configuring GitHub com Access OAuth Learn how to use GitHub com for VCS features using a per organization OAuth connection with the permissions of an individual GitHub user page title GitHub com OAuth VCS Providers HCP Terraform These instructions are for using GitHub com for HCP Terraform s VCS features using a per organization OAuth connection with the permissions of one particular GitHub user GitHub Enterprise has separate instructions terraform enterprise vcs github enterprise as do the other supported VCS providers terraform enterprise vcs
--- page_title: GitHub.com (OAuth) - VCS Providers - HCP Terraform description: >- Learn how to use GitHub.com for VCS features, using a per-organization OAuth connection with the permissions of an individual GitHub user. --- # Configuring GitHub.com Access (OAuth) These instructions are for using GitHub.com for HCP Terraform's VCS features, using a per-organization OAuth connection with the permissions of one particular GitHub user. [GitHub Enterprise has separate instructions,](/terraform/enterprise/vcs/github-enterprise) as do the [other supported VCS providers.](/terraform/enterprise/vcs) <!-- BEGIN: TFC:only --> For new users on HCP Terraform, we recommend using our [configuration-free GitHub App](/terraform/cloud-docs/vcs/github-app) to access repositories instead. <!-- END: TFC:only --> For Terraform Enterprise site admins, you can create your own [GitHub App](/terraform/enterprise/admin/application/github-app-integration) to access repositories. Configuring a new VCS provider requires permission to manage VCS settings for the organization. ([More about permissions.](/terraform/enterprise/users-teams-organizations/permissions)) [permissions-citation]: #intentionally-unused---keep-for-maintainers Connecting HCP Terraform to your VCS involves four steps: | On your VCS | On HCP Terraform | | ------------------------------------------------------------------------------ | ------------------------------------------------------------- | |   | Create a new connection in HCP Terraform. Get callback URL. | | Register your HCP Terraform organization as a new app. Provide callback URL. |   | |   | Provide HCP Terraform with ID and key. Request VCS access. | | Approve access request. |   | The rest of this page explains the GitHub versions of these steps. -> **Note:** Alternately, you can skip the OAuth configuration process and authenticate with a personal access token. This requires using HCP Terraform's API. For details, see [the OAuth Clients API page](/terraform/cloud-docs/api-docs/oauth-clients). ## Step 1: On HCP Terraform, begin adding a new VCS provider 1. Go to your organization's settings and then click **Providers** in the **Version Control** section. The **VCS Providers** page appears. 1. Click **Add a VCS provider**. The **Add VCS Provider** page appears. 1. Select **GitHub** and then select **GitHub.com (Custom)** from the menu. The page moves to the next step. Leave the page open in a browser tab. In the next step you will copy values from this page, and in later steps you will continue configuring HCP Terraform. ## Step 2: On GitHub, create a new OAuth application On the HCP Terraform **Add VCS Provider** page, click **register a new OAuth Application**. This opens GitHub.com in a new browser tab with the OAuth application settings pre-filled. Alternately, create the OAuth application manually on GitHub.com. ### Manual steps 1. In a new browser tab, open [github.com](https://github.com) and log in as whichever account you want HCP Terraform to act as. For most organizations this should be a dedicated service user, but a personal account will also work. ~> **Important:** The account you use for connecting HCP Terraform **must have admin access** to any shared repositories of Terraform configurations, since creating webhooks requires admin permissions. 1. Navigate to GitHub's [Register a New OAuth Application](https://github.com/settings/applications/new) page. This page is located at <https://github.com/settings/applications/new>. You can also reach it through GitHub's menus: - Click your profile picture and choose "Settings." - Click "Developer settings," then make sure you're on the "OAuth Apps" page (not "GitHub Apps"). - Click the "New OAuth App" button. 1. This page has a form with four text fields. Fill out the fields with the corresponding values currently displayed in your HCP Terraform browser tab. HCP Terraform lists the values in the order they appear, and includes controls for copying values to your clipboard. Fill out the text fields as follows: | Field name | Value | | -------------------------- | ----------------------------------------------------------------------------- | | Application Name | HCP Terraform (`<YOUR ORGANIZATION NAME>`) | | Homepage URL | `https://app.terraform.io` (or the URL of your Terraform Enterprise instance) | | Application Description | Any description of your choice. | | Authorization callback URL | `https://app.terraform.io/<YOUR CALLBACK URL>` | ### Register the OAuth application 1. Click the "Register application" button, which creates the application and takes you to its page. 1. <a href="https://content.hashicorp.com/api/assets?product=terraform-docs-common&version=main&asset=website/img/docs/hcp-terraform-logo-on-white.png" download>Download this image of the HCP Terraform logo</a> and upload it with the "Upload new logo" button or the drag-and-drop target. This optional step helps you identify HCP Terraform's pull request checks at a glance. 1. Click the **Generate a new client secret** button. You will need this secret in the next step. 1. Leave this page open in a browser tab. In the next step, you will copy and paste the unique **Client ID** and **Client Secret.** ## Step 3: On HCP Terraform, set up your provider 1. Enter the **Client ID** and **Client Secret** from the previous step, as well as an optional **Name** for this VCS connection. 1. Click "Connect and continue." This takes you to a page on GitHub.com, asking whether you want to authorize the app. 1. The authorization page lists any GitHub organizations this account belongs to. If there is a **Request** button next to the organization that owns your Terraform code repositories, click it now. Note that you need to do this even if you are only connecting workspaces to private forks of repositories in those organizations since those forks are subject to the organization's access restrictions. See [About OAuth App access restrictions](https://docs.github.com/en/organizations/managing-oauth-access-to-your-organizations-data/about-oauth-app-access-restrictions). 1. Click the green "Authorize `<GITHUB USER>`" button at the bottom of the authorization page. GitHub might request your password or multi-factor token to confirm the operation. ## Step 4: On HCP Terraform, configure advanced settings (optional) The settings in this section are optional. The Advanced Settings you can configure are: - **Scope of VCS Provider** - You can configure which workspaces can use repositories from this VCS provider. By default the **All Projects** option is selected, meaning this VCS provider is available to be used by all workspaces in the organization. - **Set up SSH Keypair** - Most organizations will not need to add an SSH key. However, if the organization repositories include Git submodules that can only be accessed via SSH, an SSH key can be added along with the OAuth credentials. You can add or update the SSH key at a later time. ### If you don't need to configure advanced settings: 1. Click the **Skip and finish** button. This returns you to HCP Terraform's **VCS Providers** page, which now includes your new GitHub client. ### If you need to limit the scope of this VCS provider: 1. Select the **Selected Projects** option and use the text field that appears to search for and select projects to enable. All current and future workspaces for any selected projects can use repositories from this VCS Provider. 1. Click the **Update VCS Provider** button to save your selections. ### If you need an SSH keypair: #### Important notes - SSH will only be used to clone Git submodules. All other Git operations will still use HTTPS. - Do not use your personal SSH key to connect HCP Terraform and GitHub; generate a new one or use an existing key reserved for service access. - In the following steps, you must provide HCP Terraform with the private key. Although HCP Terraform does not display the text of the key to users after it is entered, it retains it and will use it when authenticating to GitHub. - **Protect this private key carefully.** It can push code to the repositories you use to manage your infrastructure. Take note of your organization's policies for protecting important credentials and be sure to follow them. 1. On a secure workstation, create an SSH keypair that HCP Terraform can use to connect to GitHub.com. The exact command depends on your OS, but is usually something like: `ssh-keygen -t rsa -m PEM -f "/Users/<NAME>/.ssh/service_terraform" -C "service_terraform_enterprise"` This creates a `service_terraform` file with the private key, and a `service_terraform.pub` file with the public key. This SSH key **must have an empty passphrase**. HCP Terraform cannot use SSH keys that require a passphrase. 1. While logged into the GitHub.com account you want HCP Terraform to act as, navigate to the SSH Keys settings page, add a new SSH key and paste the value of the SSH public key you just created. 1. In HCP Terraform's **Add VCS Provider** page, paste the text of the **SSH private key** you just created, and click the **Add SSH Key** button. ## Step 5: Contact your GitHub organization admins If your organization uses OAuth app access restrictions, you had to click a **Request** button when authorizing HCP Terraform, which sent an automated email to the administrators of your GitHub organization. An administrator must approve the request before HCP Terraform can access your organization's shared repositories. If you're a GitHub administrator, check your email now and respond to the request; otherwise, contact whoever is responsible for GitHub accounts in your organization, and wait for confirmation that they've approved your request. ## Finished At this point, GitHub access for HCP Terraform is fully configured, and you can create Terraform workspaces based on your organization's shared GitHub repositories.
terraform
page title GitHub com OAuth VCS Providers HCP Terraform description Learn how to use GitHub com for VCS features using a per organization OAuth connection with the permissions of an individual GitHub user Configuring GitHub com Access OAuth These instructions are for using GitHub com for HCP Terraform s VCS features using a per organization OAuth connection with the permissions of one particular GitHub user GitHub Enterprise has separate instructions terraform enterprise vcs github enterprise as do the other supported VCS providers terraform enterprise vcs BEGIN TFC only For new users on HCP Terraform we recommend using our configuration free GitHub App terraform cloud docs vcs github app to access repositories instead END TFC only For Terraform Enterprise site admins you can create your own GitHub App terraform enterprise admin application github app integration to access repositories Configuring a new VCS provider requires permission to manage VCS settings for the organization More about permissions terraform enterprise users teams organizations permissions permissions citation intentionally unused keep for maintainers Connecting HCP Terraform to your VCS involves four steps On your VCS On HCP Terraform Create a new connection in HCP Terraform Get callback URL Register your HCP Terraform organization as a new app Provide callback URL Provide HCP Terraform with ID and key Request VCS access Approve access request The rest of this page explains the GitHub versions of these steps Note Alternately you can skip the OAuth configuration process and authenticate with a personal access token This requires using HCP Terraform s API For details see the OAuth Clients API page terraform cloud docs api docs oauth clients Step 1 On HCP Terraform begin adding a new VCS provider 1 Go to your organization s settings and then click Providers in the Version Control section The VCS Providers page appears 1 Click Add a VCS provider The Add VCS Provider page appears 1 Select GitHub and then select GitHub com Custom from the menu The page moves to the next step Leave the page open in a browser tab In the next step you will copy values from this page and in later steps you will continue configuring HCP Terraform Step 2 On GitHub create a new OAuth application On the HCP Terraform Add VCS Provider page click register a new OAuth Application This opens GitHub com in a new browser tab with the OAuth application settings pre filled Alternately create the OAuth application manually on GitHub com Manual steps 1 In a new browser tab open github com https github com and log in as whichever account you want HCP Terraform to act as For most organizations this should be a dedicated service user but a personal account will also work Important The account you use for connecting HCP Terraform must have admin access to any shared repositories of Terraform configurations since creating webhooks requires admin permissions 1 Navigate to GitHub s Register a New OAuth Application https github com settings applications new page This page is located at https github com settings applications new You can also reach it through GitHub s menus Click your profile picture and choose Settings Click Developer settings then make sure you re on the OAuth Apps page not GitHub Apps Click the New OAuth App button 1 This page has a form with four text fields Fill out the fields with the corresponding values currently displayed in your HCP Terraform browser tab HCP Terraform lists the values in the order they appear and includes controls for copying values to your clipboard Fill out the text fields as follows Field name Value Application Name HCP Terraform YOUR ORGANIZATION NAME Homepage URL https app terraform io or the URL of your Terraform Enterprise instance Application Description Any description of your choice Authorization callback URL https app terraform io YOUR CALLBACK URL Register the OAuth application 1 Click the Register application button which creates the application and takes you to its page 1 a href https content hashicorp com api assets product terraform docs common version main asset website img docs hcp terraform logo on white png download Download this image of the HCP Terraform logo a and upload it with the Upload new logo button or the drag and drop target This optional step helps you identify HCP Terraform s pull request checks at a glance 1 Click the Generate a new client secret button You will need this secret in the next step 1 Leave this page open in a browser tab In the next step you will copy and paste the unique Client ID and Client Secret Step 3 On HCP Terraform set up your provider 1 Enter the Client ID and Client Secret from the previous step as well as an optional Name for this VCS connection 1 Click Connect and continue This takes you to a page on GitHub com asking whether you want to authorize the app 1 The authorization page lists any GitHub organizations this account belongs to If there is a Request button next to the organization that owns your Terraform code repositories click it now Note that you need to do this even if you are only connecting workspaces to private forks of repositories in those organizations since those forks are subject to the organization s access restrictions See About OAuth App access restrictions https docs github com en organizations managing oauth access to your organizations data about oauth app access restrictions 1 Click the green Authorize GITHUB USER button at the bottom of the authorization page GitHub might request your password or multi factor token to confirm the operation Step 4 On HCP Terraform configure advanced settings optional The settings in this section are optional The Advanced Settings you can configure are Scope of VCS Provider You can configure which workspaces can use repositories from this VCS provider By default the All Projects option is selected meaning this VCS provider is available to be used by all workspaces in the organization Set up SSH Keypair Most organizations will not need to add an SSH key However if the organization repositories include Git submodules that can only be accessed via SSH an SSH key can be added along with the OAuth credentials You can add or update the SSH key at a later time If you don t need to configure advanced settings 1 Click the Skip and finish button This returns you to HCP Terraform s VCS Providers page which now includes your new GitHub client If you need to limit the scope of this VCS provider 1 Select the Selected Projects option and use the text field that appears to search for and select projects to enable All current and future workspaces for any selected projects can use repositories from this VCS Provider 1 Click the Update VCS Provider button to save your selections If you need an SSH keypair Important notes SSH will only be used to clone Git submodules All other Git operations will still use HTTPS Do not use your personal SSH key to connect HCP Terraform and GitHub generate a new one or use an existing key reserved for service access In the following steps you must provide HCP Terraform with the private key Although HCP Terraform does not display the text of the key to users after it is entered it retains it and will use it when authenticating to GitHub Protect this private key carefully It can push code to the repositories you use to manage your infrastructure Take note of your organization s policies for protecting important credentials and be sure to follow them 1 On a secure workstation create an SSH keypair that HCP Terraform can use to connect to GitHub com The exact command depends on your OS but is usually something like ssh keygen t rsa m PEM f Users NAME ssh service terraform C service terraform enterprise This creates a service terraform file with the private key and a service terraform pub file with the public key This SSH key must have an empty passphrase HCP Terraform cannot use SSH keys that require a passphrase 1 While logged into the GitHub com account you want HCP Terraform to act as navigate to the SSH Keys settings page add a new SSH key and paste the value of the SSH public key you just created 1 In HCP Terraform s Add VCS Provider page paste the text of the SSH private key you just created and click the Add SSH Key button Step 5 Contact your GitHub organization admins If your organization uses OAuth app access restrictions you had to click a Request button when authorizing HCP Terraform which sent an automated email to the administrators of your GitHub organization An administrator must approve the request before HCP Terraform can access your organization s shared repositories If you re a GitHub administrator check your email now and respond to the request otherwise contact whoever is responsible for GitHub accounts in your organization and wait for confirmation that they ve approved your request Finished At this point GitHub access for HCP Terraform is fully configured and you can create Terraform workspaces based on your organization s shared GitHub repositories
terraform Configuring GitLab EE and CE Access Learn how to use on premise installation of GitLab Enterprise Edition EE or GitLab Community Edition CE for VCS features page title GitLab EE and CE VCS Providers HCP Terraform These instructions are for using an on premise installation of GitLab Enterprise Edition EE or GitLab Community Edition CE for HCP Terraform s VCS features GitLab com has separate instructions terraform cloud docs vcs gitlab com as do the other supported VCS providers terraform cloud docs vcs
--- page_title: GitLab EE and CE - VCS Providers - HCP Terraform description: >- Learn how to use on-premise installation of GitLab Enterprise Edition (EE) or GitLab Community Edition (CE) for VCS features. --- # Configuring GitLab EE and CE Access These instructions are for using an on-premise installation of GitLab Enterprise Edition (EE) or GitLab Community Edition (CE) for HCP Terraform's VCS features. [GitLab.com has separate instructions,](/terraform/cloud-docs/vcs/gitlab-com) as do the [other supported VCS providers.](/terraform/cloud-docs/vcs) Configuring a new VCS provider requires permission to manage VCS settings for the organization. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) [permissions-citation]: #intentionally-unused---keep-for-maintainers Connecting HCP Terraform to your VCS involves four steps: | On your VCS | On HCP Terraform | | ---------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | |   | Create a new connection in HCP Terraform. Get redirect URI. | | Register your HCP Terraform organization as a new app. Provide redirect URI. Get ID and key. |   | |   | Provide HCP Terraform with application ID and secret. Request VCS access. | | Approve access request. |   | The rest of this page explains the on-premise GitLab versions of these steps. ~> **Important:** HCP Terraform needs to contact your GitLab instance during setup and during normal operation. For the SaaS version of HCP Terraform, this means GitLab must be internet-accessible; for Terraform Enterprise, you must have network connectivity between your Terraform Enterprise and GitLab instances. -> **Note:** Alternately, you can skip the OAuth configuration process and authenticate with a personal access token. This requires using HCP Terraform's API. For details, see [the OAuth Clients API page](/terraform/cloud-docs/api-docs/oauth-clients). -> **Version Note:** HCP Terraform supports GitLab versions 9.0 and newer. HashiCorp does not test older versions of GitLab with HCP Terraform, and they might not work as expected. Also note that, although we do not deliberately remove support for versions that have reached end of life (per the [GitLab Support End of Life Policy](https://docs.gitlab.com/ee/policy/maintenance.html#patch-releases)), our ability to resolve customer issues with end of life versions might be limited. ## Step 1: On HCP Terraform, Begin Adding a New VCS Provider 1. Go to your organization's settings and then click **Providers**. The **VCS Providers** page appears. 1. Click **Add VCS Provider**. The **VCS Providers** page appears. 1. Select **GitLab** and then select **GitLab Enterprise Edition** or **GitLab Community Edition** from the menu. The page moves to the next step. 1. In the "Set up provider" step, fill in the **HTTP URL** and **API URL** of your GitLab Enterprise Edition or GitLab Community Edition instance, as well as an optional **Name** for this VCS connection. Click "Continue." | Field | Value | | -------- | ------------------------------------------- | | HTTP URL | `https://<GITLAB INSTANCE HOSTNAME>` | | API URL | `https://<GITLAB INSTANCE HOSTNAME>/api/v4` | Note that HCP Terraform uses GitLab's v4 API. Leave the page open in a browser tab. In the next step you will copy values from this page, and in later steps you will continue configuring HCP Terraform. ## Step 2: On GitLab, Create a New Application 1. In a new browser tab, open your GitLab instance and log in as whichever account you want HCP Terraform to act as. For most organizations this should be a dedicated service user, but a personal account will also work. ~> **Important:** The account you use for connecting HCP Terraform **must have admin (master) access** to any shared repositories of Terraform configurations, since creating webhooks requires admin permissions. Do not create the application as an administrative application not owned by a user; HCP Terraform needs user access to repositories to create webhooks and ingress configurations. ~> **Important**: In GitLab CE or EE 10.6 and up, you may also need to enable **Allow requests to the local network from hooks and services** on the "Outbound requests" section inside the Admin area under Settings (`/admin/application_settings/network`). Refer to [the GitLab documentation](https://docs.gitlab.com/ee/security/webhooks.html) for details. 1. Navigate to GitLab's "User Settings > Applications" page. This page is located at `https://<GITLAB INSTANCE HOSTNAME>/profile/applications`. You can also reach it through GitLab's menus: - Click your profile picture and choose "Settings." - Click "Applications." 1. This page has a list of applications and a form for adding new ones. The form has two text fields and some checkboxes. Fill out the fields and checkboxes with the corresponding values currently displayed in your HCP Terraform browser tab. HCP Terraform lists the values in the order they appear, and includes controls for copying values to your clipboard. Fill out the form as follows: | Field | Value | | ----------------------- | ---------------------------------------------- | | Name | HCP Terraform (`<YOUR ORGANIZATION NAME>`) | | Redirect URI | `https://app.terraform.io/<YOUR CALLBACK URL>` | | Confidential (checkbox) | ✔️ (enabled) | | Expire access tokens (checkbox) | (no longer required) | | Scopes (all checkboxes) | api | -> **Note:** For previous versions of HCP Terraform and GitLab, we recommended disabling a setting called `Expire access tokens`. This action was required because Gitlab marked OAuth tokens as expired after 2 hours, but HCP Terraform only refreshed tokens after 6 hours. This setting does not exist on Gitlab v15+ and HCP Terraform now refreshes tokens more often. 1. Click the "Save application" button, which creates the application and takes you to its page. 1. Leave this page open in a browser tab. In the next step, you will copy and paste the unique **Application ID** and **Secret.** ## Step 3: On HCP Terraform, Set up Your Provider 1. On the "Configure settings" step on HCP Terraform, enter the **Application ID** and **Secret** from the previous step. 1. Click **Connect and continue.** This takes you to a page on GitLab asking whether you want to authorize the app. Alternatively, if you are redirected to a 500 error, it usually means HCP Terraform was unable to reach your GitLab instance. 1. Click the green **Authorize** button at the bottom of the authorization page. ## Step 4: On HCP Terraform, Configure Advanced Settings (Optional) The settings in this section are optional. The Advanced Settings you can configure are: - **Scope of VCS Provider** - You can configure which workspaces can use repositories from this VCS provider. By default the **All Projects** option is selected, meaning this VCS provider is available to be used by all workspaces in the organization. - **Set up a PEM formatted SSH Keypair** - Most organizations will not need to add an SSH key. However, if the organization repositories include Git submodules that can only be accessed via SSH, an SSH key can be added along with the OAuth credentials. You can add or update the SSH key at a later time. ### If You Don't Need to Configure Advanced Settings: 1. Click the **Skip and Finish** button. This returns you to HCP Terraform's VCS Provider page, which now includes your new GitLab client. ### If You Need to Limit the Scope of this VCS Provider: 1. Select the **Selected Projects** option and use the text field that appears to search for and select projects to enable. All current and future workspaces for any selected projects can use repositories from this VCS Provider. 1. Click the **Update VCS Provider** button to save your selections. ### If You Do Need a PEM formatted SSH Keypair: #### Important Notes - SSH will only be used to clone Git submodules. All other Git operations will still use HTTPS. - Do not use your personal SSH key to connect HCP Terraform and GitLab; generate a new one or use an existing key reserved for service access. - In the following steps, you must provide HCP Terraform with the private key. Although HCP Terraform does not display the text of the key to users after it is entered, it retains it and will use it when authenticating to GitLab. - **Protect this private key carefully.** It can push code to the repositories you use to manage your infrastructure. Take note of your organization's policies for protecting important credentials and be sure to follow them. 1. On a secure workstation, create a PEM formatted SSH keypair that HCP Terraform can use to connect to GitLab. The exact command depends on your OS, but is usually something like: `ssh-keygen -t rsa -m PEM -f "/Users/<NAME>/.ssh/service_terraform" -C "service_terraform_enterprise"` This creates a `service_terraform` file with the private key, and a `service_terraform.pub` file with the public key. This SSH key **must have an empty passphrase**. HCP Terraform cannot use SSH keys that require a passphrase. 1. While logged into the GitLab account you want HCP Terraform to act as, navigate to the SSH Keys settings page, add a new SSH key and paste the value of the SSH public key you just created. 1. In HCP Terraform's **Add VCS Provider** page, paste the text of the **SSH private key** you just created, and click the **Add SSH Key** button. ## Finished At this point, GitLab access for HCP Terraform is fully configured, and you can create Terraform workspaces based on your organization's shared repositories.
terraform
page title GitLab EE and CE VCS Providers HCP Terraform description Learn how to use on premise installation of GitLab Enterprise Edition EE or GitLab Community Edition CE for VCS features Configuring GitLab EE and CE Access These instructions are for using an on premise installation of GitLab Enterprise Edition EE or GitLab Community Edition CE for HCP Terraform s VCS features GitLab com has separate instructions terraform cloud docs vcs gitlab com as do the other supported VCS providers terraform cloud docs vcs Configuring a new VCS provider requires permission to manage VCS settings for the organization More about permissions terraform cloud docs users teams organizations permissions permissions citation intentionally unused keep for maintainers Connecting HCP Terraform to your VCS involves four steps On your VCS On HCP Terraform Create a new connection in HCP Terraform Get redirect URI Register your HCP Terraform organization as a new app Provide redirect URI Get ID and key Provide HCP Terraform with application ID and secret Request VCS access Approve access request The rest of this page explains the on premise GitLab versions of these steps Important HCP Terraform needs to contact your GitLab instance during setup and during normal operation For the SaaS version of HCP Terraform this means GitLab must be internet accessible for Terraform Enterprise you must have network connectivity between your Terraform Enterprise and GitLab instances Note Alternately you can skip the OAuth configuration process and authenticate with a personal access token This requires using HCP Terraform s API For details see the OAuth Clients API page terraform cloud docs api docs oauth clients Version Note HCP Terraform supports GitLab versions 9 0 and newer HashiCorp does not test older versions of GitLab with HCP Terraform and they might not work as expected Also note that although we do not deliberately remove support for versions that have reached end of life per the GitLab Support End of Life Policy https docs gitlab com ee policy maintenance html patch releases our ability to resolve customer issues with end of life versions might be limited Step 1 On HCP Terraform Begin Adding a New VCS Provider 1 Go to your organization s settings and then click Providers The VCS Providers page appears 1 Click Add VCS Provider The VCS Providers page appears 1 Select GitLab and then select GitLab Enterprise Edition or GitLab Community Edition from the menu The page moves to the next step 1 In the Set up provider step fill in the HTTP URL and API URL of your GitLab Enterprise Edition or GitLab Community Edition instance as well as an optional Name for this VCS connection Click Continue Field Value HTTP URL https GITLAB INSTANCE HOSTNAME API URL https GITLAB INSTANCE HOSTNAME api v4 Note that HCP Terraform uses GitLab s v4 API Leave the page open in a browser tab In the next step you will copy values from this page and in later steps you will continue configuring HCP Terraform Step 2 On GitLab Create a New Application 1 In a new browser tab open your GitLab instance and log in as whichever account you want HCP Terraform to act as For most organizations this should be a dedicated service user but a personal account will also work Important The account you use for connecting HCP Terraform must have admin master access to any shared repositories of Terraform configurations since creating webhooks requires admin permissions Do not create the application as an administrative application not owned by a user HCP Terraform needs user access to repositories to create webhooks and ingress configurations Important In GitLab CE or EE 10 6 and up you may also need to enable Allow requests to the local network from hooks and services on the Outbound requests section inside the Admin area under Settings admin application settings network Refer to the GitLab documentation https docs gitlab com ee security webhooks html for details 1 Navigate to GitLab s User Settings Applications page This page is located at https GITLAB INSTANCE HOSTNAME profile applications You can also reach it through GitLab s menus Click your profile picture and choose Settings Click Applications 1 This page has a list of applications and a form for adding new ones The form has two text fields and some checkboxes Fill out the fields and checkboxes with the corresponding values currently displayed in your HCP Terraform browser tab HCP Terraform lists the values in the order they appear and includes controls for copying values to your clipboard Fill out the form as follows Field Value Name HCP Terraform YOUR ORGANIZATION NAME Redirect URI https app terraform io YOUR CALLBACK URL Confidential checkbox enabled Expire access tokens checkbox no longer required Scopes all checkboxes api Note For previous versions of HCP Terraform and GitLab we recommended disabling a setting called Expire access tokens This action was required because Gitlab marked OAuth tokens as expired after 2 hours but HCP Terraform only refreshed tokens after 6 hours This setting does not exist on Gitlab v15 and HCP Terraform now refreshes tokens more often 1 Click the Save application button which creates the application and takes you to its page 1 Leave this page open in a browser tab In the next step you will copy and paste the unique Application ID and Secret Step 3 On HCP Terraform Set up Your Provider 1 On the Configure settings step on HCP Terraform enter the Application ID and Secret from the previous step 1 Click Connect and continue This takes you to a page on GitLab asking whether you want to authorize the app Alternatively if you are redirected to a 500 error it usually means HCP Terraform was unable to reach your GitLab instance 1 Click the green Authorize button at the bottom of the authorization page Step 4 On HCP Terraform Configure Advanced Settings Optional The settings in this section are optional The Advanced Settings you can configure are Scope of VCS Provider You can configure which workspaces can use repositories from this VCS provider By default the All Projects option is selected meaning this VCS provider is available to be used by all workspaces in the organization Set up a PEM formatted SSH Keypair Most organizations will not need to add an SSH key However if the organization repositories include Git submodules that can only be accessed via SSH an SSH key can be added along with the OAuth credentials You can add or update the SSH key at a later time If You Don t Need to Configure Advanced Settings 1 Click the Skip and Finish button This returns you to HCP Terraform s VCS Provider page which now includes your new GitLab client If You Need to Limit the Scope of this VCS Provider 1 Select the Selected Projects option and use the text field that appears to search for and select projects to enable All current and future workspaces for any selected projects can use repositories from this VCS Provider 1 Click the Update VCS Provider button to save your selections If You Do Need a PEM formatted SSH Keypair Important Notes SSH will only be used to clone Git submodules All other Git operations will still use HTTPS Do not use your personal SSH key to connect HCP Terraform and GitLab generate a new one or use an existing key reserved for service access In the following steps you must provide HCP Terraform with the private key Although HCP Terraform does not display the text of the key to users after it is entered it retains it and will use it when authenticating to GitLab Protect this private key carefully It can push code to the repositories you use to manage your infrastructure Take note of your organization s policies for protecting important credentials and be sure to follow them 1 On a secure workstation create a PEM formatted SSH keypair that HCP Terraform can use to connect to GitLab The exact command depends on your OS but is usually something like ssh keygen t rsa m PEM f Users NAME ssh service terraform C service terraform enterprise This creates a service terraform file with the private key and a service terraform pub file with the public key This SSH key must have an empty passphrase HCP Terraform cannot use SSH keys that require a passphrase 1 While logged into the GitLab account you want HCP Terraform to act as navigate to the SSH Keys settings page add a new SSH key and paste the value of the SSH public key you just created 1 In HCP Terraform s Add VCS Provider page paste the text of the SSH private key you just created and click the Add SSH Key button Finished At this point GitLab access for HCP Terraform is fully configured and you can create Terraform workspaces based on your organization s shared repositories
terraform HCP Terraform is more powerful when you integrate it with your version control system VCS provider Although you can use many of HCP Terraform s features without one a VCS connection provides additional features and improved workflows In particular Connecting VCS Providers to HCP Terraform page title Connecting VCS Providers HCP Terraform Learn how to connect a version control system VCS to your organization to integrate HCP Terraform into your development workflow and access additional features
--- page_title: Connecting VCS Providers - HCP Terraform description: >- Learn how to connect a version control system (VCS) to your organization to integrate HCP Terraform into your development workflow and access additional features. --- # Connecting VCS Providers to HCP Terraform HCP Terraform is more powerful when you integrate it with your version control system (VCS) provider. Although you can use many of HCP Terraform's features without one, a VCS connection provides additional features and improved workflows. In particular: - When workspaces are linked to a VCS repository, HCP Terraform can [automatically initiate Terraform runs](/terraform/cloud-docs/run/ui) when changes are committed to the specified branch. - HCP Terraform makes code review easier by [automatically predicting](/terraform/cloud-docs/run/ui#speculative-plans-on-pull-requests) how pull requests will affect infrastructure. - Publishing new versions of a [private Terraform module](/terraform/cloud-docs/registry/publish-modules) is as easy as pushing a tag to the module's repository. We recommend configuring VCS access when first setting up an organization, and you might need to add additional VCS providers later depending on how your organization grows. Configuring a new VCS provider requires permission to manage VCS settings for the organization. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) [permissions-citation]: #intentionally-unused---keep-for-maintainers ## Supported VCS Providers HCP Terraform supports the following VCS providers: <!-- BEGIN: TFC:only --> - [GitHub.com](/terraform/cloud-docs/vcs/github-app) <!-- END: TFC:only --> - [GitHub App for TFE](/terraform/enterprise/admin/application/github-app-integration) - [GitHub.com (OAuth)](/terraform/cloud-docs/vcs/github) - [GitHub Enterprise](/terraform/cloud-docs/vcs/github-enterprise) - [GitLab.com](/terraform/cloud-docs/vcs/gitlab-com) - [GitLab EE and CE](/terraform/cloud-docs/vcs/gitlab-eece) - [Bitbucket Cloud](/terraform/cloud-docs/vcs/bitbucket-cloud) - [Bitbucket Data Center](/terraform/cloud-docs/vcs/bitbucket-data-center) - [Azure DevOps Server](/terraform/cloud-docs/vcs/azure-devops-server) - [Azure DevOps Services](/terraform/cloud-docs/vcs/azure-devops-services) Use the links above to see details on configuring VCS access for each supported provider. If you use another VCS that is not supported, you can build an integration via [the API-driven run workflow](/terraform/cloud-docs/run/api). ## How HCP Terraform Uses VCS Access Most workspaces in HCP Terraform are associated with a VCS repository, which provides Terraform configurations for that workspace. To find out which repos are available, access their contents, and create webhooks, HCP Terraform needs access to your VCS provider. Although HCP Terraform's API lets you create workspaces and push configurations to them without a VCS connection, the primary workflow expects every workspace to be backed by a repository. To use configurations from VCS, HCP Terraform needs to do several things: - Access a list of repositories, to let you search for repos when creating new workspaces. - Register webhooks with your VCS provider, to get notified of new commits to a chosen branch. - Download the contents of a repository at a specific commit in order to run Terraform with that code. ~> **Important:** HCP Terraform usually performs VCS actions using a designated VCS user account, but it has no other knowledge about your VCS's authorization controls and does not associate HCP Terraform user accounts with VCS user accounts. This means HCP Terraform's VCS user might have a different level of access to repositories than any given HCP Terraform user. Keep this in mind when selecting a VCS user, as it may affect your security posture in one or both systems. ### Webhooks HCP Terraform uses webhooks to monitor new commits and pull requests. - When someone adds new commits to a branch, any HCP Terraform workspaces based on that branch will begin a Terraform run. Usually a user must inspect the plan output and approve an apply, but you can also enable automatic applies on a per-workspace basis. You can prevent automatic runs by locking a workspace. A run will only occur if the workspace has not previously processed a run for the commit SHA. - When someone submits a pull request/merge request to a branch, any HCP Terraform workspaces based on that branch will perform a [speculative plan](/terraform/cloud-docs/run/remote-operations#speculative-plans) with the contents of the request and links to the results on the PR's page. This helps you avoid merging PRs that cause plan failures. ~> **Important:** In Terraform Enterprise, integration with a SaaS VCS provider (GitHub.com, GitLab.com, Bitbucket Cloud, or Azure DevOps Services) requires ingress from the public internet. This lets the inbound web hooks reach Terraform Enterprise. You should also configure appropriate security controls, such as a Web Application Firewall (WAF). ### SSH Keys For most supported VCS providers, HCP Terraform does not need an SSH key. This is because Terraform can do everything it needs with the provider's API and an OAuth token. The exceptions are Azure DevOps Server and Bitbucket Data Center, which require an SSH key for downloading repository contents. Refer to the setup instructions for [Azure DevOps Server](/terraform/cloud-docs/vcs/azure-devops-server) and [Bitbucket Data Center](/terraform/cloud-docs/vcs/bitbucket-data-center) for details. For other VCS providers, most organizations will not need to add an SSH private key. However, if the organization repositories include Git submodules that can only be accessed via SSH, an SSH key can be added along with the OAuth credentials. For VCS providers where adding an SSH private key is optional, SSH will only be used to clone Git submodules. All other Git operations will still use HTTPS. If submodules will be cloned via SSH from a private VCS instance, SSH must be running on the standard port 22 on the VCS server. To add an SSH key to a VCS connection, finish configuring OAuth in the organization settings, and then use the "add a private SSH key" link on the VCS Provider settings page to add a private key that has access to the submodule repositories. When setting up a workspace, if submodules are required, select "Include submodules on clone". More at [Workspace settings](/terraform/cloud-docs/workspaces/settings). ### Multiple VCS Connections If your infrastructure code is spread across multiple VCS providers, you can configure multiple VCS connections. You can choose which VCS connection to use whenever you create a new workspace. #### Scoping VCS Connections using Projects You can configure which projects can use repositories from a VCS connection. By default each VCS connection is enabled for all workspaces in the organization. If you need to limit which projects can use repositories from a given VCS connection, you can change this setting to enable the connection for only workspaces in the selected projects. ## Configuring VCS Access HCP Terraform uses the OAuth protocol to authenticate with VCS providers. ~> **Important:** Even if you've used OAuth before, read the instructions carefully. Since HCP Terraform's security model treats each _organization_ as a separate OAuth application, we authenticate with OAuth's developer workflow, which is more complex than the standard user workflow. The exact steps to authenticate are different for each VCS provider, but they follow this general order: | On your VCS | On HCP Terraform | | ------------------------------------------------------------------------ | -------------------------------------------------------------------------------- | | Register your HCP Terraform organization as a new app. Get ID and key. |   | |   | Tell HCP Terraform how to reach VCS, and provide ID and key. Get callback URL. | | Provide callback URL. |   | |   | Request VCS access. | | Approve access request. |   | For complete details, click the link for your VCS provider: - [GitHub](/terraform/cloud-docs/vcs/github) - [GitHub Enterprise](/terraform/cloud-docs/vcs/github-enterprise) - [GitLab.com](/terraform/cloud-docs/vcs/gitlab-com) - [GitLab EE and CE](/terraform/cloud-docs/vcs/gitlab-eece) - [Bitbucket Cloud](/terraform/cloud-docs/vcs/bitbucket-cloud) - [Bitbucket Data Center](/terraform/cloud-docs/vcs/bitbucket-data-center) - [Azure DevOps Server](/terraform/cloud-docs/vcs/azure-devops-server) - [Azure DevOps Services](/terraform/cloud-docs/vcs/azure-devops-services) -> **Note:** Alternatively, you can skip the OAuth configuration process and authenticate with a personal access token. This requires using HCP Terraform's API. For details, see [the OAuth Clients API page](/terraform/cloud-docs/api-docs/oauth-clients). <!-- BEGIN: TFC:only --> ### Private VCS You can use self-hosted HCP Terraform Agents to connect HCP Terraform to your private VCS provider, such as GitHub Enterprise, GitLab Enterprise, and BitBucket Data Center. For more information, refer to [Connect to Private VCS Providers](/terraform/cloud-docs/vcs/private). <!-- END: TFC:only --> ## Viewing events VCS events describe changes within your organization for VCS-related actions. The VCS events page only displays events from previously processed commits in the past 30 days. The VCS page indicates previously processed commits with the message, `"Processing skipped for duplicate commit SHA"`. Viewing VCS events requires permission to manage VCS settings for the organization. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) [permissions-citation]: #intentionally-unused---keep-for-maintainers To view VCS events for your organization, go to your organization's settings and click **Events**. The **VCS Events** page appears.
terraform
page title Connecting VCS Providers HCP Terraform description Learn how to connect a version control system VCS to your organization to integrate HCP Terraform into your development workflow and access additional features Connecting VCS Providers to HCP Terraform HCP Terraform is more powerful when you integrate it with your version control system VCS provider Although you can use many of HCP Terraform s features without one a VCS connection provides additional features and improved workflows In particular When workspaces are linked to a VCS repository HCP Terraform can automatically initiate Terraform runs terraform cloud docs run ui when changes are committed to the specified branch HCP Terraform makes code review easier by automatically predicting terraform cloud docs run ui speculative plans on pull requests how pull requests will affect infrastructure Publishing new versions of a private Terraform module terraform cloud docs registry publish modules is as easy as pushing a tag to the module s repository We recommend configuring VCS access when first setting up an organization and you might need to add additional VCS providers later depending on how your organization grows Configuring a new VCS provider requires permission to manage VCS settings for the organization More about permissions terraform cloud docs users teams organizations permissions permissions citation intentionally unused keep for maintainers Supported VCS Providers HCP Terraform supports the following VCS providers BEGIN TFC only GitHub com terraform cloud docs vcs github app END TFC only GitHub App for TFE terraform enterprise admin application github app integration GitHub com OAuth terraform cloud docs vcs github GitHub Enterprise terraform cloud docs vcs github enterprise GitLab com terraform cloud docs vcs gitlab com GitLab EE and CE terraform cloud docs vcs gitlab eece Bitbucket Cloud terraform cloud docs vcs bitbucket cloud Bitbucket Data Center terraform cloud docs vcs bitbucket data center Azure DevOps Server terraform cloud docs vcs azure devops server Azure DevOps Services terraform cloud docs vcs azure devops services Use the links above to see details on configuring VCS access for each supported provider If you use another VCS that is not supported you can build an integration via the API driven run workflow terraform cloud docs run api How HCP Terraform Uses VCS Access Most workspaces in HCP Terraform are associated with a VCS repository which provides Terraform configurations for that workspace To find out which repos are available access their contents and create webhooks HCP Terraform needs access to your VCS provider Although HCP Terraform s API lets you create workspaces and push configurations to them without a VCS connection the primary workflow expects every workspace to be backed by a repository To use configurations from VCS HCP Terraform needs to do several things Access a list of repositories to let you search for repos when creating new workspaces Register webhooks with your VCS provider to get notified of new commits to a chosen branch Download the contents of a repository at a specific commit in order to run Terraform with that code Important HCP Terraform usually performs VCS actions using a designated VCS user account but it has no other knowledge about your VCS s authorization controls and does not associate HCP Terraform user accounts with VCS user accounts This means HCP Terraform s VCS user might have a different level of access to repositories than any given HCP Terraform user Keep this in mind when selecting a VCS user as it may affect your security posture in one or both systems Webhooks HCP Terraform uses webhooks to monitor new commits and pull requests When someone adds new commits to a branch any HCP Terraform workspaces based on that branch will begin a Terraform run Usually a user must inspect the plan output and approve an apply but you can also enable automatic applies on a per workspace basis You can prevent automatic runs by locking a workspace A run will only occur if the workspace has not previously processed a run for the commit SHA When someone submits a pull request merge request to a branch any HCP Terraform workspaces based on that branch will perform a speculative plan terraform cloud docs run remote operations speculative plans with the contents of the request and links to the results on the PR s page This helps you avoid merging PRs that cause plan failures Important In Terraform Enterprise integration with a SaaS VCS provider GitHub com GitLab com Bitbucket Cloud or Azure DevOps Services requires ingress from the public internet This lets the inbound web hooks reach Terraform Enterprise You should also configure appropriate security controls such as a Web Application Firewall WAF SSH Keys For most supported VCS providers HCP Terraform does not need an SSH key This is because Terraform can do everything it needs with the provider s API and an OAuth token The exceptions are Azure DevOps Server and Bitbucket Data Center which require an SSH key for downloading repository contents Refer to the setup instructions for Azure DevOps Server terraform cloud docs vcs azure devops server and Bitbucket Data Center terraform cloud docs vcs bitbucket data center for details For other VCS providers most organizations will not need to add an SSH private key However if the organization repositories include Git submodules that can only be accessed via SSH an SSH key can be added along with the OAuth credentials For VCS providers where adding an SSH private key is optional SSH will only be used to clone Git submodules All other Git operations will still use HTTPS If submodules will be cloned via SSH from a private VCS instance SSH must be running on the standard port 22 on the VCS server To add an SSH key to a VCS connection finish configuring OAuth in the organization settings and then use the add a private SSH key link on the VCS Provider settings page to add a private key that has access to the submodule repositories When setting up a workspace if submodules are required select Include submodules on clone More at Workspace settings terraform cloud docs workspaces settings Multiple VCS Connections If your infrastructure code is spread across multiple VCS providers you can configure multiple VCS connections You can choose which VCS connection to use whenever you create a new workspace Scoping VCS Connections using Projects You can configure which projects can use repositories from a VCS connection By default each VCS connection is enabled for all workspaces in the organization If you need to limit which projects can use repositories from a given VCS connection you can change this setting to enable the connection for only workspaces in the selected projects Configuring VCS Access HCP Terraform uses the OAuth protocol to authenticate with VCS providers Important Even if you ve used OAuth before read the instructions carefully Since HCP Terraform s security model treats each organization as a separate OAuth application we authenticate with OAuth s developer workflow which is more complex than the standard user workflow The exact steps to authenticate are different for each VCS provider but they follow this general order On your VCS On HCP Terraform Register your HCP Terraform organization as a new app Get ID and key Tell HCP Terraform how to reach VCS and provide ID and key Get callback URL Provide callback URL Request VCS access Approve access request For complete details click the link for your VCS provider GitHub terraform cloud docs vcs github GitHub Enterprise terraform cloud docs vcs github enterprise GitLab com terraform cloud docs vcs gitlab com GitLab EE and CE terraform cloud docs vcs gitlab eece Bitbucket Cloud terraform cloud docs vcs bitbucket cloud Bitbucket Data Center terraform cloud docs vcs bitbucket data center Azure DevOps Server terraform cloud docs vcs azure devops server Azure DevOps Services terraform cloud docs vcs azure devops services Note Alternatively you can skip the OAuth configuration process and authenticate with a personal access token This requires using HCP Terraform s API For details see the OAuth Clients API page terraform cloud docs api docs oauth clients BEGIN TFC only Private VCS You can use self hosted HCP Terraform Agents to connect HCP Terraform to your private VCS provider such as GitHub Enterprise GitLab Enterprise and BitBucket Data Center For more information refer to Connect to Private VCS Providers terraform cloud docs vcs private END TFC only Viewing events VCS events describe changes within your organization for VCS related actions The VCS events page only displays events from previously processed commits in the past 30 days The VCS page indicates previously processed commits with the message Processing skipped for duplicate commit SHA Viewing VCS events requires permission to manage VCS settings for the organization More about permissions terraform cloud docs users teams organizations permissions permissions citation intentionally unused keep for maintainers To view VCS events for your organization go to your organization s settings and click Events The VCS Events page appears
terraform This topic describes how to connect Bitbucket Cloud to HCP Terraform Bitbucket Cloud is the cloud hosted version of Bitbucket For self hosted Bitbucket Data Center instances refer to Configuring Bitbucket Data Center Access terraform cloud docs vcs bitbucket data center Refer to Connecting VCS Providers to HCP Terraform terraform cloud docs vcs for other supported VCS providers Configuring Bitbucket Cloud Access Learn how to use Bitbucket Cloud for VCS features page title Bitbucket Cloud VCS Providers HCP Terraform
--- page_title: Bitbucket Cloud - VCS Providers - HCP Terraform description: >- Learn how to use Bitbucket Cloud for VCS features. --- # Configuring Bitbucket Cloud Access This topic describes how to connect Bitbucket Cloud to HCP Terraform. Bitbucket Cloud is the cloud-hosted version of Bitbucket. For self-hosted Bitbucket Data Center instances, refer to [Configuring Bitbucket Data Center Access](/terraform/cloud-docs/vcs/bitbucket-data-center). Refer to [Connecting VCS Providers to HCP Terraform](/terraform/cloud-docs/vcs) for other supported VCS providers. Configuring a new VCS provider requires permission to manage VCS settings for the organization. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) [permissions-citation]: #intentionally-unused---keep-for-maintainers Connecting HCP Terraform to your VCS involves four steps: | On your VCS | On HCP Terraform | | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | |   | Create a new connection in HCP Terraform. Get callback URL. | | Register your HCP Terraform organization as a new app. Provide callback URL. Get ID and key. |   | |   | Provide HCP Terraform with ID and key. Request VCS access. | | Approve access request. |   | The rest of this page explains the Bitbucket Cloud-specific versions of these steps. ## Step 1: On HCP Terraform, Begin Adding a New VCS Provider 1. Go to your organization's settings and then click **Providers**. The **VCS Providers** page appears. 1. Click **Add VCS Provider**. The **VCS Providers** page appears. 1. Select **Bitbucket** and then select **Bitbucket Cloud** from the menu. The page moves to the next step. Leave the page open in a browser tab. In the next step you will copy values from this page, and in later steps you will continue configuring HCP Terraform. ## Step 2: On Bitbucket Cloud, Create a New OAuth Consumer 1. In a new browser tab, open [Bitbucket Cloud](https://bitbucket.org) and log in as whichever account you want HCP Terraform to act as. For most organizations this should be a dedicated service user, but a personal account will also work. ~> **Important:** The account you use for connecting HCP Terraform **must have admin access** to any shared repositories of Terraform configurations, since creating webhooks requires admin permissions. 1. Navigate to Bitbucket's "Add OAuth Consumer" page. This page is located at `https://bitbucket.org/<YOUR WORKSPACE NAME>/workspace/settings/oauth-consumers/new`. You can also reach it through Bitbucket's menus: - Click your profile picture and choose the workspace you want to access. - Click "Settings". - Click "OAuth consumers," which is in the "Apps and Features" section. - On the OAuth settings page, click the "Add consumer" button. 1. This page has a form with several text fields and checkboxes. Fill out the fields and checkboxes with the corresponding values currently displayed in your HCP Terraform browser tab. HCP Terraform lists the values in the order they appear, and includes controls for copying values to your clipboard. Fill out the text fields as follows: | Field | Value | | ------------ | ----------------------------------------------------------------------------- | | Name | HCP Terraform (`<YOUR ORGANIZATION NAME>`) | | Description | Any description of your choice. | | Callback URL | `https://app.terraform.io/<YOUR CALLBACK URL>` | | URL | `https://app.terraform.io` (or the URL of your Terraform Enterprise instance) | Ensure that the "This is a private consumer" option is checked. Then, activate the following permissions checkboxes: | Permission type | Permission level | | --------------- | ---------------- | | Account | Write | | Repositories | Admin | | Pull requests | Write | | Webhooks | Read and write | 1. Click the "Save" button, which returns you to the OAuth settings page. 1. Find your new OAuth consumer under the "OAuth Consumers" heading, and click its name to reveal its details. Leave this page open in a browser tab. In the next step, you will copy and paste the unique **Key** and **Secret.** ## Step 3: On HCP Terraform, Set up Your Provider 1. Enter the **Key** and **Secret** from the previous step, as well as an optional **Name** for this VCS connection. 1. Click "Connect and continue." This takes you to a page on Bitbucket Cloud asking whether you want to authorize the app. 1. Click the blue "Grant access" button to proceed. ## Step 4: On HCP Terraform, Configure Advanced Settings (Optional) The settings in this section are optional. The Advanced Settings you can configure are: - **Scope of VCS Provider** - You can configure which workspaces can use repositories from this VCS provider. By default the **All Projects** option is selected, meaning this VCS provider is available to be used by all workspaces in the organization. - **Set up SSH Keypair** - Most organizations will not need to add an SSH key. However, if the organization repositories include Git submodules that can only be accessed via SSH, an SSH key can be added along with the OAuth credentials. You can add or update the SSH key at a later time. ### If You Don't Need to Configure Advanced Settings: 1. Click the **Skip and Finish** button. This returns you to HCP Terraform's VCS Provider page, which now includes your new Bitbucket Cloud client. ### If You Need to Limit the Scope of this VCS Provider: 1. Select the **Selected Projects** option and use the text field that appears to search for and select projects to enable. All current and future workspaces for any selected projects can use repositories from this VCS Provider. 1. Click the **Update VCS Provider** button to save your selections. ### If You Do Need an SSH Keypair: #### Important Notes - SSH will only be used to clone Git submodules. All other Git operations will still use HTTPS. - Do not use your personal SSH key to connect HCP Terraform and Bitbucket Cloud; generate a new one or use an existing key reserved for service access. - In the following steps, you must provide HCP Terraform with the private key. Although HCP Terraform does not display the text of the key to users after it is entered, it retains it and will use it when authenticating to Bitbucket Cloud. - **Protect this private key carefully.** It can push code to the repositories you use to manage your infrastructure. Take note of your organization's policies for protecting important credentials and be sure to follow them. 1. On a secure workstation, create an SSH keypair that HCP Terraform can use to connect to Bitbucket Cloud. The exact command depends on your OS, but is usually something like: `ssh-keygen -t rsa -m PEM -f "/Users/<NAME>/.ssh/service_terraform" -C "service_terraform_enterprise"` This creates a `service_terraform` file with the private key, and a `service_terraform.pub` file with the public key. This SSH key **must have an empty passphrase**. HCP Terraform cannot use SSH keys that require a passphrase. 1. While logged into the Bitbucket Cloud account you want HCP Terraform to act as, navigate to the SSH Keys settings page, add a new SSH key and paste the value of the SSH public key you just created. 1. In HCP Terraform's **Add VCS Provider** page, paste the text of the **SSH private key** you just created, and click the **Add SSH Key** button. ## Finished At this point, Bitbucket Cloud access for HCP Terraform is fully configured, and you can create Terraform workspaces based on your organization's shared repositories.
terraform
page title Bitbucket Cloud VCS Providers HCP Terraform description Learn how to use Bitbucket Cloud for VCS features Configuring Bitbucket Cloud Access This topic describes how to connect Bitbucket Cloud to HCP Terraform Bitbucket Cloud is the cloud hosted version of Bitbucket For self hosted Bitbucket Data Center instances refer to Configuring Bitbucket Data Center Access terraform cloud docs vcs bitbucket data center Refer to Connecting VCS Providers to HCP Terraform terraform cloud docs vcs for other supported VCS providers Configuring a new VCS provider requires permission to manage VCS settings for the organization More about permissions terraform cloud docs users teams organizations permissions permissions citation intentionally unused keep for maintainers Connecting HCP Terraform to your VCS involves four steps On your VCS On HCP Terraform Create a new connection in HCP Terraform Get callback URL Register your HCP Terraform organization as a new app Provide callback URL Get ID and key Provide HCP Terraform with ID and key Request VCS access Approve access request The rest of this page explains the Bitbucket Cloud specific versions of these steps Step 1 On HCP Terraform Begin Adding a New VCS Provider 1 Go to your organization s settings and then click Providers The VCS Providers page appears 1 Click Add VCS Provider The VCS Providers page appears 1 Select Bitbucket and then select Bitbucket Cloud from the menu The page moves to the next step Leave the page open in a browser tab In the next step you will copy values from this page and in later steps you will continue configuring HCP Terraform Step 2 On Bitbucket Cloud Create a New OAuth Consumer 1 In a new browser tab open Bitbucket Cloud https bitbucket org and log in as whichever account you want HCP Terraform to act as For most organizations this should be a dedicated service user but a personal account will also work Important The account you use for connecting HCP Terraform must have admin access to any shared repositories of Terraform configurations since creating webhooks requires admin permissions 1 Navigate to Bitbucket s Add OAuth Consumer page This page is located at https bitbucket org YOUR WORKSPACE NAME workspace settings oauth consumers new You can also reach it through Bitbucket s menus Click your profile picture and choose the workspace you want to access Click Settings Click OAuth consumers which is in the Apps and Features section On the OAuth settings page click the Add consumer button 1 This page has a form with several text fields and checkboxes Fill out the fields and checkboxes with the corresponding values currently displayed in your HCP Terraform browser tab HCP Terraform lists the values in the order they appear and includes controls for copying values to your clipboard Fill out the text fields as follows Field Value Name HCP Terraform YOUR ORGANIZATION NAME Description Any description of your choice Callback URL https app terraform io YOUR CALLBACK URL URL https app terraform io or the URL of your Terraform Enterprise instance Ensure that the This is a private consumer option is checked Then activate the following permissions checkboxes Permission type Permission level Account Write Repositories Admin Pull requests Write Webhooks Read and write 1 Click the Save button which returns you to the OAuth settings page 1 Find your new OAuth consumer under the OAuth Consumers heading and click its name to reveal its details Leave this page open in a browser tab In the next step you will copy and paste the unique Key and Secret Step 3 On HCP Terraform Set up Your Provider 1 Enter the Key and Secret from the previous step as well as an optional Name for this VCS connection 1 Click Connect and continue This takes you to a page on Bitbucket Cloud asking whether you want to authorize the app 1 Click the blue Grant access button to proceed Step 4 On HCP Terraform Configure Advanced Settings Optional The settings in this section are optional The Advanced Settings you can configure are Scope of VCS Provider You can configure which workspaces can use repositories from this VCS provider By default the All Projects option is selected meaning this VCS provider is available to be used by all workspaces in the organization Set up SSH Keypair Most organizations will not need to add an SSH key However if the organization repositories include Git submodules that can only be accessed via SSH an SSH key can be added along with the OAuth credentials You can add or update the SSH key at a later time If You Don t Need to Configure Advanced Settings 1 Click the Skip and Finish button This returns you to HCP Terraform s VCS Provider page which now includes your new Bitbucket Cloud client If You Need to Limit the Scope of this VCS Provider 1 Select the Selected Projects option and use the text field that appears to search for and select projects to enable All current and future workspaces for any selected projects can use repositories from this VCS Provider 1 Click the Update VCS Provider button to save your selections If You Do Need an SSH Keypair Important Notes SSH will only be used to clone Git submodules All other Git operations will still use HTTPS Do not use your personal SSH key to connect HCP Terraform and Bitbucket Cloud generate a new one or use an existing key reserved for service access In the following steps you must provide HCP Terraform with the private key Although HCP Terraform does not display the text of the key to users after it is entered it retains it and will use it when authenticating to Bitbucket Cloud Protect this private key carefully It can push code to the repositories you use to manage your infrastructure Take note of your organization s policies for protecting important credentials and be sure to follow them 1 On a secure workstation create an SSH keypair that HCP Terraform can use to connect to Bitbucket Cloud The exact command depends on your OS but is usually something like ssh keygen t rsa m PEM f Users NAME ssh service terraform C service terraform enterprise This creates a service terraform file with the private key and a service terraform pub file with the public key This SSH key must have an empty passphrase HCP Terraform cannot use SSH keys that require a passphrase 1 While logged into the Bitbucket Cloud account you want HCP Terraform to act as navigate to the SSH Keys settings page add a new SSH key and paste the value of the SSH public key you just created 1 In HCP Terraform s Add VCS Provider page paste the text of the SSH private key you just created and click the Add SSH Key button Finished At this point Bitbucket Cloud access for HCP Terraform is fully configured and you can create Terraform workspaces based on your organization s shared repositories
terraform Learn how to use Bitbucket Data Center for VCS features Configuring Bitbucket Data Center Access page title Bitbucket Data Center VCS Providers HCP Terraform This topic describes how to connect Bitbucket Data Center to HCP Terraform For instructions on how to connect Bitbucket Cloud refer to Configuring Bitbucket Cloud Access terraform cloud docs vcs bitbucket cloud Refer to Connecting VCS Providers to HCP Terraform terraform cloud docs vcs for other supported VCS providers
--- page_title: Bitbucket Data Center - VCS Providers - HCP Terraform description: >- Learn how to use Bitbucket Data Center for VCS features. --- # Configuring Bitbucket Data Center Access This topic describes how to connect Bitbucket Data Center to HCP Terraform. For instructions on how to connect Bitbucket Cloud, refer to [Configuring Bitbucket Cloud Access](/terraform/cloud-docs/vcs/bitbucket-cloud). Refer to [Connecting VCS Providers to HCP Terraform](/terraform/cloud-docs/vcs) for other supported VCS providers. **Bitbucket Server is deprecated**. Atlassian ended support for Bitbucket Server on February 15, 2024, and recommends using either Bitbucket Data Center (v8.0 or newer) or Bitbucket Cloud instead. Refer to the [Atlassian documentation](https://bitbucket.org/blog/cloud-migration-benefits) for additional information. HCP Terraform will end support Bitbucket Server on August 15, 2024. Terraform Enterprise will also end support for Bitbucket Server in Terraform Enterprise v202410. [Contact HashiCorp support](https://support.hashicorp.com/hc/en-us) if you have any questions regarding this change. ## Overview The following steps provide an overview of how to connect HCP Terraform and Terraform Enterprise to Bitbucket Data Center: 1. Add a new VCS provider to HCP Terraform or Enterprise. 1. Create a new application link in Bitbucket. 1. Create an SSH key pair. SSH keys must have an empty passphrase because HCP Terraform cannot use SSH keys that require a passphrase. 1. Add an SSH key to Bitbucket. You must complete this step as a non-administrator user in Bitbucket. 1. Add the private SSH key to Terraform. ## Requirements - You must have permission to manage VCS settings for the organization. Refer to [Permissions](/terraform/cloud-docs/users-teams-organizations/permissions) for additional information. [permissions-citation]:#intentionally-unused---keep-for-maintainers - You must have OAuth authentication credentials for Bitbucket Data Center. - Your instance of Bitbucket Data Center must be internet-accessible on its SSH and HTTP(S) ports. This is because HCP Terraform must be able to contact Bitbucket Data Center over both SSH and HTTP or HTTPS during setup and during normal operation. - HCP Terraform must have network connectivity to Bitbucket Data Center instances. Note that [Bitbucket Data Center's default ports](https://confluence.atlassian.com/bitbucketserverkb/which-ports-does-bitbucket-server-listen-on-and-what-are-they-used-for-806029586.html) are `7999` for SSH and `7990` for HTTP. Check your configuration to confirm your BitBucket instance's real ports. ## Add a new VCS provider to Terraform 1. Go to your organization's settings and then click **Providers**. The **VCS Providers** page appears. 1. Click **Add VCS Provider**. The **VCS Providers** page appears. 1. Choose **Bitbucket Data Center** from the **Bitbucket** drop-down menu. 1. (Optional) Enter a **Name** for this VCS connection. 1. Specify the URL of your Bitbucket Data Center instance in the **HTTP URL** and **API URL** fields. If the context path is not set for your Bitbucket Data Center instance, the **API URL** is the same as the **HTTP URL**. Refer to the [Atlassian documentation](https://confluence.atlassian.com/bitbucketserver/moving-bitbucket-server-to-a-different-context-path-776640153.html) for additional information. Specify the following values if the context path is set for your Bitbucket Data Center instance: - Set the **HTTP URL** field to your Bitbucket Data Center instance URL and add the context path: `https://<BITBUCKET INSTANCE HOSTNAME>/<CONTEXT PATH>`. - Set the **API URL** field to your Bitbucket Data Center instance URL: `https://<BITBUCKET INSTANCE HOSTNAME>`. By default, HCP Terraform uses port `80` for HTTP and `443` for HTTPS. If Bitbucket Data Center is configured to use non-standard ports or is behind a reverse proxy, you may need to include the port number in the URL. 1. You can either generate new consumer and public keys that you can use to create a new application link in Bitbucket Data Center described in [Create an application link](#create-an-application-link) or use keys from an existing application link: - To generate new keys, click **Continue**. Do not leave this screen until you have copied the key values. - To use existing keys, enable the **Use Custom Keys** option and enter them into the fields. ## Create an application link 1. Log into Bitbucket Data Center as an admin. 1. Open the **Application Links** administration page using the navigation or by entering `https://<BITBUCKET INSTANCE HOSTNAME>/plugins/servlet/applinks/listApplicationLinks` in your browser's address bar. 1. Click **Application Links** in the sidebar, then click **Create new link**. 1. Choose **Atlassian product** as the link type. This option also works for external applications and lets you continue to use OAuth 1.0 integrations. 1. Enter `https://app.terraform.io` or the hostname of your Terraform Enterprise instance when prompted. You can only specify the main URL once. To connect multiple HCP Terraform organizations to the same Bitbucket Data Center instance, enter the organization URL when creating the link instead. The organization URL is the HCP Terraform URL or Terraform Enterprise hostname appended with `/app/<ORG NAME>`. 1. When prompted, confirm that you wish to use the URL as entered. If you specified HCP Terraform's main URL, click **Continue**. If you specified an organization URL, enable the **Use this URL** option and then click **Continue**. 1. In the **Link applications** dialog, configure the following settings: - Specify `HCP Terraform <ORG NAME>` in the **Application Name** field - Choose **Generic Application** from the **Application Type** drop-down menu - Enable the **Create incoming link** option Leave all the other fields empty. 1. Click **Continue**. The **Link applications** screen progresses to the second configuration screen. 1. In the **Consumer Key** and **Public Key** fields, enter the key values you created in the [Add a new VCS provider to Terraform](#add-a-new-vcs-provider-to-terraform) instructions. 1. In the **Consumer Name** field, enter `HCP Terraform (<ORG NAME>)`. 1. Click **Continue**. Bitbucket prompts you to authorize Terraform to make changes. Before you proceed, verify that you are logged in with the user account that HCP Terraform will use to access Bitbucket and not as a Bitbucket administrator. If Bitbucket returns a 500 error instead of the authorization screen, Terraform may have been unable to reach your Bitbucket Data Center instance. 1. Click **Allow** and enter the SSH key when prompted. ## Create an SSH key for Terraform On a secure workstation, create an SSH keypair that HCP Terraform or Terraform Enterprise can use to connect to Bitbucket Data Center. The command for generating SSH keys depends on your OS. The following example for Linux creates a `service_terraform` file with the private key and a `service_terraform.pub` file with the public key: ```shell-session $ ssh-keygen -t rsa -m PEM -f "/Users/<NAME>/.ssh/service_terraform" -C "service_terraform_enterprise" ``` Do not specify a passphrase because Terraform cannot use SSH keys that require a passphrase. ## Add an SSH key to Bitbucket In the following steps, you must provide HCP Terraform with the private SSH key you created in [Create an SSH key for Terraform](#create-an-ssh-key-for-terraform). Although HCP Terraform does not display the text of the key to users after it is entered, it retains the key and uses it for authenticating to Bitbucket Data Center. 1. If you are logged into Bitbucket Data Center as an administrator, log out before proceeding. 1. Log in with the account that you want to enable HCP Terraform or Terraform Enterprise to log in with. Many organizations use a dedicated service user account for this purpose. The account you use for connecting HCP Terraform must have admin access to any shared repositories of Terraform configurations because since creating webhooks requires admin permissions. Refer to [Requirements](#requirements) for additional information. 1. Open the **SSH keys** page and click the profile icon. 1. Choose **Manage account**. 1. Click **SSH keys** or enter `https://<BITBUCKET INSTANCE HOSTNAME>/plugins/servlet/ssh/account/keys` in the address bar to go to the **SSH keys** screen. 1. Click **Add key** and enter the SSH public key you created in [Create an SSH key for Terraform](#create-an-ssh-key-for-terraform) into the text field. Open the `.pub` file to get the key value. 1. Click **Add key** to finish adding the key. ## Add an SSH private key Complete the following steps in HCP Terraform or Terraform Enterprise to request access to Bitbucket and add the SSH private key. 1. Open the **SSH keys** settings page and click **Add a private SSH key**. A large text field appears. 1. Enter the text of the **SSH private key** you created in [Create an SSH key for Terraform](#create-an-ssh-key-for-terraform) and click **Add SSH Key**. ## Next steps After completing these instructions, you can create Terraform workspaces based on your organization's shared repositories. Refer to the following resources for additional guidance: - [Creating Workspaces](/terraform/cloud-docs/workspaces/create) in HCP Terraform - [Creating Workspaces](/terraform/enterprise/workspaces/create) in Terraform Enterprise
terraform
page title Bitbucket Data Center VCS Providers HCP Terraform description Learn how to use Bitbucket Data Center for VCS features Configuring Bitbucket Data Center Access This topic describes how to connect Bitbucket Data Center to HCP Terraform For instructions on how to connect Bitbucket Cloud refer to Configuring Bitbucket Cloud Access terraform cloud docs vcs bitbucket cloud Refer to Connecting VCS Providers to HCP Terraform terraform cloud docs vcs for other supported VCS providers Bitbucket Server is deprecated Atlassian ended support for Bitbucket Server on February 15 2024 and recommends using either Bitbucket Data Center v8 0 or newer or Bitbucket Cloud instead Refer to the Atlassian documentation https bitbucket org blog cloud migration benefits for additional information HCP Terraform will end support Bitbucket Server on August 15 2024 Terraform Enterprise will also end support for Bitbucket Server in Terraform Enterprise v202410 Contact HashiCorp support https support hashicorp com hc en us if you have any questions regarding this change Overview The following steps provide an overview of how to connect HCP Terraform and Terraform Enterprise to Bitbucket Data Center 1 Add a new VCS provider to HCP Terraform or Enterprise 1 Create a new application link in Bitbucket 1 Create an SSH key pair SSH keys must have an empty passphrase because HCP Terraform cannot use SSH keys that require a passphrase 1 Add an SSH key to Bitbucket You must complete this step as a non administrator user in Bitbucket 1 Add the private SSH key to Terraform Requirements You must have permission to manage VCS settings for the organization Refer to Permissions terraform cloud docs users teams organizations permissions for additional information permissions citation intentionally unused keep for maintainers You must have OAuth authentication credentials for Bitbucket Data Center Your instance of Bitbucket Data Center must be internet accessible on its SSH and HTTP S ports This is because HCP Terraform must be able to contact Bitbucket Data Center over both SSH and HTTP or HTTPS during setup and during normal operation HCP Terraform must have network connectivity to Bitbucket Data Center instances Note that Bitbucket Data Center s default ports https confluence atlassian com bitbucketserverkb which ports does bitbucket server listen on and what are they used for 806029586 html are 7999 for SSH and 7990 for HTTP Check your configuration to confirm your BitBucket instance s real ports Add a new VCS provider to Terraform 1 Go to your organization s settings and then click Providers The VCS Providers page appears 1 Click Add VCS Provider The VCS Providers page appears 1 Choose Bitbucket Data Center from the Bitbucket drop down menu 1 Optional Enter a Name for this VCS connection 1 Specify the URL of your Bitbucket Data Center instance in the HTTP URL and API URL fields If the context path is not set for your Bitbucket Data Center instance the API URL is the same as the HTTP URL Refer to the Atlassian documentation https confluence atlassian com bitbucketserver moving bitbucket server to a different context path 776640153 html for additional information Specify the following values if the context path is set for your Bitbucket Data Center instance Set the HTTP URL field to your Bitbucket Data Center instance URL and add the context path https BITBUCKET INSTANCE HOSTNAME CONTEXT PATH Set the API URL field to your Bitbucket Data Center instance URL https BITBUCKET INSTANCE HOSTNAME By default HCP Terraform uses port 80 for HTTP and 443 for HTTPS If Bitbucket Data Center is configured to use non standard ports or is behind a reverse proxy you may need to include the port number in the URL 1 You can either generate new consumer and public keys that you can use to create a new application link in Bitbucket Data Center described in Create an application link create an application link or use keys from an existing application link To generate new keys click Continue Do not leave this screen until you have copied the key values To use existing keys enable the Use Custom Keys option and enter them into the fields Create an application link 1 Log into Bitbucket Data Center as an admin 1 Open the Application Links administration page using the navigation or by entering https BITBUCKET INSTANCE HOSTNAME plugins servlet applinks listApplicationLinks in your browser s address bar 1 Click Application Links in the sidebar then click Create new link 1 Choose Atlassian product as the link type This option also works for external applications and lets you continue to use OAuth 1 0 integrations 1 Enter https app terraform io or the hostname of your Terraform Enterprise instance when prompted You can only specify the main URL once To connect multiple HCP Terraform organizations to the same Bitbucket Data Center instance enter the organization URL when creating the link instead The organization URL is the HCP Terraform URL or Terraform Enterprise hostname appended with app ORG NAME 1 When prompted confirm that you wish to use the URL as entered If you specified HCP Terraform s main URL click Continue If you specified an organization URL enable the Use this URL option and then click Continue 1 In the Link applications dialog configure the following settings Specify HCP Terraform ORG NAME in the Application Name field Choose Generic Application from the Application Type drop down menu Enable the Create incoming link option Leave all the other fields empty 1 Click Continue The Link applications screen progresses to the second configuration screen 1 In the Consumer Key and Public Key fields enter the key values you created in the Add a new VCS provider to Terraform add a new vcs provider to terraform instructions 1 In the Consumer Name field enter HCP Terraform ORG NAME 1 Click Continue Bitbucket prompts you to authorize Terraform to make changes Before you proceed verify that you are logged in with the user account that HCP Terraform will use to access Bitbucket and not as a Bitbucket administrator If Bitbucket returns a 500 error instead of the authorization screen Terraform may have been unable to reach your Bitbucket Data Center instance 1 Click Allow and enter the SSH key when prompted Create an SSH key for Terraform On a secure workstation create an SSH keypair that HCP Terraform or Terraform Enterprise can use to connect to Bitbucket Data Center The command for generating SSH keys depends on your OS The following example for Linux creates a service terraform file with the private key and a service terraform pub file with the public key shell session ssh keygen t rsa m PEM f Users NAME ssh service terraform C service terraform enterprise Do not specify a passphrase because Terraform cannot use SSH keys that require a passphrase Add an SSH key to Bitbucket In the following steps you must provide HCP Terraform with the private SSH key you created in Create an SSH key for Terraform create an ssh key for terraform Although HCP Terraform does not display the text of the key to users after it is entered it retains the key and uses it for authenticating to Bitbucket Data Center 1 If you are logged into Bitbucket Data Center as an administrator log out before proceeding 1 Log in with the account that you want to enable HCP Terraform or Terraform Enterprise to log in with Many organizations use a dedicated service user account for this purpose The account you use for connecting HCP Terraform must have admin access to any shared repositories of Terraform configurations because since creating webhooks requires admin permissions Refer to Requirements requirements for additional information 1 Open the SSH keys page and click the profile icon 1 Choose Manage account 1 Click SSH keys or enter https BITBUCKET INSTANCE HOSTNAME plugins servlet ssh account keys in the address bar to go to the SSH keys screen 1 Click Add key and enter the SSH public key you created in Create an SSH key for Terraform create an ssh key for terraform into the text field Open the pub file to get the key value 1 Click Add key to finish adding the key Add an SSH private key Complete the following steps in HCP Terraform or Terraform Enterprise to request access to Bitbucket and add the SSH private key 1 Open the SSH keys settings page and click Add a private SSH key A large text field appears 1 Enter the text of the SSH private key you created in Create an SSH key for Terraform create an ssh key for terraform and click Add SSH Key Next steps After completing these instructions you can create Terraform workspaces based on your organization s shared repositories Refer to the following resources for additional guidance Creating Workspaces terraform cloud docs workspaces create in HCP Terraform Creating Workspaces terraform enterprise workspaces create in Terraform Enterprise
terraform page title Troubleshooting VCS Providers HCP Terraform Troubleshooting VCS Integration in HCP Terraform This page collects solutions to the most common problems our users encounter with VCS integration in HCP Terraform Learn how to address common problems in VCS integrations
--- page_title: Troubleshooting - VCS Providers - HCP Terraform description: >- Learn how to address common problems in VCS integrations. --- # Troubleshooting VCS Integration in HCP Terraform This page collects solutions to the most common problems our users encounter with VCS integration in HCP Terraform. ## Azure DevOps ### Required status checks not sending When configuring [status checks with Azure DevOps](https://learn.microsoft.com/en-us/azure/devops/repos/git/pr-status-policy) the web interface may auto populate Genre and Name fields (beneath "Status to check") with incorrect values that do not reflect what HCP Terraform is sending. To function correctly as required checks the Genre must be populated with "Terraform Cloud" (or the first segment for a Terraform Enterprise install), and the remainder of the status check goes in the Name field. This requires using the "Enter genre/name separately" checkbox to not use the default configuration. In the example below the status check is named `Terraform Cloud/paul-hcp/gianni-test-1` and needs to be configured with Genre `Terraform Cloud` and Name `paul-hcp/gianni-test-1`. ![Azure DevOps screenshot: configuring required status checks correctly](/img/docs/ado-required-status-check.png) With an older version of Azure DevOps Server it may be that the web interface does not allow entering the Genre and Name separately. In which case the status check will need to be created via the [API](https://learn.microsoft.com/en-us/rest/api/azure/devops/policy/configurations/create). ## Bitbucket Data Center The following errors are specific to Bitbucket Data Center integrations. ### Clicking "Connect organization `<X>`" with Bitbucket Data Center raises an error message in HCP Terraform HCP Terraform uses OAuth 1 to authenticate the user to Bitbucket Data Center. The first step in the authentication process is for HCP Terraform to call Bitbucket Data Center to obtain a request token. After the call completes, HCP Terraform redirects you to Bitbucket Data Center with the request token. An error occurs when HCP Terraform calls to Bitbucket Data Center to obtain the request token but the request is rejected. Some common reasons for the request to be rejected are: - The API endpoint is unreachable; this can happen if the address or port is incorrect or the domain name doesn't resolve. - The certificate used on Bitbucket Data Center is rejected by the HCP Terraform HTTP client because the SSL verification fails. This is often the case with self-signed certificates or when the Terraform Enterprise instance is not configured to trust the signing chain of the Bitbucket Data Center SSL certificate. To fix this issue, do the following: - Verify that the instance running Terraform Enterprise can resolve the domain name and can reach Bitbucket Data Center. - Verify that the HCP Terraform client accepts the HTTPS connection to Bitbucket Data Center. This can be done by performing a `curl` from the Terraform Enterprise instance to Bitbucket Data Center; it should not return any SSL errors. - Verify that the Consumer Key, Consumer Name, and the Public Key are configured properly in Bitbucket Data Center. - Verify that the HTTP URL and API URL in HCP Terraform are correct for your Bitbucket Data Center instance. This includes the proper scheme (HTTP vs HTTPS), as well as the port. ### Creating a workspace from a repository hangs indefinitely, displaying a spinner on the confirm button If you were able to connect HCP Terraform to Bitbucket Data Center but cannot create workspaces, it often means HCP Terraform isn't able to automatically add webhook URLs for that repository. To fix this issue: - Make sure you haven't manually entered any webhook URLs for the affected repository or project. Although the Bitbucket Web Post Hooks Plugin documentation describes how to manually enter a hook URL, HCP Terraform handles this automatically. Manually entered URLs can interfere with HCP Terraform's operation. To check the hook URLs for a repository, go to the repository's settings, then go to the "Hooks" page (in the "Workflow" section) and click on the "Post-Receive WebHooks" link. Also note that some Bitbucket Data Center versions might allow you to set per-project or server-wide hook URLs in addition to per-repository hooks. These should all be empty; if you set a hook URL that might affect more than one repo when installing the plugin, go back and delete it. - Make sure you aren't trying to connect too many workspaces to a single repository. Bitbucket Data Center's webhooks plugin can only attach five hooks to a given repo. You might need to create additional repositories if you need to make more than five workspaces from a single configuration repo. ## Bitbucket Cloud ### HCP Terraform fails to obtain repositories This typically happens when the HCP Terraform application in Bitbucket Cloud wasn't configured to have the full set of permissions. Go to the OAuth section of the Bitbucket settings, find your HCP Terraform OAuth consumer, click the edit link in the "..." menu, and ensure it has the required permissions enabled: | Permission type | Permission level | | --------------- | ---------------- | | Account | Write | | Repositories | Admin | | Pull requests | Write | | Webhooks | Read and write | ## GitHub ### "Host key verification failed" error in `terraform init` when attempting to ingress Terraform modules via Git over SSH This is most common when running Terraform 0.10.3 or 0.10.4, which had a bug in handling SSH submodule ingress. Try upgrading affected HCP Terraform workspaces to the latest Terraform version or 0.10.8 (the latest in the 0.10 series). ### HCP Terraform can't ingress Git submodules, with auth errors during init This usually happens when an SSH key isn't associated with the VCS provider's OAuth client. - Go to your organization's "VCS Provider" settings page and check your GitHub client. If it still says "You can add a private SSH key to this connection to be used for git clone operations" (instead of "A private SSH key has been added..."), you need to click the "add a private SSH key" link and add a key. - Check the settings page for affected workspaces and ensure that "Include submodules on clone" is enabled. Note that the "SSH Key" section in a workspace's settings is only used for mid-run operations like cloning Terraform modules. It isn't used when cloning the linked repository before a run. ## General The following errors may occur for all VCS providers except Bitbucket Data Center. ### HCP Terraform returns 500 after authenticating with the VCS provider The Callback URL in the OAuth application configuration in the VCS provider probably wasn't updated in the last step of the instructions and still points to the default "/" path (or an example.com link) instead of the full callback url. The fix is to update the callback URL in your VCS provider's application settings. You can look up the real callback URL in HCP Terraform's settings. ### Can't delete a workspace or module, resulting in 500 errors This often happens when the VCS connection has been somehow broken: it might have had permissions revoked, been reconfigured, or had the repository removed. Check for these possibilities and contact HashiCorp support for further assistance, including any information you collected in your support ticket. ### `redirect_uri_mismatch` error on "Connect" The domain name for HCP Terraform's SaaS release changed on 02/22 at 9AM from `atlas.hashicorp.com` to `app.terraform.io`. If the OAuth client was originally configured on the old domain, using it for a new VCS connection can result in this error. The fix is to update the OAuth Callback URL in your VCS provider to use app.terraform.io instead of atlas.hashicorp.com. ### Can't trigger workspace runs from VCS webhook A workspace with no runs will not accept new runs from a VCS webhook. You must queue at least one run manually. A workspace will not process a webhook if the workspace previously processed a webhook with the same commit SHA and created a run. To trigger a run, create a new commit. If a workspace receives a webhook with a previously processed commit, HCP Terraform adds a new event to the [VCS Events](/terraform/cloud-docs/vcs#viewing-events) page documenting the received webhook. ### Changing the URL for a VCS provider On rare occasions, you might need HCP Terraform to change the URL it uses to reach your VCS provider. This usually only happens if you move your VCS server or the VCS vendor changes their supported API versions. HCP Terraform does not allow you to change the API URL for an existing VCS connection, but you can create a new VCS connection and update existing resources to use it. This is most efficient if you script the necessary updates using HCP Terraform's API. In brief: 1. [Configure a new VCS connection](/terraform/cloud-docs/vcs) with the updated URL. 1. Obtain the [oauth-token IDs](/terraform/cloud-docs/api-docs/oauth-tokens) for the old and new OAuth clients. 1. [List all workspaces](/terraform/cloud-docs/api-docs/workspaces#list-workspaces) (dealing with pagination if necessary), and use a JSON filtering tool like `jq` to make a list of all workspace IDs whose `attributes.vcs-repo.oauth-token-id` matches the old VCS connection. 1. Iterate over the list of workspaces and [PATCH each one](/terraform/cloud-docs/api-docs/workspaces#update-a-workspace) to use the new `oauth-token-id`. 1. [List all registry modules](/terraform/registry/api-docs#list-modules) and use their `source` property to determine which ones came from the old VCS connection. 1. [Delete each affected module](/terraform/cloud-docs/api-docs/private-registry/modules#delete-a-module), then [create a new module](/terraform/cloud-docs/api-docs/private-registry/modules#publish-a-private-module-from-a-vcs) from the new connection's version of the relevant repo. 1. Delete the old VCS connection. ### Reauthorizing VCS OAuth Providers If a VCS OAuth connection breaks, you can reauthorize an existing VCS provider while retaining any VCS connected resources, like workspaces. We recommend only using this feature to fix broken VCS connections. We also recommend reauthorizing using the same VCS account to avoid permission changes to your repositories. ~> **Important:** Reauthorizing is not available when the [TFE Provider](https://registry.terraform.io/providers/hashicorp/tfe/latest/docs/resources/oauth_client) is managing the OAuth Client. Instead, you can update the [oauth_token](https://registry.terraform.io/providers/hashicorp/tfe/latest/docs/resources/oauth_client#oauth_token) argument with a new token from your VCS Provider. To reauthorize a VCS connection, complete the following steps: 1. Go to your organization's settings and click **Providers** under **Version Control**. 1. Click **Reauthorize** in the **OAuth Token ID** column. 1. Confirm the reauthorization. HCP Terraform redirects you to your VCS Provider where you can reauthorize the connection. ## Certificate Errors on Terraform Enterprise When debugging failures of VCS connections due to certificate errors, running additional diagnostics using the OpenSSL command may provide more information about the failure. First, attach a bash session to the application container: ``` docker exec -it ptfe_atlas sh -c "stty rows 50 && stty cols 150 && bash" ``` Then run the `openssl s_client` command, using the certificate at `/tmp/cust-ca-certificates.crt` in the container: ``` openssl s_client -showcerts -CAfile /tmp/cust-ca-certificates.crt -connect git-server-hostname:443 ``` For example, a Gitlab server that uses a self-signed certificate might result in an error like `verify error:num=18:self signed certificate`, as shown in the output below: ``` bash-4.3# openssl s_client -showcerts -CAfile /tmp/cust-ca-certificates.crt -connect gitlab.local:443 CONNECTED(00000003) depth=0 CN = gitlab.local verify error:num=18:self signed certificate verify return:1 depth=0 CN = gitlab.local verify return:1 --- Certificate chain 0 s:/CN=gitlab.local i:/CN=gitlab.local -----BEGIN CERTIFICATE----- MIIC/DCCAeSgAwIBAgIJAIhG2GWtcj7lMA0GCSqGSIb3DQEBCwUAMCAxHjAcBgNV BAMMFWdpdGxhYi1sb2NhbC5oYXNoaS5jbzAeFw0xODA2MDQyMjAwMDhaFw0xOTA2 MDQyMjAwMDhaMCAxHjAcBgNVBAMMFWdpdGxhYi1sb2NhbC5oYXNoaS5jbzCCASIw DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMMgrpo3zsoy2BP/AoGIgrYwEMnj PwSOFGNHbclmiVBCW9jvrZrtva8Qh+twU7CSQdkeSP34ZgLrRp1msmLvUuVMgPts i7isrI5hug/IHLLOGO5xMvxOcrHknvySYJRmvYFriEBPNRPYJGJ9O1ZUVUYeNwW/ l9eegBDpJrdsjGmFKCOzZEdUA3zu7PfNgf788uIi4UkVXZNa/OFHsZi63OYyfOc2 Zm0/vRKOn17dewOOesHhw77yYbBH8OFsEiC10JCe5y3MD9yrhV1h9Z4niK8rHPXz XEh3JfV+BBArodmDbvi4UtT+IGdDueUllXv7kbwqvQ67OFmmek0GZOY7ZvMCAwEA AaM5MDcwIAYDVR0RBBkwF4IVZ2l0bGFiLWxvY2FsLmhhc2hpLmNvMBMGA1UdJQQM MAoGCCsGAQUFBwMBMA0GCSqGSIb3DQEBCwUAA4IBAQCfkukNV/9vCA/8qoEbPt1M mvf2FHyUD69p/Gq/04IhGty3sno4eVcwWEc5EvfNt8vv1FykFQ6zMJuWA0jL9x2s LbC8yuRDnsAlukSBvyazCZ9pt3qseGOLskaVCeOqG3b+hJqikZihFUD95IvWNFQs RpvGvnA/AH2Lqqeyk2ITtLYj1AcSB1hBSnG/0fdtao9zs0JQsrS59CD1lbbTPPRN orbKtVTWF2JlJxl2watfCNTw6nTCPI+51CYd687T3MuRN7LsTgglzP4xazuNjbWB QGAiQRd6aKj+xAJnqjzXt9wl6a493m8aNkyWrxZGHfIA1W70RtMqIC/554flZ4ia -----END CERTIFICATE----- --- Server certificate subject=/CN=gitlab.local issuer=/CN=gitlab.local --- No client certificate CA names sent Peer signing digest: SHA512 Server Temp Key: ECDH, P-256, 256 bits --- SSL handshake has read 1443 bytes and written 433 bytes --- New, TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256-GCM-SHA384 Server public key is 2048 bit Secure Renegotiation IS supported Compression: NONE Expansion: NONE No ALPN negotiated SSL-Session: Protocol : TLSv1.2 Cipher : ECDHE-RSA-AES256-GCM-SHA384 Session-ID: AF5286FB7C7725D377B4A5F556DEB6DDC38B302153DDAE90C552ACB5DC4D86B8 Session-ID-ctx: Master-Key: DB75AEC12C6E7B62246C653C8CB8FC3B90DE86886D68CB09898A6A6F5D539007F7760BC25EC4563A893D34ABCFAAC28A Key-Arg : None PSK identity: None PSK identity hint: None SRP username: None TLS session ticket lifetime hint: 300 (seconds) TLS session ticket: 0000 - 03 c1 35 c4 ff 6d 24 a8-6c 70 61 fb 2c dc 2e b8 ..5..m$.lpa.,... 0010 - de 4c 6d b0 2c 13 8e b6-63 95 18 ee 4d 33 a6 dc .Lm.,...c...M3.. 0020 - 0d 64 24 f0 8d 3f 9c aa-b8 a4 e2 4f d3 c3 4d 88 .d$..?.....O..M. 0030 - 58 99 10 73 83 93 70 4a-2c 61 e7 2d 41 74 d3 e9 X..s..pJ,a.-At.. 0040 - 83 8c 4a 7f ae 7b e8 56-5c 51 fc 6f fe e3 a0 ec ..J..{.V\Q.o.... 0050 - 3c 2b 6b 13 fc a0 e5 15-a8 31 16 19 11 98 56 43 <+k......1....VC 0060 - 16 86 c4 cd 53 e6 c3 61-e2 6c 1b 99 86 f5 a8 bd ....S..a.l...... 0070 - 3c 49 c0 0a ce 81 a9 33-9b 95 2c e1 f4 6d 05 1e <I.....3..,..m.. 0080 - 18 fa bf 2e f2 27 cc 0b-df 08 13 7e 4d 5a c8 41 .....'.....~MZ.A 0090 - 93 26 23 90 f1 bb ba 3a-15 17 1b 09 6a 14 a8 47 .&#....:....j..G 00a0 - 61 eb d9 91 0a 5c 4d e0-4a 8f 4d 50 ab 4b 81 aa a....\M.J.MP.K.. Start Time: 1528152434 Timeout : 300 (sec) Verify return code: 18 (self signed certificate) --- closed ```
terraform
page title Troubleshooting VCS Providers HCP Terraform description Learn how to address common problems in VCS integrations Troubleshooting VCS Integration in HCP Terraform This page collects solutions to the most common problems our users encounter with VCS integration in HCP Terraform Azure DevOps Required status checks not sending When configuring status checks with Azure DevOps https learn microsoft com en us azure devops repos git pr status policy the web interface may auto populate Genre and Name fields beneath Status to check with incorrect values that do not reflect what HCP Terraform is sending To function correctly as required checks the Genre must be populated with Terraform Cloud or the first segment for a Terraform Enterprise install and the remainder of the status check goes in the Name field This requires using the Enter genre name separately checkbox to not use the default configuration In the example below the status check is named Terraform Cloud paul hcp gianni test 1 and needs to be configured with Genre Terraform Cloud and Name paul hcp gianni test 1 Azure DevOps screenshot configuring required status checks correctly img docs ado required status check png With an older version of Azure DevOps Server it may be that the web interface does not allow entering the Genre and Name separately In which case the status check will need to be created via the API https learn microsoft com en us rest api azure devops policy configurations create Bitbucket Data Center The following errors are specific to Bitbucket Data Center integrations Clicking Connect organization X with Bitbucket Data Center raises an error message in HCP Terraform HCP Terraform uses OAuth 1 to authenticate the user to Bitbucket Data Center The first step in the authentication process is for HCP Terraform to call Bitbucket Data Center to obtain a request token After the call completes HCP Terraform redirects you to Bitbucket Data Center with the request token An error occurs when HCP Terraform calls to Bitbucket Data Center to obtain the request token but the request is rejected Some common reasons for the request to be rejected are The API endpoint is unreachable this can happen if the address or port is incorrect or the domain name doesn t resolve The certificate used on Bitbucket Data Center is rejected by the HCP Terraform HTTP client because the SSL verification fails This is often the case with self signed certificates or when the Terraform Enterprise instance is not configured to trust the signing chain of the Bitbucket Data Center SSL certificate To fix this issue do the following Verify that the instance running Terraform Enterprise can resolve the domain name and can reach Bitbucket Data Center Verify that the HCP Terraform client accepts the HTTPS connection to Bitbucket Data Center This can be done by performing a curl from the Terraform Enterprise instance to Bitbucket Data Center it should not return any SSL errors Verify that the Consumer Key Consumer Name and the Public Key are configured properly in Bitbucket Data Center Verify that the HTTP URL and API URL in HCP Terraform are correct for your Bitbucket Data Center instance This includes the proper scheme HTTP vs HTTPS as well as the port Creating a workspace from a repository hangs indefinitely displaying a spinner on the confirm button If you were able to connect HCP Terraform to Bitbucket Data Center but cannot create workspaces it often means HCP Terraform isn t able to automatically add webhook URLs for that repository To fix this issue Make sure you haven t manually entered any webhook URLs for the affected repository or project Although the Bitbucket Web Post Hooks Plugin documentation describes how to manually enter a hook URL HCP Terraform handles this automatically Manually entered URLs can interfere with HCP Terraform s operation To check the hook URLs for a repository go to the repository s settings then go to the Hooks page in the Workflow section and click on the Post Receive WebHooks link Also note that some Bitbucket Data Center versions might allow you to set per project or server wide hook URLs in addition to per repository hooks These should all be empty if you set a hook URL that might affect more than one repo when installing the plugin go back and delete it Make sure you aren t trying to connect too many workspaces to a single repository Bitbucket Data Center s webhooks plugin can only attach five hooks to a given repo You might need to create additional repositories if you need to make more than five workspaces from a single configuration repo Bitbucket Cloud HCP Terraform fails to obtain repositories This typically happens when the HCP Terraform application in Bitbucket Cloud wasn t configured to have the full set of permissions Go to the OAuth section of the Bitbucket settings find your HCP Terraform OAuth consumer click the edit link in the menu and ensure it has the required permissions enabled Permission type Permission level Account Write Repositories Admin Pull requests Write Webhooks Read and write GitHub Host key verification failed error in terraform init when attempting to ingress Terraform modules via Git over SSH This is most common when running Terraform 0 10 3 or 0 10 4 which had a bug in handling SSH submodule ingress Try upgrading affected HCP Terraform workspaces to the latest Terraform version or 0 10 8 the latest in the 0 10 series HCP Terraform can t ingress Git submodules with auth errors during init This usually happens when an SSH key isn t associated with the VCS provider s OAuth client Go to your organization s VCS Provider settings page and check your GitHub client If it still says You can add a private SSH key to this connection to be used for git clone operations instead of A private SSH key has been added you need to click the add a private SSH key link and add a key Check the settings page for affected workspaces and ensure that Include submodules on clone is enabled Note that the SSH Key section in a workspace s settings is only used for mid run operations like cloning Terraform modules It isn t used when cloning the linked repository before a run General The following errors may occur for all VCS providers except Bitbucket Data Center HCP Terraform returns 500 after authenticating with the VCS provider The Callback URL in the OAuth application configuration in the VCS provider probably wasn t updated in the last step of the instructions and still points to the default path or an example com link instead of the full callback url The fix is to update the callback URL in your VCS provider s application settings You can look up the real callback URL in HCP Terraform s settings Can t delete a workspace or module resulting in 500 errors This often happens when the VCS connection has been somehow broken it might have had permissions revoked been reconfigured or had the repository removed Check for these possibilities and contact HashiCorp support for further assistance including any information you collected in your support ticket redirect uri mismatch error on Connect The domain name for HCP Terraform s SaaS release changed on 02 22 at 9AM from atlas hashicorp com to app terraform io If the OAuth client was originally configured on the old domain using it for a new VCS connection can result in this error The fix is to update the OAuth Callback URL in your VCS provider to use app terraform io instead of atlas hashicorp com Can t trigger workspace runs from VCS webhook A workspace with no runs will not accept new runs from a VCS webhook You must queue at least one run manually A workspace will not process a webhook if the workspace previously processed a webhook with the same commit SHA and created a run To trigger a run create a new commit If a workspace receives a webhook with a previously processed commit HCP Terraform adds a new event to the VCS Events terraform cloud docs vcs viewing events page documenting the received webhook Changing the URL for a VCS provider On rare occasions you might need HCP Terraform to change the URL it uses to reach your VCS provider This usually only happens if you move your VCS server or the VCS vendor changes their supported API versions HCP Terraform does not allow you to change the API URL for an existing VCS connection but you can create a new VCS connection and update existing resources to use it This is most efficient if you script the necessary updates using HCP Terraform s API In brief 1 Configure a new VCS connection terraform cloud docs vcs with the updated URL 1 Obtain the oauth token IDs terraform cloud docs api docs oauth tokens for the old and new OAuth clients 1 List all workspaces terraform cloud docs api docs workspaces list workspaces dealing with pagination if necessary and use a JSON filtering tool like jq to make a list of all workspace IDs whose attributes vcs repo oauth token id matches the old VCS connection 1 Iterate over the list of workspaces and PATCH each one terraform cloud docs api docs workspaces update a workspace to use the new oauth token id 1 List all registry modules terraform registry api docs list modules and use their source property to determine which ones came from the old VCS connection 1 Delete each affected module terraform cloud docs api docs private registry modules delete a module then create a new module terraform cloud docs api docs private registry modules publish a private module from a vcs from the new connection s version of the relevant repo 1 Delete the old VCS connection Reauthorizing VCS OAuth Providers If a VCS OAuth connection breaks you can reauthorize an existing VCS provider while retaining any VCS connected resources like workspaces We recommend only using this feature to fix broken VCS connections We also recommend reauthorizing using the same VCS account to avoid permission changes to your repositories Important Reauthorizing is not available when the TFE Provider https registry terraform io providers hashicorp tfe latest docs resources oauth client is managing the OAuth Client Instead you can update the oauth token https registry terraform io providers hashicorp tfe latest docs resources oauth client oauth token argument with a new token from your VCS Provider To reauthorize a VCS connection complete the following steps 1 Go to your organization s settings and click Providers under Version Control 1 Click Reauthorize in the OAuth Token ID column 1 Confirm the reauthorization HCP Terraform redirects you to your VCS Provider where you can reauthorize the connection Certificate Errors on Terraform Enterprise When debugging failures of VCS connections due to certificate errors running additional diagnostics using the OpenSSL command may provide more information about the failure First attach a bash session to the application container docker exec it ptfe atlas sh c stty rows 50 stty cols 150 bash Then run the openssl s client command using the certificate at tmp cust ca certificates crt in the container openssl s client showcerts CAfile tmp cust ca certificates crt connect git server hostname 443 For example a Gitlab server that uses a self signed certificate might result in an error like verify error num 18 self signed certificate as shown in the output below bash 4 3 openssl s client showcerts CAfile tmp cust ca certificates crt connect gitlab local 443 CONNECTED 00000003 depth 0 CN gitlab local verify error num 18 self signed certificate verify return 1 depth 0 CN gitlab local verify return 1 Certificate chain 0 s CN gitlab local i CN gitlab local BEGIN CERTIFICATE MIIC DCCAeSgAwIBAgIJAIhG2GWtcj7lMA0GCSqGSIb3DQEBCwUAMCAxHjAcBgNV BAMMFWdpdGxhYi1sb2NhbC5oYXNoaS5jbzAeFw0xODA2MDQyMjAwMDhaFw0xOTA2 MDQyMjAwMDhaMCAxHjAcBgNVBAMMFWdpdGxhYi1sb2NhbC5oYXNoaS5jbzCCASIw DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMMgrpo3zsoy2BP AoGIgrYwEMnj PwSOFGNHbclmiVBCW9jvrZrtva8Qh twU7CSQdkeSP34ZgLrRp1msmLvUuVMgPts i7isrI5hug IHLLOGO5xMvxOcrHknvySYJRmvYFriEBPNRPYJGJ9O1ZUVUYeNwW l9eegBDpJrdsjGmFKCOzZEdUA3zu7PfNgf788uIi4UkVXZNa OFHsZi63OYyfOc2 Zm0 vRKOn17dewOOesHhw77yYbBH8OFsEiC10JCe5y3MD9yrhV1h9Z4niK8rHPXz XEh3JfV BBArodmDbvi4UtT IGdDueUllXv7kbwqvQ67OFmmek0GZOY7ZvMCAwEA AaM5MDcwIAYDVR0RBBkwF4IVZ2l0bGFiLWxvY2FsLmhhc2hpLmNvMBMGA1UdJQQM MAoGCCsGAQUFBwMBMA0GCSqGSIb3DQEBCwUAA4IBAQCfkukNV 9vCA 8qoEbPt1M mvf2FHyUD69p Gq 04IhGty3sno4eVcwWEc5EvfNt8vv1FykFQ6zMJuWA0jL9x2s LbC8yuRDnsAlukSBvyazCZ9pt3qseGOLskaVCeOqG3b hJqikZihFUD95IvWNFQs RpvGvnA AH2Lqqeyk2ITtLYj1AcSB1hBSnG 0fdtao9zs0JQsrS59CD1lbbTPPRN orbKtVTWF2JlJxl2watfCNTw6nTCPI 51CYd687T3MuRN7LsTgglzP4xazuNjbWB QGAiQRd6aKj xAJnqjzXt9wl6a493m8aNkyWrxZGHfIA1W70RtMqIC 554flZ4ia END CERTIFICATE Server certificate subject CN gitlab local issuer CN gitlab local No client certificate CA names sent Peer signing digest SHA512 Server Temp Key ECDH P 256 256 bits SSL handshake has read 1443 bytes and written 433 bytes New TLSv1 SSLv3 Cipher is ECDHE RSA AES256 GCM SHA384 Server public key is 2048 bit Secure Renegotiation IS supported Compression NONE Expansion NONE No ALPN negotiated SSL Session Protocol TLSv1 2 Cipher ECDHE RSA AES256 GCM SHA384 Session ID AF5286FB7C7725D377B4A5F556DEB6DDC38B302153DDAE90C552ACB5DC4D86B8 Session ID ctx Master Key DB75AEC12C6E7B62246C653C8CB8FC3B90DE86886D68CB09898A6A6F5D539007F7760BC25EC4563A893D34ABCFAAC28A Key Arg None PSK identity None PSK identity hint None SRP username None TLS session ticket lifetime hint 300 seconds TLS session ticket 0000 03 c1 35 c4 ff 6d 24 a8 6c 70 61 fb 2c dc 2e b8 5 m lpa 0010 de 4c 6d b0 2c 13 8e b6 63 95 18 ee 4d 33 a6 dc Lm c M3 0020 0d 64 24 f0 8d 3f 9c aa b8 a4 e2 4f d3 c3 4d 88 d O M 0030 58 99 10 73 83 93 70 4a 2c 61 e7 2d 41 74 d3 e9 X s pJ a At 0040 83 8c 4a 7f ae 7b e8 56 5c 51 fc 6f fe e3 a0 ec J V Q o 0050 3c 2b 6b 13 fc a0 e5 15 a8 31 16 19 11 98 56 43 k 1 VC 0060 16 86 c4 cd 53 e6 c3 61 e2 6c 1b 99 86 f5 a8 bd S a l 0070 3c 49 c0 0a ce 81 a9 33 9b 95 2c e1 f4 6d 05 1e I 3 m 0080 18 fa bf 2e f2 27 cc 0b df 08 13 7e 4d 5a c8 41 MZ A 0090 93 26 23 90 f1 bb ba 3a 15 17 1b 09 6a 14 a8 47 j G 00a0 61 eb d9 91 0a 5c 4d e0 4a 8f 4d 50 ab 4b 81 aa a M J MP K Start Time 1528152434 Timeout 300 sec Verify return code 18 self signed certificate closed
terraform Learn to prepare private modules for publishing add them to the registry and page title Publishing Private Modules Private Registry HCP Terraform Publishing Private Modules to the HCP Terraform Private Registry vcs terraform cloud docs vcs release new versions
--- page_title: Publishing Private Modules - Private Registry - HCP Terraform description: >- Learn to prepare private modules for publishing, add them to the registry, and release new versions. --- [vcs]: /terraform/cloud-docs/vcs # Publishing Private Modules to the HCP Terraform Private Registry > **Hands-on:** Try the [Share Modules in the Private Module Registry](/terraform/tutorials/modules/module-private-registry-share) tutorial. In addition to [adding modules from the Terraform Registry](/terraform/cloud-docs/registry/add), you can publish private modules to an organization's HCP Terraform private registry. The registry handles downloads and controls access with HCP Terraform API tokens, so consumers do not need access to the module's source repository, even when running Terraform from the command line. The private registry uses your configured [Version Control System (VCS) integrations][vcs] and defers to your VCS provider for most management tasks. For example, your VCS provider handles new version releases. The only manual tasks are adding a new module and deleting module versions. [permissions-citation]: #intentionally-unused---keep-for-maintainers ## Permissions Private modules are only available to members of the organization where you add them. In Terraform Enterprise, they are also available to organizations that you configure to [share modules](/terraform/enterprise/admin/application/registry-sharing) with that organization. Members of the [owners team](/terraform/cloud-docs/users-teams-organizations/permissions#organization-owners) and teams with [Manage Private Registry permissions](/terraform/cloud-docs/users-teams-organizations/permissions#manage-private-registry) can publish and delete modules from the private registry. ## Preparing a Module Repository After you configure at least one [connection to a VCS provider][vcs], you can publish a new module by specifying a properly formatted VCS repository (details below). The registry automatically detects the rest of the information it needs, including the module's name and its available versions. A module repository must meet all of the following requirements before you can add it to the registry: - **Location and permissions:** The repository must be in one of your configured [VCS providers][vcs], and HCP Terraform's VCS user account must have admin access to the repository. The registry needs admin access to create the webhooks to import new module versions. GitLab repositories must be in the main organization or group, and not in any subgroups. - **Named `terraform-<PROVIDER>-<NAME>`:** Module repositories must use this three-part name format, where `<NAME>` reflects the type of infrastructure the module manages and `<PROVIDER>` is the main provider where it creates that infrastructure. The `<PROVIDER>` segment must be all lowercase. The `<NAME>` segment can contain additional hyphens. Examples: `terraform-google-vault` or `terraform-aws-ec2-instance`. - **Standard module structure:** The module must adhere to the [standard module structure](/terraform/language/modules/develop/structure). This allows the registry to inspect your module and generate documentation, track resource usage, and more. ## Publishing a New Module You can publish modules through the UI as shown below or with the [Registry Modules API](/terraform/cloud-docs/api-docs/private-registry/modules). The API also supports publishing modules without a VCS repo as the source, which is not possible in the UI. To publish a new module: 1. Click **Registry**. The **Registry** page appears. 1. Click **Publish** and select **Module**. The **Add Module** page appears with a list of available repositories. 1. Select the repository containing the module you want to publish. You can search the list by typing part or all of a repository name into the filter field. Remember that VCS providers use `<NAMESPACE>/<REPO NAME>` strings to locate repositories. The namespace is an organization name for most providers, but Bitbucket Data Center, not Bitbucket Cloud, uses project keys, like `INFRA`. 1. When prompted, choose either the **Tag** or **Branch** module publishing type. 1. (Optional) If this module is a [no-code ready module](/terraform/cloud-docs/no-code-provisioning/module-design), select the **Add Module to no-code provision allowlist** checkbox. 1. Click **Publish module**. HCP Terraform displays a loading page while it imports the module versions and then takes you to the new module's details page. On the details page, you can view available versions, read documentation, and copy a usage example. <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/nocode.mdx' <!-- END: TFC:only name:pnp-callout --> ### Tag-based publishing considerations When using the **Tag** module publishing type, the registry uses `x.y.z` formatted release tags to identify module versions. Your repository must contain at least one release tag for you to publish a module. Release tag names must be a [semantic version](http://semver.org), which you can optionally prefix with a `v`. For example, `v1.0.4` and `0.9.2`. The registry ignores tags that do not match these formats. <!-- BEGIN: TFC:only name:branch-based-publishing --> ### Branch-based publishing considerations When using the **Branch** module publishing type, you must provide the name of an existing branch in your VCS repository and give the module a **Module version**. Your VCS repository does not need to contain a matching tag or release. You can only enable testing on modules published using branch-based publishing. Refer to the [test-integrated modules](/terraform/cloud-docs/registry/test) documentation for more information. <!-- END: TFC:only name:branch-based-publishing --> ## Releasing New Versions of a Module <!-- BEGIN: TFC:only name:branch-based-publishing --> The process to release a new module version differs between the tag-based and branch-based publishing workflows. ### Tag-Based Publishing Workflow <!-- END: TFC:only name:branch-based-publishing --> To release a new version of a module in the tag-based publishing workflow, push a new release tag to its VCS repository. The registry automatically imports the new version. Refer to [Preparing a Module Repository](#preparing-a-module-repository) for details about release tag requirements. <!-- BEGIN: TFC:only name:branch-based-publishing --> ### Branch-Based Publishing Workflow To release a new version of a module using the branch-based publishing workflow, navigate to the module overview screen, then click the **Publish New Version** button. Select the commit SHA that the new version will point to, and assign a new module version. You cannot re-use an existing module version. ## Update Publish Settings After publishing your module, you can change between tag-based and branch-based publishing. To update your module's publish settings, navigate to the the module overview page, click the **Manage Module for Organization** dropdown, and then click **Publish Settings**. - To change from tag-based to branch-based publishing, you must configure a **Module branch** and [create a new module version](#branch-based-publishing-workflow), as HCP Terraform will not automatically create one. - To change from branch-based publishing to tag-based publishing, you must create at least one tag in your VCS repository. <!-- END: TFC:only name:branch-based-publishing --> ## Deleting Versions and Modules -> **Note:** Deleting a tag from your VCS repository does not automatically remove the version from the private registry. You can delete individual versions of a module or the entire module. If deleting a module version would leave a module with no versions, HCP Terraform removes the entire module. To delete a module or version: 1. Navigate to the module's details page. 1. If you want to delete a single version, use the **Versions** menu to select it. 1. Click **Delete module**. 1. Select an action from the menu: - **Delete only this module version:** Deletes only the version of the module you were viewing when you clicked **Delete module**. - **Delete all versions for this provider for this module:** Deletes the entire module for a single provider. This action is important if you have modules with the same name but with different providers. For example, if you have module repos named `terraform-aws-appserver` and `terraform-azure-appserver`, the registry treats them as alternate providers of the same `appserver` module. - **Delete all providers and versions for this module:** Deletes all modules with this name, even if they are from different providers. For example, this action deletes both `terraform-aws-appserver` and `terraform-azure-appserver`. 1. Type the module name and click **Delete**. ### Restoring a Deleted Module or Version Deletion is permanent, but there are ways to restore deleted modules and module versions. - To restore a deleted module, re-add it as a new module. - To restore a deleted version, either delete the corresponding tag from your VCS and push a new tag with the same name, or delete the entire module from the registry and re-add it. ## Sharing Modules Across Organizations HCP Terraform does not typically allow one organization's workspaces to use private modules from a different organization. This restriction is because HCP Terraform gives Terraform temporary credentials to access modules that are only valid for that workspace's organization. Although it is possible to mix modules from multiple organizations when you run Terraform on the command line, we strongly recommend against it. Instead, you can share modules across organizations by sharing the underlying VCS repository. Grant each organization access to the module's repository, and then add the module to each organization's registry. When you push tags to publish new module versions, both organizations update accordingly. Terraform Enterprise administrators can configure [module sharing](/terraform/enterprise/admin/application/registry-sharing) to allow organizations to use private modules from other organizations. ## Generating Module Tests (Beta) You can generate and run generated tests for your module with [the `terraform test` command](/terraform/cli/commands/test). Before you can generate tests for a module, it must have at least one version published. Tests can only be generated once per module and are intended to be reviewed by the module's authors before being checked into version control and maintained with the rest of the module's content. If the module's configuration files exceed 128KB in total size, HCP Terraform will not be able to generate tests for that module. You must have [permission to manage registry modules](/terraform/cloud-docs/users-teams-organizations/permissions#manage-private-registry) and [permission to manage module test generation](/terraform/cloud-docs/users-teams-organizations/permissions#manage-module-test-generation-beta) to generate tests.
terraform
page title Publishing Private Modules Private Registry HCP Terraform description Learn to prepare private modules for publishing add them to the registry and release new versions vcs terraform cloud docs vcs Publishing Private Modules to the HCP Terraform Private Registry Hands on Try the Share Modules in the Private Module Registry terraform tutorials modules module private registry share tutorial In addition to adding modules from the Terraform Registry terraform cloud docs registry add you can publish private modules to an organization s HCP Terraform private registry The registry handles downloads and controls access with HCP Terraform API tokens so consumers do not need access to the module s source repository even when running Terraform from the command line The private registry uses your configured Version Control System VCS integrations vcs and defers to your VCS provider for most management tasks For example your VCS provider handles new version releases The only manual tasks are adding a new module and deleting module versions permissions citation intentionally unused keep for maintainers Permissions Private modules are only available to members of the organization where you add them In Terraform Enterprise they are also available to organizations that you configure to share modules terraform enterprise admin application registry sharing with that organization Members of the owners team terraform cloud docs users teams organizations permissions organization owners and teams with Manage Private Registry permissions terraform cloud docs users teams organizations permissions manage private registry can publish and delete modules from the private registry Preparing a Module Repository After you configure at least one connection to a VCS provider vcs you can publish a new module by specifying a properly formatted VCS repository details below The registry automatically detects the rest of the information it needs including the module s name and its available versions A module repository must meet all of the following requirements before you can add it to the registry Location and permissions The repository must be in one of your configured VCS providers vcs and HCP Terraform s VCS user account must have admin access to the repository The registry needs admin access to create the webhooks to import new module versions GitLab repositories must be in the main organization or group and not in any subgroups Named terraform PROVIDER NAME Module repositories must use this three part name format where NAME reflects the type of infrastructure the module manages and PROVIDER is the main provider where it creates that infrastructure The PROVIDER segment must be all lowercase The NAME segment can contain additional hyphens Examples terraform google vault or terraform aws ec2 instance Standard module structure The module must adhere to the standard module structure terraform language modules develop structure This allows the registry to inspect your module and generate documentation track resource usage and more Publishing a New Module You can publish modules through the UI as shown below or with the Registry Modules API terraform cloud docs api docs private registry modules The API also supports publishing modules without a VCS repo as the source which is not possible in the UI To publish a new module 1 Click Registry The Registry page appears 1 Click Publish and select Module The Add Module page appears with a list of available repositories 1 Select the repository containing the module you want to publish You can search the list by typing part or all of a repository name into the filter field Remember that VCS providers use NAMESPACE REPO NAME strings to locate repositories The namespace is an organization name for most providers but Bitbucket Data Center not Bitbucket Cloud uses project keys like INFRA 1 When prompted choose either the Tag or Branch module publishing type 1 Optional If this module is a no code ready module terraform cloud docs no code provisioning module design select the Add Module to no code provision allowlist checkbox 1 Click Publish module HCP Terraform displays a loading page while it imports the module versions and then takes you to the new module s details page On the details page you can view available versions read documentation and copy a usage example BEGIN TFC only name pnp callout include tfc package callouts nocode mdx END TFC only name pnp callout Tag based publishing considerations When using the Tag module publishing type the registry uses x y z formatted release tags to identify module versions Your repository must contain at least one release tag for you to publish a module Release tag names must be a semantic version http semver org which you can optionally prefix with a v For example v1 0 4 and 0 9 2 The registry ignores tags that do not match these formats BEGIN TFC only name branch based publishing Branch based publishing considerations When using the Branch module publishing type you must provide the name of an existing branch in your VCS repository and give the module a Module version Your VCS repository does not need to contain a matching tag or release You can only enable testing on modules published using branch based publishing Refer to the test integrated modules terraform cloud docs registry test documentation for more information END TFC only name branch based publishing Releasing New Versions of a Module BEGIN TFC only name branch based publishing The process to release a new module version differs between the tag based and branch based publishing workflows Tag Based Publishing Workflow END TFC only name branch based publishing To release a new version of a module in the tag based publishing workflow push a new release tag to its VCS repository The registry automatically imports the new version Refer to Preparing a Module Repository preparing a module repository for details about release tag requirements BEGIN TFC only name branch based publishing Branch Based Publishing Workflow To release a new version of a module using the branch based publishing workflow navigate to the module overview screen then click the Publish New Version button Select the commit SHA that the new version will point to and assign a new module version You cannot re use an existing module version Update Publish Settings After publishing your module you can change between tag based and branch based publishing To update your module s publish settings navigate to the the module overview page click the Manage Module for Organization dropdown and then click Publish Settings To change from tag based to branch based publishing you must configure a Module branch and create a new module version branch based publishing workflow as HCP Terraform will not automatically create one To change from branch based publishing to tag based publishing you must create at least one tag in your VCS repository END TFC only name branch based publishing Deleting Versions and Modules Note Deleting a tag from your VCS repository does not automatically remove the version from the private registry You can delete individual versions of a module or the entire module If deleting a module version would leave a module with no versions HCP Terraform removes the entire module To delete a module or version 1 Navigate to the module s details page 1 If you want to delete a single version use the Versions menu to select it 1 Click Delete module 1 Select an action from the menu Delete only this module version Deletes only the version of the module you were viewing when you clicked Delete module Delete all versions for this provider for this module Deletes the entire module for a single provider This action is important if you have modules with the same name but with different providers For example if you have module repos named terraform aws appserver and terraform azure appserver the registry treats them as alternate providers of the same appserver module Delete all providers and versions for this module Deletes all modules with this name even if they are from different providers For example this action deletes both terraform aws appserver and terraform azure appserver 1 Type the module name and click Delete Restoring a Deleted Module or Version Deletion is permanent but there are ways to restore deleted modules and module versions To restore a deleted module re add it as a new module To restore a deleted version either delete the corresponding tag from your VCS and push a new tag with the same name or delete the entire module from the registry and re add it Sharing Modules Across Organizations HCP Terraform does not typically allow one organization s workspaces to use private modules from a different organization This restriction is because HCP Terraform gives Terraform temporary credentials to access modules that are only valid for that workspace s organization Although it is possible to mix modules from multiple organizations when you run Terraform on the command line we strongly recommend against it Instead you can share modules across organizations by sharing the underlying VCS repository Grant each organization access to the module s repository and then add the module to each organization s registry When you push tags to publish new module versions both organizations update accordingly Terraform Enterprise administrators can configure module sharing terraform enterprise admin application registry sharing to allow organizations to use private modules from other organizations Generating Module Tests Beta You can generate and run generated tests for your module with the terraform test command terraform cli commands test Before you can generate tests for a module it must have at least one version published Tests can only be generated once per module and are intended to be reviewed by the module s authors before being checked into version control and maintained with the rest of the module s content If the module s configuration files exceed 128KB in total size HCP Terraform will not be able to generate tests for that module You must have permission to manage registry modules terraform cloud docs users teams organizations permissions manage private registry and permission to manage module test generation terraform cloud docs users teams organizations permissions manage module test generation beta to generate tests
terraform page title Publishing Private Providers Private Registry In addition to curating public providers from the Terraform Registry terraform cloud docs registry add you can publish private providers to an organization s HCP Terraform private registry Once you have published a private provider through the API members of your organization can search for it in the private registry UI and use it in configurations and release new versions Publishing private providers to the HCP Terraform private registry Prepare private providers for publishing add them to the private registry
--- page_title: Publishing Private Providers - Private Registry description: >- Prepare private providers for publishing, add them to the private registry, and release new versions. --- # Publishing private providers to the HCP Terraform private registry In addition to [curating public providers from the Terraform Registry](/terraform/cloud-docs/registry/add), you can publish private providers to an organization's HCP Terraform private registry. Once you have published a private provider through the API, members of your organization can search for it in the private registry UI and use it in configurations. ## Requirements Review the following before publishing a new provider or provider version. ### Permissions Users must be members of an organization to access its registry and private providers. In Terraform Enterprise, providers are also available to organizations that you configure to [share registry access](/terraform/enterprise/admin/application/registry-sharing). You must be a member of the [owners team](/terraform/cloud-docs/users-teams-organizations/permissions#organization-owners) or a team with [Manage Private Registry permissions](/terraform/cloud-docs/users-teams-organizations/permissions#manage-private-registry) to publish and delete private providers from the private registry. ### Release files You must publish at least one version of your provider that follows [semantic versioning format](http://semver.org). For each version, you must upload the `SHA256SUMS` file, `SHA256SUMS.sig` file, and one or more provider binaries. Using GoReleaser to [create a release on GitHub](/terraform/registry/providers/publishing#creating-a-github-release) or [create a release locally](/terraform/registry/providers/publishing#using-goreleaser-locally) generates these files automatically. The private registry does not have strict naming conventions, but we recommend using GoReleaser file naming schemes for consistency. Private providers do not currently support documentation. ### Signed releases GPG signing is required for private providers, and you must upload the public key of the GPG keypair used to sign the release. Refer to [Preparing and Adding a Signing Key](/terraform/registry/providers/publishing#preparing-and-adding-a-signing-key) for more details. Unlike the public Terraform Registry, the private registry does not automatically upload new releases. You must manually add new provider versions and the associated release files. -> **Note**: If you are using the [provider API](/terraform/cloud-docs/api-docs/private-registry/providers) to upload an official HashiCorp public provider into your private registry, use [HashiCorp's public PGP key](https://www.hashicorp.com/.well-known/pgp-key.txt). You do not need to upload this public key, and it is automatically included in Terraform Enterprise version v202309-1 and newer. ## Publishing a provider Before consumers can use a private provider, you must do the following: 1. [Create the provider](#create-the-provider) 2. [Upload a GPG signing key](#add-your-public-key) 3. [Create at least one version](#create-a-version) 4. [Create at least one platform for that version](#create-a-provider-platform) 5. [Upload release files](#upload-provider-binary) ### Create the provider Create a file named `provider.json` with the following contents. Replace `PROVIDER_NAME` with the name of your provider and replace `ORG_NAME` with the name of your organization. ```json { "data": { "type": "registry-providers", "attributes": { "name": "PROVIDER_NAME", "namespace": "ORG_NAME", "registry-name": "private" } } } ``` Use the [Create a Provider endpoint](/terraform/cloud-docs/api-docs/private-registry/providers#create-a-provider) to create the provider in HCP Terraform. Replace `TOKEN` in the `Authorization` header with your HCP Terraform API token and replace `ORG_NAME` with the name of your organization. ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @provider.json \ https://app.terraform.io/api/v2/organizations/ORG_NAME/registry-providers ``` The provider is now available in your organization’s HCP Terraform private registry, but consumers cannot use it until you add a version and a platform. To create a version and a platform, you need the following resources: * The Provider binaries * A public GPG signing key * A `SHA256SUMS` file * A `SHA256SUMS.sig` file from at least one release ### Add your public key -> **Note**: If you are uploading an official HashiCorp public provider into your private registry, skip this step and instead use [HashiCorp's public PGP key](https://www.hashicorp.com/.well-known/pgp-key.txt) in the the [create a version](#create-a-version) step. The key ID for HashiCorp's public ID is `34365D9472D7468F`, and you can verify the ID by [importing the public key locally](/terraform/tutorials/cli/verify-archive#download-and-import-hashicorp-s-public-key). Create a file named `key.json` with the following contents. Replace `ORG_NAME` with the name of your organization and supply your public key in the `ascii-armor` field. ```hcl { "data": { "type": "gpg-keys", "attributes": { "namespace": "ORG_NAME", "ascii-armor": "-----BEGIN PGP PUBLIC KEY BLOCK-----\n\nmQINB...=txfz\n-----END PGP PUBLIC KEY BLOCK-----\n" } } } ``` Use the [Add a GPG key endpoint](/terraform/cloud-docs/api-docs/private-registry/gpg-keys#add-a-gpg-key) to add the public key that matches the signing key for the release. Replace `TOKEN` in the `Authorization` header with your HCP Terraform API token. ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @key.json \ https://app.terraform.io/api/registry/private/v2/gpg-keys ``` The response contains a `key-id` that you will use to create a provider version. ```json "key-id": "34365D9472D7468F" ``` ### Create a version Create a file named `version.json` with the following contents. Replace the value of the `version` field with the version of your provider, and replace the `key-id` field with the id of the GPG key that you created in the [Add your public key](#add-your-public-key) step. If you are uploading an official HashiCorp public provider, use the value `34365D9472D7468F` for your `key-id`. ```hcl { "data": { "type": "registry-provider-versions", "attributes": { "version": "5.14.0", "key-id": "34365D9472D7468F", "protocols": ["5.0"] } } } ``` Use the [Create a Provider Version endpoint](/terraform/cloud-docs/api-docs/private-registry/provider-versions-platforms#create-a-provider-version) to create a version for your provider. Replace `TOKEN` in the `Authorization` header with your HCP Terraform API token, and replace both instances of `ORG_NAME` with the name of your organization. If are not using the `aws` provider, then replace `aws` with your provider's name. ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @version.json \ https://app.terraform.io/api/v2/organizations/ORG_NAME/registry-providers/private/ORG_NAME/aws/versions ``` The response includes URL links that you will use to upload the `SHA256SUMS` and `SHA256.sig` files. ```json "links": { "shasums-upload": "https://archivist.terraform.io/v1/object/dmF1b64hd73ghd63", "shasums-sig-upload": "https://archivist.terraform.io/v1/object/dmF1b37dj37dh33d" } ``` ### Upload signatures Upload the `SHA256SUMS` and `SHA256SUMS.sig` files to the URLs [returned in the previous step](#create-a-version). The example command below uploads the files from your local machine. First upload the `SHA256SUMS` file to the URL returned in the `shasums-upload` field. ```shell-session $ curl \ -T terraform-provider-aws_5.14.0_SHA256SUMS \ https://archivist.terraform.io/v1/object/dmF1b64hd73ghd63... ``` Next, upload the `SHA256SUMS.sig` file to the URL returned in the `shasums-sig-upload` field. ```shell-session $ curl \ -T terraform-provider-aws_5.14.0_SHA256SUMS.72D7468F.sig \ https://archivist.terraform.io/v1/object/dmF1b37dj37dh33d... ``` ### Create a provider platform First, calculate the SHA256 hash of the provider binary that you intend to upload. This should match the SHA256 hash of the file listed in the `SHA256SUMS` file. ```shell-session $ shasum -a 256 terraform-provider-aws_5.14.0_linux_amd64.zip f1d83b3e5a29bae471f9841a4e0153eac5bccedbdece369e2f6186e9044db64e terraform-provider-aws_5.14.0_linux_amd64.zip ``` Next, create a file named `platform.json`. Replace the `os`, `arch`, `filename`, and `shasum` fields with the values that match the provider you intend to upload. ```json { "data": { "type": "registry-provider-version-platforms", "attributes": { "os": "linux", "arch": "amd64", "shasum": "f1d83b3e5a29bae471f9841a4e0153eac5bccedbdece369e2f6186e9044db64e", "filename": "terraform-provider-aws_5.14.0_linux_amd64.zip" } } } ``` Use the [Create a Provider Platform endpoint](/terraform/cloud-docs/api-docs/private-registry/provider-versions-platforms#create-a-provider-platform) to create a platform for the version. Platforms are binaries that allow the provider to run on a particular operating system and architecture combination (e.g., Linux and AMD64). Replace `TOKEN` in the `Authorization` header with your HCP Terraform API token and replace both instances of `ORG_NAME` with the name of your organization. ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @platform.json \ https://app.terraform.io/api/v2/organizations/ORG_NAME/registry-providers/private/ORG_NAME/aws/versions/5.14.0/platforms ``` The response includes a `provider-binary-upload` URL that you will use to upload the binary file for the platform. ```json "links": { "provider-binary-upload": "https://archivist.terraform.io/v1/object/dmF1b45c367djh45nj78" } ``` ### Upload provider binary Upload the platform binary file to the `provider-binary-upload` URL returned in the [previous step](#create-a-version). The example command below uploads the binary from your local machine. ```shell-session $ curl -T local-example/terraform-provider-random_5.14.0_linux_amd64.zip https://archivist.terraform.io/v1/object/dmF1b45c367djh45nj78 ``` The version is available in the HCP Terraform user interface. Consumers can now begin using this provider version in configurations. You can repeat these steps starting from [Create a provider platform](#create-a-provider-platform) to add additional platform binaries for the release. ## Checking Release Files Consumers cannot use a private provider version until you upload all required [release files](#release-files). To determine whether these files have been uploaded: 1. Click **Registry** and click the private provider to go to its details page. 1. Use the version menu to navigate to the version you want to check. The UI shows a warning banner for versions that do not have all required release files. 1. Open the **Manage Provider** menu and select **Show release files**. The **Release Files** page appears containing lists of uploaded and missing files for the current version. ## Managing private providers Use the HCP Terraform API to create, read, update, and delete the following: - [GPG keys](/terraform/cloud-docs/api-docs/private-registry/gpg-keys) - [Private providers](/terraform/cloud-docs/api-docs/private-registry/providers) - [Provider versions and platforms](/terraform/cloud-docs/api-docs/private-registry/provider-versions-platforms) ## Deleting private providers and versions In addition to the [Registry Providers API](/terraform/cloud-docs/api-docs/private-registry/providers#delete-a-provider), you can delete providers and provider versions through the HCP Terraform UI. To delete providers and versions in the UI: 1. Click **Registry** and click the private provider to go to its details page. 1. If you want to delete a single version, use the **Versions** menu to select it. 1. Open the **Manage Provider** menu and select **Delete Provider**. The **Delete Provider from Organization** box appears. 1. Select an action from the menu: - **Delete only this provider version:** Deletes only the version of the provider you are currently viewing. - **Delete all versions for this provider:** Deletes the entire provider and all associated versions. 1. Type the provider name into the confirmation box and click **Delete**. The provider version or entire provider has been deleted from this organization's private registry and its data has been removed. Consumers will no longer be able to reference it in configurations. ### Restoring a deleted provider Deletion is permanent, but you can restore a deleted private provider by re-adding it to your organization and recreating its versions and platforms.
terraform
page title Publishing Private Providers Private Registry description Prepare private providers for publishing add them to the private registry and release new versions Publishing private providers to the HCP Terraform private registry In addition to curating public providers from the Terraform Registry terraform cloud docs registry add you can publish private providers to an organization s HCP Terraform private registry Once you have published a private provider through the API members of your organization can search for it in the private registry UI and use it in configurations Requirements Review the following before publishing a new provider or provider version Permissions Users must be members of an organization to access its registry and private providers In Terraform Enterprise providers are also available to organizations that you configure to share registry access terraform enterprise admin application registry sharing You must be a member of the owners team terraform cloud docs users teams organizations permissions organization owners or a team with Manage Private Registry permissions terraform cloud docs users teams organizations permissions manage private registry to publish and delete private providers from the private registry Release files You must publish at least one version of your provider that follows semantic versioning format http semver org For each version you must upload the SHA256SUMS file SHA256SUMS sig file and one or more provider binaries Using GoReleaser to create a release on GitHub terraform registry providers publishing creating a github release or create a release locally terraform registry providers publishing using goreleaser locally generates these files automatically The private registry does not have strict naming conventions but we recommend using GoReleaser file naming schemes for consistency Private providers do not currently support documentation Signed releases GPG signing is required for private providers and you must upload the public key of the GPG keypair used to sign the release Refer to Preparing and Adding a Signing Key terraform registry providers publishing preparing and adding a signing key for more details Unlike the public Terraform Registry the private registry does not automatically upload new releases You must manually add new provider versions and the associated release files Note If you are using the provider API terraform cloud docs api docs private registry providers to upload an official HashiCorp public provider into your private registry use HashiCorp s public PGP key https www hashicorp com well known pgp key txt You do not need to upload this public key and it is automatically included in Terraform Enterprise version v202309 1 and newer Publishing a provider Before consumers can use a private provider you must do the following 1 Create the provider create the provider 2 Upload a GPG signing key add your public key 3 Create at least one version create a version 4 Create at least one platform for that version create a provider platform 5 Upload release files upload provider binary Create the provider Create a file named provider json with the following contents Replace PROVIDER NAME with the name of your provider and replace ORG NAME with the name of your organization json data type registry providers attributes name PROVIDER NAME namespace ORG NAME registry name private Use the Create a Provider endpoint terraform cloud docs api docs private registry providers create a provider to create the provider in HCP Terraform Replace TOKEN in the Authorization header with your HCP Terraform API token and replace ORG NAME with the name of your organization shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data provider json https app terraform io api v2 organizations ORG NAME registry providers The provider is now available in your organization s HCP Terraform private registry but consumers cannot use it until you add a version and a platform To create a version and a platform you need the following resources The Provider binaries A public GPG signing key A SHA256SUMS file A SHA256SUMS sig file from at least one release Add your public key Note If you are uploading an official HashiCorp public provider into your private registry skip this step and instead use HashiCorp s public PGP key https www hashicorp com well known pgp key txt in the the create a version create a version step The key ID for HashiCorp s public ID is 34365D9472D7468F and you can verify the ID by importing the public key locally terraform tutorials cli verify archive download and import hashicorp s public key Create a file named key json with the following contents Replace ORG NAME with the name of your organization and supply your public key in the ascii armor field hcl data type gpg keys attributes namespace ORG NAME ascii armor BEGIN PGP PUBLIC KEY BLOCK n nmQINB txfz n END PGP PUBLIC KEY BLOCK n Use the Add a GPG key endpoint terraform cloud docs api docs private registry gpg keys add a gpg key to add the public key that matches the signing key for the release Replace TOKEN in the Authorization header with your HCP Terraform API token shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data key json https app terraform io api registry private v2 gpg keys The response contains a key id that you will use to create a provider version json key id 34365D9472D7468F Create a version Create a file named version json with the following contents Replace the value of the version field with the version of your provider and replace the key id field with the id of the GPG key that you created in the Add your public key add your public key step If you are uploading an official HashiCorp public provider use the value 34365D9472D7468F for your key id hcl data type registry provider versions attributes version 5 14 0 key id 34365D9472D7468F protocols 5 0 Use the Create a Provider Version endpoint terraform cloud docs api docs private registry provider versions platforms create a provider version to create a version for your provider Replace TOKEN in the Authorization header with your HCP Terraform API token and replace both instances of ORG NAME with the name of your organization If are not using the aws provider then replace aws with your provider s name shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data version json https app terraform io api v2 organizations ORG NAME registry providers private ORG NAME aws versions The response includes URL links that you will use to upload the SHA256SUMS and SHA256 sig files json links shasums upload https archivist terraform io v1 object dmF1b64hd73ghd63 shasums sig upload https archivist terraform io v1 object dmF1b37dj37dh33d Upload signatures Upload the SHA256SUMS and SHA256SUMS sig files to the URLs returned in the previous step create a version The example command below uploads the files from your local machine First upload the SHA256SUMS file to the URL returned in the shasums upload field shell session curl T terraform provider aws 5 14 0 SHA256SUMS https archivist terraform io v1 object dmF1b64hd73ghd63 Next upload the SHA256SUMS sig file to the URL returned in the shasums sig upload field shell session curl T terraform provider aws 5 14 0 SHA256SUMS 72D7468F sig https archivist terraform io v1 object dmF1b37dj37dh33d Create a provider platform First calculate the SHA256 hash of the provider binary that you intend to upload This should match the SHA256 hash of the file listed in the SHA256SUMS file shell session shasum a 256 terraform provider aws 5 14 0 linux amd64 zip f1d83b3e5a29bae471f9841a4e0153eac5bccedbdece369e2f6186e9044db64e terraform provider aws 5 14 0 linux amd64 zip Next create a file named platform json Replace the os arch filename and shasum fields with the values that match the provider you intend to upload json data type registry provider version platforms attributes os linux arch amd64 shasum f1d83b3e5a29bae471f9841a4e0153eac5bccedbdece369e2f6186e9044db64e filename terraform provider aws 5 14 0 linux amd64 zip Use the Create a Provider Platform endpoint terraform cloud docs api docs private registry provider versions platforms create a provider platform to create a platform for the version Platforms are binaries that allow the provider to run on a particular operating system and architecture combination e g Linux and AMD64 Replace TOKEN in the Authorization header with your HCP Terraform API token and replace both instances of ORG NAME with the name of your organization shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data platform json https app terraform io api v2 organizations ORG NAME registry providers private ORG NAME aws versions 5 14 0 platforms The response includes a provider binary upload URL that you will use to upload the binary file for the platform json links provider binary upload https archivist terraform io v1 object dmF1b45c367djh45nj78 Upload provider binary Upload the platform binary file to the provider binary upload URL returned in the previous step create a version The example command below uploads the binary from your local machine shell session curl T local example terraform provider random 5 14 0 linux amd64 zip https archivist terraform io v1 object dmF1b45c367djh45nj78 The version is available in the HCP Terraform user interface Consumers can now begin using this provider version in configurations You can repeat these steps starting from Create a provider platform create a provider platform to add additional platform binaries for the release Checking Release Files Consumers cannot use a private provider version until you upload all required release files release files To determine whether these files have been uploaded 1 Click Registry and click the private provider to go to its details page 1 Use the version menu to navigate to the version you want to check The UI shows a warning banner for versions that do not have all required release files 1 Open the Manage Provider menu and select Show release files The Release Files page appears containing lists of uploaded and missing files for the current version Managing private providers Use the HCP Terraform API to create read update and delete the following GPG keys terraform cloud docs api docs private registry gpg keys Private providers terraform cloud docs api docs private registry providers Provider versions and platforms terraform cloud docs api docs private registry provider versions platforms Deleting private providers and versions In addition to the Registry Providers API terraform cloud docs api docs private registry providers delete a provider you can delete providers and provider versions through the HCP Terraform UI To delete providers and versions in the UI 1 Click Registry and click the private provider to go to its details page 1 If you want to delete a single version use the Versions menu to select it 1 Open the Manage Provider menu and select Delete Provider The Delete Provider from Organization box appears 1 Select an action from the menu Delete only this provider version Deletes only the version of the provider you are currently viewing Delete all versions for this provider Deletes the entire provider and all associated versions 1 Type the provider name into the confirmation box and click Delete The provider version or entire provider has been deleted from this organization s private registry and its data has been removed Consumers will no longer be able to reference it in configurations Restoring a deleted provider Deletion is permanent but you can restore a deleted private provider by re adding it to your organization and recreating its versions and platforms
terraform Location Search for providers modules and usage examples in the HCP Terraform private registry UI All users in an organization can view the HCP Terraform private registry and use the available providers and modules A private registry has some key requirements and differences from the public Terraform Registry terraform registry Using Providers and Modules from the Private Registry Find available providers and modules and include them in configurations page title Using Providers and Modules Private Module Registry HCP Terraform
--- page_title: Using Providers and Modules - Private Module Registry - HCP Terraform description: Find available providers and modules and include them in configurations. --- # Using Providers and Modules from the Private Registry All users in an organization can view the HCP Terraform private registry and use the available providers and modules. A private registry has some key requirements and differences from the [public Terraform Registry](/terraform/registry): - **Location:** Search for providers, modules, and usage examples in the HCP Terraform private registry UI. - **Provider and Module block `source` argument:** Private providers and modules use a [different format](/terraform/cloud-docs/registry/using#using-private-providers-and-modules-in-configurations). - **Terraform version:** HCP Terraform workspaces using version 0.11 and higher can automatically access your private modules during Terraform runs, and workspaces using version 0.13 and higher can also automatically access private providers. - **Authentication:** If you run Terraform on the command line, you must [authenticate](/terraform/cloud-docs/registry/using#authentication) to HCP Terraform or your instance to use providers and modules in your organization’s private registry. HCP Terraform supports using modules in written configuration or through the [no-code provisioning workflow](/terraform/cloud-docs/no-code-provisioning/provisioning). ## Finding Providers and Modules To find available providers and modules, click the **Registry** button. The **Registry** page appears. Click **Providers** and **Modules** to toggle back and forth between lists of available providers and modules in the private registry. You can also use the search field to filter for titles that contain a specific keyword. The search does not include READMEs or resource details. ### Shared Providers and Modules - Terraform Enterprise On Terraform Enterprise, your [registry sharing](/terraform/enterprise/admin/application/registry-sharing) configuration may grant you access to another organization's providers and modules. Providers and modules that are shared with your current organization have a **Shared** badge in the private registry (below). Providers and modules in your current organization that are shared with other organizations have a badge that says **Sharing**. ### Viewing Provider and Module Details and Versions Click a provider or module to view its details page. Use the **Versions** menu in the upper right to switch between the available versions, and use the **Readme**, **Inputs**, **Outputs**, **Dependencies**, and **Resources** tabs to view more information about the selected version. ### Viewing Nested Modules and Examples Use the **Submodules** menu to navigate to the detail pages for any nested modules. Use the **Examples** menu to navigate to the detail pages for any available example modules. ## Provisioning Infrastructure from No-Code Ready Modules You can use modules marked **No-Code Ready** to create a new workspace and automatically provision the module's resources without writing any Terraform configuration. Refer to [Provisioning No-Code Infrastructure](/terraform/cloud-docs/no-code-provisioning/provisioning) for details. ## Using Public Providers and Modules in Configurations > **Hands-on:** Try the [Use Modules from the Registry](/terraform/tutorials/modules/module-use) tutorial. The syntax for public providers in a private registry is the same as for providers that you use directly from the public Terraform Registry. The syntax for the [provider block](/terraform/language/providers/configuration#provider-configuration-1) `source` argument is `<NAMESPACE>/<PROVIDER_NAME>`. ```hcl terraform { required_providers { google = { source = "hashicorp/google" version = "4.0.0" } } ``` The syntax for referencing public modules in the [module block](/terraform/language/modules/syntax) `source` argument is `<NAMESPACE>/<MODULE_NAME>/<PROVIDER_NAME>`. ```hcl module "subnets" { source = "hashicorp/subnets/cidr" version = "1.0.0" } ``` ## Using Private Providers and Modules in Configurations The syntax for referencing private providers in the [provider block](/terraform/language/providers/configuration#provider-configuration-1) `source` argument is `<HOSTNAME>/<NAMESPACE>/<PROVIDER_NAME>`. For the SaaS version of HCP Terraform, the hostname is `app.terraform.io`. ```hcl terraform { required_providers { random = { source = "app.terraform.io/demo-custom-provider/random" version = "1.1.0" } } ``` The syntax for referencing private modules in the [module block](/terraform/language/modules/syntax) `source` argument is `<HOSTNAME>/<ORGANIZATION>/<MODULE_NAME>/<PROVIDER_NAME>`. - **Hostname:** For the SaaS version of HCP Terraform, use `app.terraform.io`. In Terraform Enterprise, use the hostname for your instance or the [generic hostname](/terraform/cloud-docs/registry/using#generic-hostname-terraform-enterprise). - **Organization:** If you are using a shared module with Terraform Enterprise, the module's organization name may be different from your organization's name. Check the source string at the top of the module's registry page to find the proper organization name. ```hcl module "vpc" { source = "app.terraform.io/example_corp/vpc/aws" version = "1.0.4" } ``` ### Generic Hostname - HCP Terraform and Terraform Enterprise You can use the generic hostname `localterraform.com` in module sources to reference modules without modifying the HCP Terraform or Terraform Enterprise instance. When you run Terraform, it automatically requests any `localterraform.com` modules from the instance it runs on. ```hcl module "vpc" { source = "localterraform.com/example_corp/vpc/aws" version = "1.0.4" } ``` ~> **Important**: CLI-driven workflows require Terraform CLI v1.4.0 or above. To test configurations on a developer workstation without the remote backend configured, you must replace the generic hostname with a literal hostname in all module sources and then change them back before committing to VCS. We are working on making this workflow smoother, but we only recommend `localterraform.com` for large organizations that use multiple Terraform Enterprise instances. ### Provider and Module Availability A workspace can only use private providers and modules from its own organization's registry. When using providers or modules from multiple organizations in the same configuration, we recommend: - **HCP Terraform:** [Add providers and modules to the registry](/terraform/cloud-docs/registry/publish-modules#sharing-modules-across-organizations) for each organization that requires access. - **Terraform Enterprise:** Check your site's [registry sharing](/terraform/enterprise/admin/application/registry-sharing) configuration. Workspaces can also use private providers and modules from organizations that are sharing with the workspace's organization. ## Running Configurations with Private Providers and Modules ### Version Requirements Terraform version 0.11 or later is required to use private modules in HCP Terraform workspaces and to use the CLI to apply configurations with private modules. Terraform version 0.13 and later is required to use private providers in HCP Terraform workspaces and apply configurations with private providers. ### Authentication To authenticate with HCP Terraform, you can use either a [user token](/terraform/cloud-docs/users-teams-organizations/users#api-tokens) or a [team token](/terraform/cloud-docs/users-teams-organizations/api-tokens#team-api-tokens). The type of token you choose may grant different permissions. - **User Token**: Allows you to access providers and modules from any organization in which you are a member. You are a member of an organization if you belong to any team in that organization. You can also access modules from any organization that is sharing modules with any of your organizations. -> **Note:** When SAML SSO is enabled, there is a [session timeout for user API tokens](/terraform/enterprise/saml/login#api-token-expiration), requiring you to periodically re-authenticate through the web UI. Expired tokens produce a _401 Unauthorized_ error. A SAML SSO account with [IsServiceAccount](/terraform/enterprise/saml/attributes#isserviceaccount) is treated as a service account and will not have the session timeout. - **Team Token**: Allows you to access the private registry of that team's organization and the registries from any other organizations that have configured sharing. _Permissions Example_ A user belongs to three organizations (1, 2, and 3), and organizations 1 and 2 share access with each other. In this case, the user's token gives them access to the private registries for all of the organizations they belong to: 1, 2, and 3. However, a team token from a team in organization 1 only gives the user access to the private registry in organizations 1 and 2. #### Configure Authentication To configure authentication to HCP Terraform or your Terraform Enterprise instance, you can: - (Terraform 0.12.21 or later) Use the [`terraform login`](/terraform/cli/commands/login) command to obtain and save a user API token. - Create a token and [manually configure credentials in the CLI config file][cli-credentials]. Make sure the hostname matches the hostname you use in provider and module sources because if the same HCP Terraform server is available at two hostnames, Terraform will not know that they reference the same server. To support multiple hostnames for provider and module sources, use the `terraform login` command multiple times and specify a different hostname each time. [user-token]: /terraform/cloud-docs/users-teams-organizations/users#api-tokens [cli-credentials]: /terraform/cli/config/config-file#credentials [permissions-citation]: #intentionally-unused---keep-for-maintainers
terraform
page title Using Providers and Modules Private Module Registry HCP Terraform description Find available providers and modules and include them in configurations Using Providers and Modules from the Private Registry All users in an organization can view the HCP Terraform private registry and use the available providers and modules A private registry has some key requirements and differences from the public Terraform Registry terraform registry Location Search for providers modules and usage examples in the HCP Terraform private registry UI Provider and Module block source argument Private providers and modules use a different format terraform cloud docs registry using using private providers and modules in configurations Terraform version HCP Terraform workspaces using version 0 11 and higher can automatically access your private modules during Terraform runs and workspaces using version 0 13 and higher can also automatically access private providers Authentication If you run Terraform on the command line you must authenticate terraform cloud docs registry using authentication to HCP Terraform or your instance to use providers and modules in your organization s private registry HCP Terraform supports using modules in written configuration or through the no code provisioning workflow terraform cloud docs no code provisioning provisioning Finding Providers and Modules To find available providers and modules click the Registry button The Registry page appears Click Providers and Modules to toggle back and forth between lists of available providers and modules in the private registry You can also use the search field to filter for titles that contain a specific keyword The search does not include READMEs or resource details Shared Providers and Modules Terraform Enterprise On Terraform Enterprise your registry sharing terraform enterprise admin application registry sharing configuration may grant you access to another organization s providers and modules Providers and modules that are shared with your current organization have a Shared badge in the private registry below Providers and modules in your current organization that are shared with other organizations have a badge that says Sharing Viewing Provider and Module Details and Versions Click a provider or module to view its details page Use the Versions menu in the upper right to switch between the available versions and use the Readme Inputs Outputs Dependencies and Resources tabs to view more information about the selected version Viewing Nested Modules and Examples Use the Submodules menu to navigate to the detail pages for any nested modules Use the Examples menu to navigate to the detail pages for any available example modules Provisioning Infrastructure from No Code Ready Modules You can use modules marked No Code Ready to create a new workspace and automatically provision the module s resources without writing any Terraform configuration Refer to Provisioning No Code Infrastructure terraform cloud docs no code provisioning provisioning for details Using Public Providers and Modules in Configurations Hands on Try the Use Modules from the Registry terraform tutorials modules module use tutorial The syntax for public providers in a private registry is the same as for providers that you use directly from the public Terraform Registry The syntax for the provider block terraform language providers configuration provider configuration 1 source argument is NAMESPACE PROVIDER NAME hcl terraform required providers google source hashicorp google version 4 0 0 The syntax for referencing public modules in the module block terraform language modules syntax source argument is NAMESPACE MODULE NAME PROVIDER NAME hcl module subnets source hashicorp subnets cidr version 1 0 0 Using Private Providers and Modules in Configurations The syntax for referencing private providers in the provider block terraform language providers configuration provider configuration 1 source argument is HOSTNAME NAMESPACE PROVIDER NAME For the SaaS version of HCP Terraform the hostname is app terraform io hcl terraform required providers random source app terraform io demo custom provider random version 1 1 0 The syntax for referencing private modules in the module block terraform language modules syntax source argument is HOSTNAME ORGANIZATION MODULE NAME PROVIDER NAME Hostname For the SaaS version of HCP Terraform use app terraform io In Terraform Enterprise use the hostname for your instance or the generic hostname terraform cloud docs registry using generic hostname terraform enterprise Organization If you are using a shared module with Terraform Enterprise the module s organization name may be different from your organization s name Check the source string at the top of the module s registry page to find the proper organization name hcl module vpc source app terraform io example corp vpc aws version 1 0 4 Generic Hostname HCP Terraform and Terraform Enterprise You can use the generic hostname localterraform com in module sources to reference modules without modifying the HCP Terraform or Terraform Enterprise instance When you run Terraform it automatically requests any localterraform com modules from the instance it runs on hcl module vpc source localterraform com example corp vpc aws version 1 0 4 Important CLI driven workflows require Terraform CLI v1 4 0 or above To test configurations on a developer workstation without the remote backend configured you must replace the generic hostname with a literal hostname in all module sources and then change them back before committing to VCS We are working on making this workflow smoother but we only recommend localterraform com for large organizations that use multiple Terraform Enterprise instances Provider and Module Availability A workspace can only use private providers and modules from its own organization s registry When using providers or modules from multiple organizations in the same configuration we recommend HCP Terraform Add providers and modules to the registry terraform cloud docs registry publish modules sharing modules across organizations for each organization that requires access Terraform Enterprise Check your site s registry sharing terraform enterprise admin application registry sharing configuration Workspaces can also use private providers and modules from organizations that are sharing with the workspace s organization Running Configurations with Private Providers and Modules Version Requirements Terraform version 0 11 or later is required to use private modules in HCP Terraform workspaces and to use the CLI to apply configurations with private modules Terraform version 0 13 and later is required to use private providers in HCP Terraform workspaces and apply configurations with private providers Authentication To authenticate with HCP Terraform you can use either a user token terraform cloud docs users teams organizations users api tokens or a team token terraform cloud docs users teams organizations api tokens team api tokens The type of token you choose may grant different permissions User Token Allows you to access providers and modules from any organization in which you are a member You are a member of an organization if you belong to any team in that organization You can also access modules from any organization that is sharing modules with any of your organizations Note When SAML SSO is enabled there is a session timeout for user API tokens terraform enterprise saml login api token expiration requiring you to periodically re authenticate through the web UI Expired tokens produce a 401 Unauthorized error A SAML SSO account with IsServiceAccount terraform enterprise saml attributes isserviceaccount is treated as a service account and will not have the session timeout Team Token Allows you to access the private registry of that team s organization and the registries from any other organizations that have configured sharing Permissions Example A user belongs to three organizations 1 2 and 3 and organizations 1 and 2 share access with each other In this case the user s token gives them access to the private registries for all of the organizations they belong to 1 2 and 3 However a team token from a team in organization 1 only gives the user access to the private registry in organizations 1 and 2 Configure Authentication To configure authentication to HCP Terraform or your Terraform Enterprise instance you can Terraform 0 12 21 or later Use the terraform login terraform cli commands login command to obtain and save a user API token Create a token and manually configure credentials in the CLI config file cli credentials Make sure the hostname matches the hostname you use in provider and module sources because if the same HCP Terraform server is available at two hostnames Terraform will not know that they reference the same server To support multiple hostnames for provider and module sources use the terraform login command multiple times and specify a different hostname each time user token terraform cloud docs users teams organizations users api tokens cli credentials terraform cli config config file credentials permissions citation intentionally unused keep for maintainers
terraform We recommend that you test your Sentinel policies extensively before deploying page title Mocking Terraform Sentinel Data Sentinel HCP Terraform Learn how to use the UI or API to generate mock Sentinel data and how to use Mocking Terraform Sentinel Data that data for testing
--- page_title: Mocking Terraform Sentinel Data - Sentinel - HCP Terraform description: >- Learn how to use the UI or API to generate mock Sentinel data and how to use that data for testing. --- # Mocking Terraform Sentinel Data We recommend that you test your Sentinel policies extensively before deploying them within HCP Terraform. An important part of this process is mocking the data that you wish your policies to operate on. <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/policies.mdx' <!-- END: TFC:only name:pnp-callout --> Due to the highly variable structure of data that can be produced by an individual Terraform configuration, HCP Terraform provides the ability to generate mock data from existing configurations. This can be used to create sample data for a new policy, or data to reproduce issues in an existing one. Testing policies is done using the [Sentinel CLI](https://docs.hashicorp.com/sentinel/commands). More general information on testing Sentinel policies can be found in the [Testing section](https://docs.hashicorp.com/sentinel/writing/testing) of the [Sentinel runtime documentation](https://docs.hashicorp.com/sentinel). ~> **Be careful!** Mock data generated by HCP Terraform directly exposes any and all data within the configuration, plan, and state. Terraform attempts to scrub sensitive data from these mocks, but we do not guarantee 100% accuracy. Treat this data with care, and avoid generating mocks with live sensitive data when possible. Access to this information requires [permission to download Sentinel mocks](/terraform/cloud-docs/users-teams-organizations/permissions) for the workspace where the data was generated. [permissions-citation]: #intentionally-unused---keep-for-maintainers ## Generating Mock Data Using the UI Mock data can be generated using the UI by expanding the plan status section of the run page, and clicking on the **Download Sentinel mocks** button. ![sentinel mock generate ui](/img/docs/download-mocks.png) For more information on creating a run, see the [Terraform Runs and Remote Operations](/terraform/cloud-docs/run/remote-operations) section of the docs. If the button is not visible, then the plan is ineligible for mock generation or the user doesn't have the necessary permissions. See [Mock Data Availability](#mock-data-availability) for more details. ## Generating Mock Data Using the API Mock data can also be created with the [Plan Export API](/terraform/cloud-docs/api-docs/plan-exports). Multiple steps are required for mock generation. The export process is asynchronous, so you must monitor the request to know when the data is generated and available for download. 1. Get the plan ID for the run that you want to generate the mock for by [getting the run details](/terraform/cloud-docs/api-docs/run#get-run-details). Look for the `id` of the `plan` object within the `relationships` section of the return data. 1. [Request a plan export](/terraform/cloud-docs/api-docs/plan-exports#create-a-plan-export) using the discovered plan ID. Supply the Sentinel export type `sentinel-mock-bundle-v0`. 1. Monitor the export request by [viewing the plan export](/terraform/cloud-docs/api-docs/plan-exports#show-a-plan-export). When the status is `finished`, the data is ready for download. 1. Finally, [download the export data](/terraform/cloud-docs/api-docs/plan-exports#download-exported-plan-data). You have up to an hour from the completion of the export request - after that, the mock data expires and must be re-generated. ## Using Mock Data -> **Note:** The v2 mock files are only available on Terraform 0.12 and higher. Mock data is supplied as a bundled tarball, containing the following files: ``` mock-tfconfig.sentinel # tfconfig mock data mock-tfconfig-v2.sentinel # tfconfig/v2 mock data mock-tfplan.sentinel # tfplan mock data mock-tfplan-v2.sentinel # tfplan/v2 mock data mock-tfstate.sentinel # tfstate mock data mock-tfstate-v2.sentinel # tfstate/v2 mock data mock-tfrun.sentinel # tfrun mock data sentinel.hcl # sample configuration file ``` The sample `sentinel.hcl` file contains mappings to the mocks so that you can get started testing with `sentinel apply` right away. For `sentinel test`, however, we recommend a more detailed layout. We recommend placing the files for `sentinel test` in a subdirectory of the repository holding your policies, so they don't interfere with the command's automatic policy detection. While the test data is Sentinel code, it's not a policy and will produce errors if evaluated like one. ``` . ├── foo.sentinel ├── sentinel.hcl ├── test │   └── foo │   ├── fail.hcl │   └── pass.hcl └── testdata ├── mock-tfconfig.sentinel ├── mock-tfconfig-v2.sentinel ├── mock-tfplan.sentinel ├── mock-tfplan-v2.sentinel ├── mock-tfstate.sentinel ├── mock-tfstate-v2.sentinel └── mock-tfrun.sentinel ``` Each configuration that needs access to the mock should reference the mock data files within the `mock` block in the Sentinel configuration file. For `sentinel apply`, this path is relative to the working directory. Assuming you always run this command from the repository root, the `sentinel.hcl` configuration file would look like: ```hcl mock "tfconfig" { module { source = "testdata/mock-tfconfig.sentinel" } } mock "tfconfig/v1" { module { source = "testdata/mock-tfconfig.sentinel" } } mock "tfconfig/v2" { module { source = "testdata/mock-tfconfig-v2.sentinel" } } mock "tfplan" { module { source = "testdata/mock-tfplan.sentinel" } } mock "tfplan/v1" { module { source = "testdata/mock-tfplan.sentinel" } } mock "tfplan/v2" { module { source = "testdata/mock-tfplan-v2.sentinel" } } mock "tfstate" { module { source = "testdata/mock-tfstate.sentinel" } } mock "tfstate/v1" { module { source = "testdata/mock-tfstate.sentinel" } } mock "tfstate/v2" { module { source = "testdata/mock-tfstate-v2.sentinel" } } mock "tfrun" { module { source = "testdata/mock-tfrun.sentinel" } } ``` For `sentinel test`, the paths are relative to the specific test configuration file. For example, the contents of `pass.hcl`, asserting that the result of the `main` rule was `true`, would be: ``` mock "tfconfig" { module { source = "../../testdata/mock-tfconfig.sentinel" } } mock "tfconfig/v1" { module { source = "../../testdata/mock-tfconfig.sentinel" } } mock "tfconfig/v2" { module { source = "../../testdata/mock-tfconfig-v2.sentinel" } } mock "tfplan" { module { source = "../../testdata/mock-tfplan.sentinel" } } mock "tfplan/v1" { module { source = "../../testdata/mock-tfplan.sentinel" } } mock "tfplan/v2" { module { source = "../../testdata/mock-tfplan-v2.sentinel" } } mock "tfstate" { module { source = "../../testdata/mock-tfstate.sentinel" } } mock "tfstate/v1" { module { source = "../../testdata/mock-tfstate.sentinel" } } mock "tfstate/v2" { module { source = "../../testdata/mock-tfstate-v2.sentinel" } } mock "tfrun" { module { source = "../../testdata/mock-tfrun.sentinel" } } test { rules = { main = true } } ``` ## Mock Data Availability The following factors can prevent you from generating mock data: * You do not have permission to download Sentinel mocks for the workspace. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) Permission is required to protect the possibly sensitive data which can be produced via mock generation. * The run has not progressed past the planning stage, or did not create a plan successfully. * The run progressed past the planning stage prior to July 23, 2021. Prior to this date, HCP Terraform only kept JSON plans for 7 days. [permissions-citation]: #intentionally-unused---keep-for-maintainers If a plan cannot have its mock data exported due to any of these reasons, the **Download Sentinel mocks** button within the plan status section of the UI will not be visible. -> **Note:** Only a successful plan is required for mock generation. Sentinel can still generate the data if apply or policy checks fail.
terraform
page title Mocking Terraform Sentinel Data Sentinel HCP Terraform description Learn how to use the UI or API to generate mock Sentinel data and how to use that data for testing Mocking Terraform Sentinel Data We recommend that you test your Sentinel policies extensively before deploying them within HCP Terraform An important part of this process is mocking the data that you wish your policies to operate on BEGIN TFC only name pnp callout include tfc package callouts policies mdx END TFC only name pnp callout Due to the highly variable structure of data that can be produced by an individual Terraform configuration HCP Terraform provides the ability to generate mock data from existing configurations This can be used to create sample data for a new policy or data to reproduce issues in an existing one Testing policies is done using the Sentinel CLI https docs hashicorp com sentinel commands More general information on testing Sentinel policies can be found in the Testing section https docs hashicorp com sentinel writing testing of the Sentinel runtime documentation https docs hashicorp com sentinel Be careful Mock data generated by HCP Terraform directly exposes any and all data within the configuration plan and state Terraform attempts to scrub sensitive data from these mocks but we do not guarantee 100 accuracy Treat this data with care and avoid generating mocks with live sensitive data when possible Access to this information requires permission to download Sentinel mocks terraform cloud docs users teams organizations permissions for the workspace where the data was generated permissions citation intentionally unused keep for maintainers Generating Mock Data Using the UI Mock data can be generated using the UI by expanding the plan status section of the run page and clicking on the Download Sentinel mocks button sentinel mock generate ui img docs download mocks png For more information on creating a run see the Terraform Runs and Remote Operations terraform cloud docs run remote operations section of the docs If the button is not visible then the plan is ineligible for mock generation or the user doesn t have the necessary permissions See Mock Data Availability mock data availability for more details Generating Mock Data Using the API Mock data can also be created with the Plan Export API terraform cloud docs api docs plan exports Multiple steps are required for mock generation The export process is asynchronous so you must monitor the request to know when the data is generated and available for download 1 Get the plan ID for the run that you want to generate the mock for by getting the run details terraform cloud docs api docs run get run details Look for the id of the plan object within the relationships section of the return data 1 Request a plan export terraform cloud docs api docs plan exports create a plan export using the discovered plan ID Supply the Sentinel export type sentinel mock bundle v0 1 Monitor the export request by viewing the plan export terraform cloud docs api docs plan exports show a plan export When the status is finished the data is ready for download 1 Finally download the export data terraform cloud docs api docs plan exports download exported plan data You have up to an hour from the completion of the export request after that the mock data expires and must be re generated Using Mock Data Note The v2 mock files are only available on Terraform 0 12 and higher Mock data is supplied as a bundled tarball containing the following files mock tfconfig sentinel tfconfig mock data mock tfconfig v2 sentinel tfconfig v2 mock data mock tfplan sentinel tfplan mock data mock tfplan v2 sentinel tfplan v2 mock data mock tfstate sentinel tfstate mock data mock tfstate v2 sentinel tfstate v2 mock data mock tfrun sentinel tfrun mock data sentinel hcl sample configuration file The sample sentinel hcl file contains mappings to the mocks so that you can get started testing with sentinel apply right away For sentinel test however we recommend a more detailed layout We recommend placing the files for sentinel test in a subdirectory of the repository holding your policies so they don t interfere with the command s automatic policy detection While the test data is Sentinel code it s not a policy and will produce errors if evaluated like one foo sentinel sentinel hcl test foo fail hcl pass hcl testdata mock tfconfig sentinel mock tfconfig v2 sentinel mock tfplan sentinel mock tfplan v2 sentinel mock tfstate sentinel mock tfstate v2 sentinel mock tfrun sentinel Each configuration that needs access to the mock should reference the mock data files within the mock block in the Sentinel configuration file For sentinel apply this path is relative to the working directory Assuming you always run this command from the repository root the sentinel hcl configuration file would look like hcl mock tfconfig module source testdata mock tfconfig sentinel mock tfconfig v1 module source testdata mock tfconfig sentinel mock tfconfig v2 module source testdata mock tfconfig v2 sentinel mock tfplan module source testdata mock tfplan sentinel mock tfplan v1 module source testdata mock tfplan sentinel mock tfplan v2 module source testdata mock tfplan v2 sentinel mock tfstate module source testdata mock tfstate sentinel mock tfstate v1 module source testdata mock tfstate sentinel mock tfstate v2 module source testdata mock tfstate v2 sentinel mock tfrun module source testdata mock tfrun sentinel For sentinel test the paths are relative to the specific test configuration file For example the contents of pass hcl asserting that the result of the main rule was true would be mock tfconfig module source testdata mock tfconfig sentinel mock tfconfig v1 module source testdata mock tfconfig sentinel mock tfconfig v2 module source testdata mock tfconfig v2 sentinel mock tfplan module source testdata mock tfplan sentinel mock tfplan v1 module source testdata mock tfplan sentinel mock tfplan v2 module source testdata mock tfplan v2 sentinel mock tfstate module source testdata mock tfstate sentinel mock tfstate v1 module source testdata mock tfstate sentinel mock tfstate v2 module source testdata mock tfstate v2 sentinel mock tfrun module source testdata mock tfrun sentinel test rules main true Mock Data Availability The following factors can prevent you from generating mock data You do not have permission to download Sentinel mocks for the workspace More about permissions terraform cloud docs users teams organizations permissions Permission is required to protect the possibly sensitive data which can be produced via mock generation The run has not progressed past the planning stage or did not create a plan successfully The run progressed past the planning stage prior to July 23 2021 Prior to this date HCP Terraform only kept JSON plans for 7 days permissions citation intentionally unused keep for maintainers If a plan cannot have its mock data exported due to any of these reasons the Download Sentinel mocks button within the plan status section of the UI will not be visible Note Only a successful plan is required for mock generation Sentinel can still generate the data if apply or policy checks fail
terraform Policies and policy sets Add policies to HCP Terraform group policies into policy sets and apply policy sets to workspaces HCP Terraform checks the Terraform plan against the policy set for each run Policies are rules that HCP Terraform enforces on Terraform runs You can define policies using either the Sentinel terraform cloud docs policy enforcement sentinel or Open Policy Agent OPA terraform cloud docs policy enforcement opa policy as code frameworks page title Manage Policies and Policy Sets HCP Terraform
--- page_title: Manage Policies and Policy Sets - HCP Terraform description: >- Add policies to HCP Terraform, group policies into policy sets, and apply policy sets to workspaces. HCP Terraform checks the Terraform plan against the policy set for each run. --- # Policies and policy sets Policies are rules that HCP Terraform enforces on Terraform runs. You can define policies using either the [Sentinel](/terraform/cloud-docs/policy-enforcement/sentinel) or [Open Policy Agent (OPA)](/terraform/cloud-docs/policy-enforcement/opa) policy-as-code frameworks. <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/policies.mdx' <!-- END: TFC:only name:pnp-callout --> Policy sets are collections of policies you can apply globally or to specific [projects](/terraform/cloud-docs/projects/manage) and workspaces in your organization. For each run in the applicable workspaces, HCP Terraform checks the Terraform plan against the policy set. Depending on the [enforcement level](#policy-enforcement-levels), failed policies can stop a run in a workspace. If you do not want to enforce a policy set on a specific workspace, you can exclude the workspace from that set. ## Permissions To view and manage policies and policy sets, you must have [manage policy permissions](/terraform/cloud-docs/users-teams-organizations/permissions#manage-policies) for your organization. ## Policy checks versus policy evaluations Policy checks and evaluations can access different types of data and enable slightly different workflows. ### Policy checks Only Sentinel policies can run as policy checks. Checks can access cost estimation data but can only use the latest version of Sentinel. ~> **Warning:** Policy checks are deprecated and will be permanently removed in August 2025. We recommend that you start using policy evaluations to avoid disruptions. ### Policy evaluations OPA policy sets can only run as policy evaluations, and you can enable policy evaluations for Sentinel policy sets by selecting the `Enhanced` policy set type. Policy evaluations run within the [HCP Terraform agent](/terraform/cloud-docs/agents) in HCP Terraform's infrastructure. For Sentinel policy sets, using policy evaluations lets you: - Enable overrides for soft-mandatory and hard-mandatory policies, letting any user with [Manage Policy Overrides permission](/terraform/cloud-docs/users-teams-organizations/permissions#manage-policy-overrides) proceed with a run in the event of policy failure. - Select a specific Sentinel runtime version for the policy set. Policy evaluations **cannot** access cost estimation data, so use policy checks if your policies rely on cost estimates. ~> **Tip:** Sentinel runtime version pinning is supported only for Sentinel 0.23.1 and above, as well as HCP Terraform agent versions 1.13.1 and above ## Policy enforcement levels You can set an enforcement level for each policy that determines what happens when a Terraform plan does not pass the policy rule. Sentinel and OPA policies have different enforcement levels available. ### Sentinel Sentinel provides three policy enforcement levels: - **advisory:** Failed policies never interrupt the run. They provide information about policy check failures in the UI. - **soft mandatory:** Failed policies stop the run, but any user with [Manage Policy Overrides permission](/terraform/cloud-docs/users-teams-organizations/permissions#manage-policy-overrides) can override these failures and allow the run to complete. - **hard mandatory:** Failed policies stop the run. Terraform does not apply runs with failed **hard mandatory** policies until a user fixes the issue that caused the failure. ### OPA OPA provides two policy enforcement levels: - **advisory** Failed policies never interrupt the run. They provide information about policy failures in the UI. - **mandatory:** Failed policies stop the run, but any user with [Manage Policy Overrides permission](/terraform/cloud-docs/users-teams-organizations/permissions#manage-policy-overrides) can override these failures and allow the run to complete. ## Policy publishing workflows You can create policies and policy sets for your HCP Terraform organization in one of three ways: - **HCP Terraform web UI:** Add individually-managed policies manually in the HCP Terraform UI, and store your policy code in HCP Terraform. This workflow is ideal for initial experimentation with policy enforcement, but we do not recommend it for organizations with large numbers of policies. - **Version control:** Connect HCP Terraform to a version control repository containing a policy set. When you push changes to the repository, HCP Terraform automatically uses the updated policy set. - **Automated:** Push versions of policy sets to HCP Terraform with the [HCP Terraform Policy Sets API](/terraform/cloud-docs/api-docs/policy-sets#create-a-policy-set-version) or the `tfe` provider [`tfe_policy_set`](https://registry.terraform.io/providers/hashicorp/tfe/latest/docs/resources/policy_set) resource. This workflow is ideal for automated Continuous Integration and Deployment (CI/CD) pipelines. ### Manage individual policies in the web UI You can add policies directly to HCP Terraform using the web UI. This process requires you to paste completed, valid Sentinel or Rego code into the UI. We recommend validating your policy code before adding it to HCP Terraform. #### Add managed policies To add an individually managed policy: 1. Go to **Policies** in your organization’s settings. A list of managed policies in HCP Terraform appears. Each policy designates its policy framework (Sentinel or OPA) and associated policy sets. 1. Click **Create a new policy**. 1. Choose the **Policy framework** you want to use. You can only create a policy set from policies written using the same framework. You cannot change the framework type after you create the policy. 1. Complete the following fields to define the policy: - **Policy Name:** Add a name containing letters, numbers, `-`, and `_`. HCP Terraform displays this name in the UI. The name must be unique within your organization. - **Description:** Describe the policy’s purpose. The description supports Markdown rendering, and HCP Terraform displays this text in the UI. - **Enforcement mode:** Choose whether this policy can stop Terraform runs and whether users can override it. Refer to [policy enforcement levels](#policy-enforcement-levels) for more details. - **(OPA Only) Query:** Write a query to identify a specific policy rule within your rego code. HCP Terraform uses this query to determine the result of the policy. The query is typically a combination of the policy package name and rule name, such as `terraform.deny`. The result of this query must be an array. The policy passes when the array is empty. - **Policy code**: Paste the code for the policy: either Sentinel code or Rego code for OPA policies. The UI provides syntax highlighting for the policy language. - **(Optional) Policy sets:** Select one or more existing managed policy sets where you want to add the new policy. You can only select policy sets compatible with the chosen policy set framework. If there are no policy sets available, you can [create a new one](#create-policy-sets). The policy is now available in the HCP Terraform UI for you to edit and add to one or more policy sets. #### Edit managed policies To edit a managed policy: - Go to **Policies** in your organization’s settings. - Click the policy you want to edit to go to its details page. - Edit the policy's fields and then click **Update policy**. #### Delete managed policies ~> **Warning:** Deleting a policy that applies to an active run causes that run’s policy evaluation stage to error. We recommend warning other members of your organization before you delete widely used policies. You can not restore policies after deletion. You must manually re-add them to HCP Terraform. You may want to save the policy code in a separate location before you delete the policy. To delete a managed policy: - Go to **Policies** in your organization’s settings. - Click the policy you want to delete to go to its details page. - Click **Delete policy** and then click **Yes, delete policy** to confirm. The policy no longer appears in HCP Terraform and in any associated policy sets. ## Manage policy sets Policy sets are collections of policies that you can apply globally or to specific [projects](/terraform/cloud-docs/projects/manage) and workspaces. To view and manage policy sets, go to the **Policy Sets** section of your organization’s settings. This page contains all of the policy sets available in the organization, including those added through the API. The way you set up and configure a new policy set depends on your workflow and where you store policies. - For [managed policies](#managed-policies), you use the UI to create a policy set and add managed policies. - For policy sets in a version control system, you use the UI to create a policy set connected to that repository. HCP Terraform automatically refreshes the policy set when you change relevant files in that repository. Version control policy sets have specific organization and formatting requirements. Refer to [Sentinel VCS Repositories](/terraform/cloud-docs/policy-enforcement/sentinel/vcs) and [OPA VCS Repositories](/terraform/cloud-docs/policy-enforcement/opa/vcs) for details. - For automated workflows like continuous deployment, you can use the UI to create an empty policy set and then use the [Policy Sets API](/terraform/cloud-docs/api-docs/policy-sets) to add policies. You can also use the API or the [`tfe` provider (Sentinel Only)](https://registry.terraform.io/providers/hashicorp/tfe/latest/docs/resources/policy_set) to add an entire, packaged policy set. ### Create policy sets To create a policy set: 1. Go to **Policy Sets** in your organization’s settings. 1. Click **Connect a new policy set**. 1. Choose your workflow. - For managed policies, click **create a policy set with individually managed policies**. HCP Terraform shows a form to create a policy set and add individually managed policies. - For version control policies, choose a version control provider and then select the repository with your policy set. HCP Terraform shows a form to create a policy set connected to that repository. - For automated workflows, click **No VCS Connection**. HCP Terraform shows a form to create an empty policy set. You can use the API to add policies to this empty policy set later. 1. Choose a **Policy framework** for the policies you want to add. A policy set can only contain policies that use the same framework (OPA or Sentinel). You cannot change a policy set's framework type after creation. 1. Choose a policy set scope: - **Policies enforced globally:** HCP Terraform automatically enforces this global policy set on all of an organization's existing and future workspaces. - **Policies enforced on selected projects and workspaces:** Use the text fields to find and select the workspaces and projects to enforce this policy set on. This affects all current and future workspaces for any chosen projects. 1. **(Optional)** Add **Policy exclusions** for this policy set. Specify any workspaces in the policy set's scope that HCP Terraform will not enforce this policy set on. 1. **(Sentinel Only)** Choose a policy set type: - **Standard:** This is the default workflow. A Sentinel policy set uses a [policy check](#policy-checks) in HCP Terraform and lets you access cost estimation data. - **Enhanced:** A Sentinel policy set uses a [policy evaluation](#policy-evaluations) in HCP Terraform. This lets you enable policy overrides and enforce a Sentinel runtime version 1. **(OPA Only)** Select a **Runtime version** for this policy set. 1. **(OPA Only)** Allow **Overrides**, which enables users with override policy permissions to apply plans that have [mandatory policy](#policy-enforcement-levels) failures. 1. **(VCS Only)** Optionally specify the **VCS branch** within your VCS repository where HCP Terraform should import new versions of policies. If you do not set this field, HCP Terraform uses your selected VCS repository's default branch. 1. **(VCS Only)** Specify where your policy set files live using the **Policies path**. This lets you maintain multiple policy sets within a single repository. Use a relative path from your root directory to the directory that contains either the `sentinel.hcl` (Sentinel) or `policies.hcl` (OPA) configuration files. If you do not set this field, HCP Terraform uses the repository's root directory. 1. **(Managed Policies Only)** Select managed **Policies** to add to the policy set. You can only add policies written with the same policy framework you selected for this set. 1. Choose a descriptive and unique **Name** for the policy set. You can use any combination of letters, numbers, `-`, and `_`. 1. Write an optional **Description** that tells other users about the purpose of the policy set and what it contains. ### Edit policy sets To edit a policy set: 1. Go to the **Policy Sets** section of your organization’s settings. 1. Click the policy set you want to edit to go to its settings page. 1. Adjust the settings and click **Update policy set**. ### Evaluate a policy runtime upgrade You can validate that changing a policy runtime version does not introduce any breaking changes. To perform a policy evaluation: 1. Go to the **Policy Sets** section of your organization’s settings. 1. Click the policy set you want to upgrade. 1. Click the **Evaluate** tab. 1. Select the **Runtime version** you wish to upgrade to. 1. Select a **Workspace** to test the policy and upgraded version against. 1. Click **Evaluate**. HCP Terraform will execute the policy set using the specified version and the latest plan data for the selected workspace. It will display the evaluation results. If the evaluation returns a `Failed` status, inspect the JSON output to determine whether the issue is related to a non-compliant resource or is due to a syntax issue. If the evaluation results in an error, check that the policy configuration is valid. ### Delete policy sets ~> **Warning:** Deleting a policy set that applies to an active run causes that run’s policy evaluation stage to error. We recommend warning other members of your organization before you delete widely used policy sets. You can not restore policy sets after deletion. You must manually re-add them to HCP Terraform. To delete a policy set: 1. Go to **Policy Sets** in your organization’s settings. 2. Click the policy set you want to delete to go to its details page. 3. Click **Delete policy** and then click **Yes, delete policy set** to confirm. The policy set no longer appears on the UI and HCP Terraform no longer applies it to any workspaces. For managed policy sets, all of the individual policies are still available in HCP Terraform. You must delete each policy individually to remove it from your organization. ### (Sentinel only) Sentinel parameters [Sentinel parameters](https://docs.hashicorp.com/sentinel/language/parameters) are a list of key/value pairs that HCP Terraform sends to the Sentinel runtime when performing policy checks on workspaces. If the value parses as JSON, HCP Terraform sends it to Sentinel as the corresponding type (string, boolean, integer, map, or list). If the value fails JSON validation, HCP Terraform sends it as a string. You can set Sentinel parameters when you [edit a policy set](#edit-policy-sets).
terraform
page title Manage Policies and Policy Sets HCP Terraform description Add policies to HCP Terraform group policies into policy sets and apply policy sets to workspaces HCP Terraform checks the Terraform plan against the policy set for each run Policies and policy sets Policies are rules that HCP Terraform enforces on Terraform runs You can define policies using either the Sentinel terraform cloud docs policy enforcement sentinel or Open Policy Agent OPA terraform cloud docs policy enforcement opa policy as code frameworks BEGIN TFC only name pnp callout include tfc package callouts policies mdx END TFC only name pnp callout Policy sets are collections of policies you can apply globally or to specific projects terraform cloud docs projects manage and workspaces in your organization For each run in the applicable workspaces HCP Terraform checks the Terraform plan against the policy set Depending on the enforcement level policy enforcement levels failed policies can stop a run in a workspace If you do not want to enforce a policy set on a specific workspace you can exclude the workspace from that set Permissions To view and manage policies and policy sets you must have manage policy permissions terraform cloud docs users teams organizations permissions manage policies for your organization Policy checks versus policy evaluations Policy checks and evaluations can access different types of data and enable slightly different workflows Policy checks Only Sentinel policies can run as policy checks Checks can access cost estimation data but can only use the latest version of Sentinel Warning Policy checks are deprecated and will be permanently removed in August 2025 We recommend that you start using policy evaluations to avoid disruptions Policy evaluations OPA policy sets can only run as policy evaluations and you can enable policy evaluations for Sentinel policy sets by selecting the Enhanced policy set type Policy evaluations run within the HCP Terraform agent terraform cloud docs agents in HCP Terraform s infrastructure For Sentinel policy sets using policy evaluations lets you Enable overrides for soft mandatory and hard mandatory policies letting any user with Manage Policy Overrides permission terraform cloud docs users teams organizations permissions manage policy overrides proceed with a run in the event of policy failure Select a specific Sentinel runtime version for the policy set Policy evaluations cannot access cost estimation data so use policy checks if your policies rely on cost estimates Tip Sentinel runtime version pinning is supported only for Sentinel 0 23 1 and above as well as HCP Terraform agent versions 1 13 1 and above Policy enforcement levels You can set an enforcement level for each policy that determines what happens when a Terraform plan does not pass the policy rule Sentinel and OPA policies have different enforcement levels available Sentinel Sentinel provides three policy enforcement levels advisory Failed policies never interrupt the run They provide information about policy check failures in the UI soft mandatory Failed policies stop the run but any user with Manage Policy Overrides permission terraform cloud docs users teams organizations permissions manage policy overrides can override these failures and allow the run to complete hard mandatory Failed policies stop the run Terraform does not apply runs with failed hard mandatory policies until a user fixes the issue that caused the failure OPA OPA provides two policy enforcement levels advisory Failed policies never interrupt the run They provide information about policy failures in the UI mandatory Failed policies stop the run but any user with Manage Policy Overrides permission terraform cloud docs users teams organizations permissions manage policy overrides can override these failures and allow the run to complete Policy publishing workflows You can create policies and policy sets for your HCP Terraform organization in one of three ways HCP Terraform web UI Add individually managed policies manually in the HCP Terraform UI and store your policy code in HCP Terraform This workflow is ideal for initial experimentation with policy enforcement but we do not recommend it for organizations with large numbers of policies Version control Connect HCP Terraform to a version control repository containing a policy set When you push changes to the repository HCP Terraform automatically uses the updated policy set Automated Push versions of policy sets to HCP Terraform with the HCP Terraform Policy Sets API terraform cloud docs api docs policy sets create a policy set version or the tfe provider tfe policy set https registry terraform io providers hashicorp tfe latest docs resources policy set resource This workflow is ideal for automated Continuous Integration and Deployment CI CD pipelines Manage individual policies in the web UI You can add policies directly to HCP Terraform using the web UI This process requires you to paste completed valid Sentinel or Rego code into the UI We recommend validating your policy code before adding it to HCP Terraform Add managed policies To add an individually managed policy 1 Go to Policies in your organization s settings A list of managed policies in HCP Terraform appears Each policy designates its policy framework Sentinel or OPA and associated policy sets 1 Click Create a new policy 1 Choose the Policy framework you want to use You can only create a policy set from policies written using the same framework You cannot change the framework type after you create the policy 1 Complete the following fields to define the policy Policy Name Add a name containing letters numbers and HCP Terraform displays this name in the UI The name must be unique within your organization Description Describe the policy s purpose The description supports Markdown rendering and HCP Terraform displays this text in the UI Enforcement mode Choose whether this policy can stop Terraform runs and whether users can override it Refer to policy enforcement levels policy enforcement levels for more details OPA Only Query Write a query to identify a specific policy rule within your rego code HCP Terraform uses this query to determine the result of the policy The query is typically a combination of the policy package name and rule name such as terraform deny The result of this query must be an array The policy passes when the array is empty Policy code Paste the code for the policy either Sentinel code or Rego code for OPA policies The UI provides syntax highlighting for the policy language Optional Policy sets Select one or more existing managed policy sets where you want to add the new policy You can only select policy sets compatible with the chosen policy set framework If there are no policy sets available you can create a new one create policy sets The policy is now available in the HCP Terraform UI for you to edit and add to one or more policy sets Edit managed policies To edit a managed policy Go to Policies in your organization s settings Click the policy you want to edit to go to its details page Edit the policy s fields and then click Update policy Delete managed policies Warning Deleting a policy that applies to an active run causes that run s policy evaluation stage to error We recommend warning other members of your organization before you delete widely used policies You can not restore policies after deletion You must manually re add them to HCP Terraform You may want to save the policy code in a separate location before you delete the policy To delete a managed policy Go to Policies in your organization s settings Click the policy you want to delete to go to its details page Click Delete policy and then click Yes delete policy to confirm The policy no longer appears in HCP Terraform and in any associated policy sets Manage policy sets Policy sets are collections of policies that you can apply globally or to specific projects terraform cloud docs projects manage and workspaces To view and manage policy sets go to the Policy Sets section of your organization s settings This page contains all of the policy sets available in the organization including those added through the API The way you set up and configure a new policy set depends on your workflow and where you store policies For managed policies managed policies you use the UI to create a policy set and add managed policies For policy sets in a version control system you use the UI to create a policy set connected to that repository HCP Terraform automatically refreshes the policy set when you change relevant files in that repository Version control policy sets have specific organization and formatting requirements Refer to Sentinel VCS Repositories terraform cloud docs policy enforcement sentinel vcs and OPA VCS Repositories terraform cloud docs policy enforcement opa vcs for details For automated workflows like continuous deployment you can use the UI to create an empty policy set and then use the Policy Sets API terraform cloud docs api docs policy sets to add policies You can also use the API or the tfe provider Sentinel Only https registry terraform io providers hashicorp tfe latest docs resources policy set to add an entire packaged policy set Create policy sets To create a policy set 1 Go to Policy Sets in your organization s settings 1 Click Connect a new policy set 1 Choose your workflow For managed policies click create a policy set with individually managed policies HCP Terraform shows a form to create a policy set and add individually managed policies For version control policies choose a version control provider and then select the repository with your policy set HCP Terraform shows a form to create a policy set connected to that repository For automated workflows click No VCS Connection HCP Terraform shows a form to create an empty policy set You can use the API to add policies to this empty policy set later 1 Choose a Policy framework for the policies you want to add A policy set can only contain policies that use the same framework OPA or Sentinel You cannot change a policy set s framework type after creation 1 Choose a policy set scope Policies enforced globally HCP Terraform automatically enforces this global policy set on all of an organization s existing and future workspaces Policies enforced on selected projects and workspaces Use the text fields to find and select the workspaces and projects to enforce this policy set on This affects all current and future workspaces for any chosen projects 1 Optional Add Policy exclusions for this policy set Specify any workspaces in the policy set s scope that HCP Terraform will not enforce this policy set on 1 Sentinel Only Choose a policy set type Standard This is the default workflow A Sentinel policy set uses a policy check policy checks in HCP Terraform and lets you access cost estimation data Enhanced A Sentinel policy set uses a policy evaluation policy evaluations in HCP Terraform This lets you enable policy overrides and enforce a Sentinel runtime version 1 OPA Only Select a Runtime version for this policy set 1 OPA Only Allow Overrides which enables users with override policy permissions to apply plans that have mandatory policy policy enforcement levels failures 1 VCS Only Optionally specify the VCS branch within your VCS repository where HCP Terraform should import new versions of policies If you do not set this field HCP Terraform uses your selected VCS repository s default branch 1 VCS Only Specify where your policy set files live using the Policies path This lets you maintain multiple policy sets within a single repository Use a relative path from your root directory to the directory that contains either the sentinel hcl Sentinel or policies hcl OPA configuration files If you do not set this field HCP Terraform uses the repository s root directory 1 Managed Policies Only Select managed Policies to add to the policy set You can only add policies written with the same policy framework you selected for this set 1 Choose a descriptive and unique Name for the policy set You can use any combination of letters numbers and 1 Write an optional Description that tells other users about the purpose of the policy set and what it contains Edit policy sets To edit a policy set 1 Go to the Policy Sets section of your organization s settings 1 Click the policy set you want to edit to go to its settings page 1 Adjust the settings and click Update policy set Evaluate a policy runtime upgrade You can validate that changing a policy runtime version does not introduce any breaking changes To perform a policy evaluation 1 Go to the Policy Sets section of your organization s settings 1 Click the policy set you want to upgrade 1 Click the Evaluate tab 1 Select the Runtime version you wish to upgrade to 1 Select a Workspace to test the policy and upgraded version against 1 Click Evaluate HCP Terraform will execute the policy set using the specified version and the latest plan data for the selected workspace It will display the evaluation results If the evaluation returns a Failed status inspect the JSON output to determine whether the issue is related to a non compliant resource or is due to a syntax issue If the evaluation results in an error check that the policy configuration is valid Delete policy sets Warning Deleting a policy set that applies to an active run causes that run s policy evaluation stage to error We recommend warning other members of your organization before you delete widely used policy sets You can not restore policy sets after deletion You must manually re add them to HCP Terraform To delete a policy set 1 Go to Policy Sets in your organization s settings 2 Click the policy set you want to delete to go to its details page 3 Click Delete policy and then click Yes delete policy set to confirm The policy set no longer appears on the UI and HCP Terraform no longer applies it to any workspaces For managed policy sets all of the individual policies are still available in HCP Terraform You must delete each policy individually to remove it from your organization Sentinel only Sentinel parameters Sentinel parameters https docs hashicorp com sentinel language parameters are a list of key value pairs that HCP Terraform sends to the Sentinel runtime when performing policy checks on workspaces If the value parses as JSON HCP Terraform sends it to Sentinel as the corresponding type string boolean integer map or list If the value fails JSON validation HCP Terraform sends it as a string You can set Sentinel parameters when you edit a policy set edit policy sets
terraform Sentinel Policy Set VCS Repositories To enable policy enforcement you must group Sentinel policies into policy sets You can then apply those policy sets globally or to specific projects terraform cloud docs projects manage and workspaces page title Policy Set VCS Repositories Sentinel HCP Terraform Configure a Sentinel policy set version control repository to use in HCP Terraform A policy set repository has a configuration file policy files and module files
--- page_title: Policy Set VCS Repositories - Sentinel - HCP Terraform description: >- Configure a Sentinel policy set version control repository to use in HCP Terraform. A policy set repository has a configuration file, policy files, and module files. --- # Sentinel Policy Set VCS Repositories To enable policy enforcement, you must group Sentinel policies into policy sets. You can then apply those policy sets globally or to specific [projects](/terraform/cloud-docs/projects/manage) and workspaces. <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/policies.mdx' <!-- END: TFC:only name:pnp-callout --> One way to create policy sets is by connecting HCP Terraform to a version control repository. When you push changes to the repository, HCP Terraform automatically uses the updated policy set. Refer to [Managing Policy Sets](/terraform/cloud-docs/policy-enforcement/manage-policy-sets) for more details. A Sentinel policy set repository contains a Sentinel configuration file, policy files, and module files. ## Configuration File Your repository must contain a configuration file named `sentinel.hcl` that defines the following features of the policy set: - Each policy included in the set. The policy name must match the names of individual [policy code files](#policy-code-files) exactly. HCP Terraform ignores policy files in the repository that are not listed in the configuration file. For each policy, the configuration file must designate the policy’s [enforcement level](/terraform/cloud-docs/policy-enforcement/manage-policy-sets#policy-enforcement-levels) and [source](#policy-source). - [Terraform modules](#modules) that policies in the set need to access. The following example shows a portion of a `sentinel.hcl` configuration file that defines a policy named `terraform-maintenance-windows`. The policy has a `hard-mandatory` enforcement level, meaning that it can block Terraform runs when it fails and users cannot override it. ```hcl policy "terraform-maintenance-windows" { source = "./terraform-maintenance-windows.sentinel" enforcement_level = "hard-mandatory" } ``` To configure a module, add a `module` entry to your `sentinel.hcl` file. The following example adds a module called `timezone`. ```hcl module "timezone" { source = "./modules/timezone.sentinel" } ``` The repositories for [policy libraries on the Terraform Registry](https://registry.terraform.io/browse/policies) contain more examples. ## Policy Code Files Define each Sentinel policy in a separate file within your repository. All local policy files must reside in the same directory as the `sentinel.hcl` configuration file and end with the `.sentinel` suffix. ### Policy Source A policy's `source` field can either reference a file within the policy repository, or it can reference a remote source. For example, the configuration could reference a policy from HashiCorp's [foundational policies library](https://github.com/hashicorp/terraform-foundational-policies-library). Sentinel only supports HTTP and HTTPS remote sources. To specify a local source, prefix the `source` with a `./`, or `../`. The following example shows how to reference a local source policy called `terraform-maintenance-windows.sentinel`. ```hcl policy "terraform-maintenance-windows" { source = "./terraform-maintenance-windows.sentinel" enforcement_level = "hard-mandatory" } ``` To specify a remote source, supply the URL as the `source`. The following example references a policy from HashiCorp's foundational policies library. ```hcl policy "deny-public-ssh-nsg-rules" { source = "https://registry.terraform.io/v2/policies/hashicorp/azure-networking-terraform/1.0.2/policy/deny-public-ssh-nsg-rules.sentinel?checksum=sha256:75c95bf1d6eb48153cb31f15c49c237bf7829549beebe20effa07bcdd3f3cb74" enforcement_level = "advisory" } ``` For GitHub, you must use the URL of the raw policy content. Other URL types cause HCP Terraform to error when checking the policy. For example, do not use `https://github.com/hashicorp/policy-library-azure-networking-terraform/blob/main/policies/deny-public-ssh-nsg-rules/deny-public-ssh-nsg-rules.sentinel`. To access the raw URL, open the Sentinel file in your Github repository, right-click **Raw** on the top right of the page, and save the link address. ### Example Policy The following example policy uses the `time` and `tfrun` imports and a custom `timezone` module to do the following tasks: 1. Load the time when the Terraform run occurred 1. Convert the loaded time with the correct offset using the [Timezone API](https://timezoneapi.io/) 1. Verify that the provisioning operation occurs only on a specific day The example policy also uses a [rule expression](https://docs.hashicorp.com/sentinel/language/spec#rule-expressions) with the `when` predicate. If the value of `tfrun.workspace.auto_apply` is false, the rule is not evaluated and returns true. Finally, the example uses parameters to facilitate module reuse within Terraform. Refer to the [Sentinel parameter documentation](https://docs.hashicorp.com/sentinel/language/parameters) for details. ```hcl import "time" import "tfrun" import "timezone" param token default "WbNKULOBheqV" param maintenance_days default ["Friday", "Saturday", "Sunday"] param timezone_id default "America/Los_Angeles" tfrun_created_at = time.load(tfrun.created_at) supported_maintenance_day = rule when tfrun.workspace.auto_apply is true { tfrun_created_at.add(time.hour * timezone.offset(timezone_id, token)).weekday_name in maintenance_days } main = rule { supported_maintenance_day } ``` To expand the policy, you could use the [time.hour](https://docs.hashicorp.com/sentinel/imports/time#time-hour) function to also restrict provisioning to specific times of day. ## Modules HCP Terraform supports [Sentinel modules](https://docs.hashicorp.com/sentinel/extending/modules). Modules let you write reusable policy code that you can import and use within several policies at once. You can store modules locally or retrieve them from a remote HTTP or HTTPS source. -> **Note:** We recommend reviewing [Sentinel runtime's modules documentation](https://docs.hashicorp.com/sentinel/extending/modules) to learn how to use modules within Sentinel. However, the configuration examples in the runtime documentation are relevant to the Sentinel CLI and not HCP Terraform. The following example module loads the code at `./modules/timezone.sentinel` relative to the policy set working directory. Other modules can access this code with the statement `import "timezone"`. ```hcl import "http" import "json" import "decimal" httpGet = func(id, token){ uri = "https://timezoneapi.io/api/timezone/?" + id + "&token=" + token request = http.get(uri) return json.unmarshal(request.body) } offset = func(id, token) { tz = httpGet(id, token) offset = decimal.new(tz.data.datetime.offset_hours).int return offset } ``
terraform
page title Policy Set VCS Repositories Sentinel HCP Terraform description Configure a Sentinel policy set version control repository to use in HCP Terraform A policy set repository has a configuration file policy files and module files Sentinel Policy Set VCS Repositories To enable policy enforcement you must group Sentinel policies into policy sets You can then apply those policy sets globally or to specific projects terraform cloud docs projects manage and workspaces BEGIN TFC only name pnp callout include tfc package callouts policies mdx END TFC only name pnp callout One way to create policy sets is by connecting HCP Terraform to a version control repository When you push changes to the repository HCP Terraform automatically uses the updated policy set Refer to Managing Policy Sets terraform cloud docs policy enforcement manage policy sets for more details A Sentinel policy set repository contains a Sentinel configuration file policy files and module files Configuration File Your repository must contain a configuration file named sentinel hcl that defines the following features of the policy set Each policy included in the set The policy name must match the names of individual policy code files policy code files exactly HCP Terraform ignores policy files in the repository that are not listed in the configuration file For each policy the configuration file must designate the policy s enforcement level terraform cloud docs policy enforcement manage policy sets policy enforcement levels and source policy source Terraform modules modules that policies in the set need to access The following example shows a portion of a sentinel hcl configuration file that defines a policy named terraform maintenance windows The policy has a hard mandatory enforcement level meaning that it can block Terraform runs when it fails and users cannot override it hcl policy terraform maintenance windows source terraform maintenance windows sentinel enforcement level hard mandatory To configure a module add a module entry to your sentinel hcl file The following example adds a module called timezone hcl module timezone source modules timezone sentinel The repositories for policy libraries on the Terraform Registry https registry terraform io browse policies contain more examples Policy Code Files Define each Sentinel policy in a separate file within your repository All local policy files must reside in the same directory as the sentinel hcl configuration file and end with the sentinel suffix Policy Source A policy s source field can either reference a file within the policy repository or it can reference a remote source For example the configuration could reference a policy from HashiCorp s foundational policies library https github com hashicorp terraform foundational policies library Sentinel only supports HTTP and HTTPS remote sources To specify a local source prefix the source with a or The following example shows how to reference a local source policy called terraform maintenance windows sentinel hcl policy terraform maintenance windows source terraform maintenance windows sentinel enforcement level hard mandatory To specify a remote source supply the URL as the source The following example references a policy from HashiCorp s foundational policies library hcl policy deny public ssh nsg rules source https registry terraform io v2 policies hashicorp azure networking terraform 1 0 2 policy deny public ssh nsg rules sentinel checksum sha256 75c95bf1d6eb48153cb31f15c49c237bf7829549beebe20effa07bcdd3f3cb74 enforcement level advisory For GitHub you must use the URL of the raw policy content Other URL types cause HCP Terraform to error when checking the policy For example do not use https github com hashicorp policy library azure networking terraform blob main policies deny public ssh nsg rules deny public ssh nsg rules sentinel To access the raw URL open the Sentinel file in your Github repository right click Raw on the top right of the page and save the link address Example Policy The following example policy uses the time and tfrun imports and a custom timezone module to do the following tasks 1 Load the time when the Terraform run occurred 1 Convert the loaded time with the correct offset using the Timezone API https timezoneapi io 1 Verify that the provisioning operation occurs only on a specific day The example policy also uses a rule expression https docs hashicorp com sentinel language spec rule expressions with the when predicate If the value of tfrun workspace auto apply is false the rule is not evaluated and returns true Finally the example uses parameters to facilitate module reuse within Terraform Refer to the Sentinel parameter documentation https docs hashicorp com sentinel language parameters for details hcl import time import tfrun import timezone param token default WbNKULOBheqV param maintenance days default Friday Saturday Sunday param timezone id default America Los Angeles tfrun created at time load tfrun created at supported maintenance day rule when tfrun workspace auto apply is true tfrun created at add time hour timezone offset timezone id token weekday name in maintenance days main rule supported maintenance day To expand the policy you could use the time hour https docs hashicorp com sentinel imports time time hour function to also restrict provisioning to specific times of day Modules HCP Terraform supports Sentinel modules https docs hashicorp com sentinel extending modules Modules let you write reusable policy code that you can import and use within several policies at once You can store modules locally or retrieve them from a remote HTTP or HTTPS source Note We recommend reviewing Sentinel runtime s modules documentation https docs hashicorp com sentinel extending modules to learn how to use modules within Sentinel However the configuration examples in the runtime documentation are relevant to the Sentinel CLI and not HCP Terraform The following example module loads the code at modules timezone sentinel relative to the policy set working directory Other modules can access this code with the statement import timezone hcl import http import json import decimal httpGet func id token uri https timezoneapi io api timezone id token token request http get uri return json unmarshal request body offset func id token tz httpGet id token offset decimal new tz data datetime offset hours int return offset
terraform page title tfstate v2 Imports Sentinel HCP Terraform Sentinel import designed specifically for Terraform 0 12 This import requires Terraform 0 12 or higher and must currently be loaded by path using an alias The tfstate v2 import provides access to a Terraform state Note This is documentation for the next version of the tfstate example import tfstate v2 as tfstate
--- page_title: tfstate/v2 - Imports - Sentinel - HCP Terraform description: The tfstate/v2 import provides access to a Terraform state. --- -> **Note:** This is documentation for the next version of the `tfstate` Sentinel import, designed specifically for Terraform 0.12. This import requires Terraform 0.12 or higher, and must currently be loaded by path, using an alias, example: `import "tfstate/v2" as tfstate`. # Import: tfstate/v2 The `tfstate/v2` import provides access to a Terraform state. <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/policies.mdx' <!-- END: TFC:only name:pnp-callout --> The _state_ is the data that Terraform has recorded about a workspace at a particular point in its lifecycle, usually after an apply. You can read more general information about how Terraform uses state [here](/terraform/language/state). -> **NOTE:** Since HCP Terraform currently only supports policy checks at plan time, the usefulness of this import is somewhat limited, as it will usually give you the state _prior_ to the plan the policy check is currently being run for. Depending on your needs, you may find the [`planned_values`](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfplan-v2#the-planned_values-collection) collection in `tfplan/v2` more useful, which will give you a _predicted_ state by applying plan data to the data found here. The one exception to this rule is _data sources_, which will always give up to date data here, as long as the data source could be evaluated at plan time. The data in the `tfstate/v2` import is sourced from the JSON configuration file that is generated by the [`terraform show -json`](/terraform/cli/commands/show#json-output) command. For more information on the file format, see the [JSON Output Format](/terraform/internals/json-format) page. ## Import Overview The `tfstate/v2` import is structured as currently two _collections_, keyed in resource address and output name, respectively. ``` (tfstate/v2) ├── terraform_version (string) ├── resources │ └── (indexed by address) │ ├── address (string) │ ├── module_address (string) │ ├── mode (string) │ ├── type (string) │ ├── name (string) │ ├── index (float (number) or string) │ ├── provider_name (string) │ ├── values (map) │ ├── depends_on (list of strings) │ ├── tainted (boolean) │ └── deposed_key (string) └── outputs └── (indexed by name) ├── name (string) ├── sensitive (boolean) └── value (value) ``` The collections are: * [`resources`](#the-resources-collection) - The state of all resources across all modules in the state. * [`outputs`](#the-outputs-collection) - The state of all outputs from the root module in the state. These collections are specifically designed to be used with the [`filter`](https://docs.hashicorp.com/sentinel/language/collection-operations#filter-expression) quantifier expression in Sentinel, so that one can collect a list of resources to perform policy checks on without having to write complex module traversal. As an example, the following code will return all `aws_instance` resource types within the state, regardless of what module they are in: ``` all_aws_instances = filter tfstate.resources as _, r { r.mode is "managed" and r.type is "aws_instance" } ``` You can add specific attributes to the filter to narrow the search, such as the module address. The following code would return resources in a module named `foo` only: ``` all_aws_instances = filter tfstate.resources as _, r { r.module_address is "module.foo" and r.mode is "managed" and r.type is "aws_instance" } ``` ## The `terraform_version` Value The top-level `terraform_version` value in this import gives the Terraform version that recorded the state. This can be used to do version validation. ``` import "tfstate/v2" as tfstate import "strings" v = strings.split(tfstate.terraform_version, ".") version_major = int(v[1]) version_minor = int(v[2]) main = rule { version_major is 12 and version_minor >= 19 } ``` -> **NOTE:** The above example will give errors when working with pre-release versions (example: `0.12.0beta1`). Future versions of this import will include helpers to assist with processing versions that will account for these kinds of exceptions. ## The `resources` Collection The `resources` collection is a collection representing all of the resources in the state, across all modules. This collection is indexed on the complete resource address as the key. An element in the collection has the following values: * `address` - The absolute resource address - also the key for the collection's index. * `module_address` - The address portion of the absolute resource address. * `mode` - The resource mode, either `managed` (resources) or `data` (data sources). * `type` - The resource type, example: `aws_instance` for `aws_instance.foo`. * `name` - The resource name, example: `foo` for `aws_instance.foo`. * `index` - The resource index. Can be either a number or a string. * `provider_name` - The name of the provider this resource belongs to. This allows the provider to be interpreted unambiguously in the unusual situation where a provider offers a resource type whose name does not start with its own name, such as the `googlebeta` provider offering `google_compute_instance`. -> **Note:** Starting with Terraform 0.13, the `provider_name` field contains the _full_ source address to the provider in the Terraform Registry. Example: `registry.terraform.io/hashicorp/null` for the null provider. * `values` - An object (map) representation of the attribute values of the resource, whose structure depends on the resource type schema. When accessing proposed state through the [`planned_values`](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfplan-v2#the-planned_values-collection) collection of the tfplan/v2 import, unknown values will be omitted. * `depends_on` - The addresses of the resources that this resource depends on. * `tainted` - `true` if the resource has been explicitly marked as [tainted](/terraform/cli/commands/taint) in the state. * `deposed_key` - Set if the resource has been marked deposed and will be destroyed on the next apply. This matches the deposed field in the [`resource_changes`](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfplan-v2#the-resource_changes-collection) collection in the [`tfplan/v2`](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfplan-v2) import. ## The `outputs` Collection The `outputs` collection is a collection of outputs from the root module of the state. Note that no child modules are included in this output set, and there is no way to fetch child module output values. This is to encourage the correct flow of outputs to the recommended root consumption level. The collection is indexed on the output name, with the following fields: * `name`: The name of the output, also the collection key. * `sensitive`: Whether or not the value was marked as [sensitive](/terraform/language/values/outputs#sensitive-suppressing-values-in-cli-output) in configuration. * `value`: The value of the output.
terraform
page title tfstate v2 Imports Sentinel HCP Terraform description The tfstate v2 import provides access to a Terraform state Note This is documentation for the next version of the tfstate Sentinel import designed specifically for Terraform 0 12 This import requires Terraform 0 12 or higher and must currently be loaded by path using an alias example import tfstate v2 as tfstate Import tfstate v2 The tfstate v2 import provides access to a Terraform state BEGIN TFC only name pnp callout include tfc package callouts policies mdx END TFC only name pnp callout The state is the data that Terraform has recorded about a workspace at a particular point in its lifecycle usually after an apply You can read more general information about how Terraform uses state here terraform language state NOTE Since HCP Terraform currently only supports policy checks at plan time the usefulness of this import is somewhat limited as it will usually give you the state prior to the plan the policy check is currently being run for Depending on your needs you may find the planned values terraform cloud docs policy enforcement sentinel import tfplan v2 the planned values collection collection in tfplan v2 more useful which will give you a predicted state by applying plan data to the data found here The one exception to this rule is data sources which will always give up to date data here as long as the data source could be evaluated at plan time The data in the tfstate v2 import is sourced from the JSON configuration file that is generated by the terraform show json terraform cli commands show json output command For more information on the file format see the JSON Output Format terraform internals json format page Import Overview The tfstate v2 import is structured as currently two collections keyed in resource address and output name respectively tfstate v2 terraform version string resources indexed by address address string module address string mode string type string name string index float number or string provider name string values map depends on list of strings tainted boolean deposed key string outputs indexed by name name string sensitive boolean value value The collections are resources the resources collection The state of all resources across all modules in the state outputs the outputs collection The state of all outputs from the root module in the state These collections are specifically designed to be used with the filter https docs hashicorp com sentinel language collection operations filter expression quantifier expression in Sentinel so that one can collect a list of resources to perform policy checks on without having to write complex module traversal As an example the following code will return all aws instance resource types within the state regardless of what module they are in all aws instances filter tfstate resources as r r mode is managed and r type is aws instance You can add specific attributes to the filter to narrow the search such as the module address The following code would return resources in a module named foo only all aws instances filter tfstate resources as r r module address is module foo and r mode is managed and r type is aws instance The terraform version Value The top level terraform version value in this import gives the Terraform version that recorded the state This can be used to do version validation import tfstate v2 as tfstate import strings v strings split tfstate terraform version version major int v 1 version minor int v 2 main rule version major is 12 and version minor 19 NOTE The above example will give errors when working with pre release versions example 0 12 0beta1 Future versions of this import will include helpers to assist with processing versions that will account for these kinds of exceptions The resources Collection The resources collection is a collection representing all of the resources in the state across all modules This collection is indexed on the complete resource address as the key An element in the collection has the following values address The absolute resource address also the key for the collection s index module address The address portion of the absolute resource address mode The resource mode either managed resources or data data sources type The resource type example aws instance for aws instance foo name The resource name example foo for aws instance foo index The resource index Can be either a number or a string provider name The name of the provider this resource belongs to This allows the provider to be interpreted unambiguously in the unusual situation where a provider offers a resource type whose name does not start with its own name such as the googlebeta provider offering google compute instance Note Starting with Terraform 0 13 the provider name field contains the full source address to the provider in the Terraform Registry Example registry terraform io hashicorp null for the null provider values An object map representation of the attribute values of the resource whose structure depends on the resource type schema When accessing proposed state through the planned values terraform cloud docs policy enforcement sentinel import tfplan v2 the planned values collection collection of the tfplan v2 import unknown values will be omitted depends on The addresses of the resources that this resource depends on tainted true if the resource has been explicitly marked as tainted terraform cli commands taint in the state deposed key Set if the resource has been marked deposed and will be destroyed on the next apply This matches the deposed field in the resource changes terraform cloud docs policy enforcement sentinel import tfplan v2 the resource changes collection collection in the tfplan v2 terraform cloud docs policy enforcement sentinel import tfplan v2 import The outputs Collection The outputs collection is a collection of outputs from the root module of the state Note that no child modules are included in this output set and there is no way to fetch child module output values This is to encourage the correct flow of outputs to the recommended root consumption level The collection is indexed on the output name with the following fields name The name of the output also the collection key sensitive Whether or not the value was marked as sensitive terraform language values outputs sensitive suppressing values in cli output in configuration value The value of the output
terraform The tfrun import provides access to data associated with a Terraform run The tfrun import provides access to data associated with a Terraform run run glossary BEGIN TFC only name pnp callout page title tfrun Imports Sentinel HCP Terraform Import tfrun
--- page_title: tfrun - Imports - Sentinel - HCP Terraform description: The `tfrun` import provides access to data associated with a Terraform run. --- # Import: tfrun The `tfrun` import provides access to data associated with a [Terraform run][run-glossary]. <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/policies.mdx' <!-- END: TFC:only name:pnp-callout --> This import currently consists of run attributes, as well as namespaces for the `organization`, `workspace` and `cost-estimate`. Each namespace provides static data regarding the HCP Terraform application that can then be consumed by Sentinel during a policy evaluation. ``` tfrun ├── 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) | ├── tag_bindings (array of objects) │ ├── working_directory (string) │ └── vcs_repo (map of keys) └── cost_estimate ├── prior_monthly_cost (string) ├── proposed_monthly_cost (string) └── delta_monthly_cost (string) ``` -> **Note:** When writing policies using this import, keep in mind that workspace data is generally editable by users outside of the context of policy enforcement. For example, consider the case of omitting the enforcement of policy rules for development workspaces by the workspace name (allowing the policy to pass if the workspace ends in `-dev`). While this is useful for extremely granular exceptions, the workspace name could be edited by workspace admins, effectively bypassing the policy. In this case, where an extremely strict separation of policy managers vs. workspace practitioners is required, using [policy sets](/terraform/cloud-docs/policy-enforcement/manage-policy-sets) to only enforce the policy on non-development workspaces is more appropriate. [run-glossary]: /terraform/docs/glossary#run [workspace-glossary]: /terraform/docs/glossary#workspace ## Namespace: root The **root namespace** contains data associated with the current run. ### Value: `id` * **Value Type:** String. Specifies the ID that is associated with the current Terraform run. ### Value: `created_at` * **Value Type:** String. The `created_at` value within the [root namespace](#namespace-root) specifies the time that the run was created. The timestamp returned follows the format outlined in [RFC3339](https://datatracker.ietf.org/doc/html/rfc3339). Users can use the `time` import to [load](https://docs.hashicorp.com/sentinel/imports/time#time-load-timeish) a run timestamp and create a new timespace from the specified value. See the `time` import [documentation](https://docs.hashicorp.com/sentinel/imports/time#import-time) for available actions that can be performed on timespaces. ### Value: `created_by` * **Value Type:** String. The `created_by` value within the [root namespace](#namespace-root) is string that specifies the user name of the HCP Terraform user for the specific run. ### Value: `message` * **Value Type:** String. Specifies the message that is associated with the Terraform run. The default value is _"Queued manually via the Terraform Enterprise API"_. ### Value: `commit_sha` * **Value Type:** String. Specifies the checksum hash (SHA) that identifies the commit. ### Value: `is_destroy` * **Value Type:** Boolean. Specifies if the plan is a destroy plan, which will destroy all provisioned resources. ### Value: `refresh` * **Value Type:** Boolean. Specifies whether the state was refreshed prior to the plan. ### Value: `refresh_only` * **Value Type:** Boolean. Specifies whether the plan is in refresh-only mode, which ignores configuration changes and updates state with any changes made outside of Terraform. ### Value: `replace_addrs` * **Value Type:** An array of strings representing [resource addresses](/terraform/cli/state/resource-addressing). Provides the targets specified using the [`-replace`](/terraform/cli/commands/plan#resource-targeting) flag in the CLI or the `replace-addrs` attribute in the API. Will be null if no resource targets are specified. ### Value: `speculative` * **Value Type:** Boolean. Specifies whether the plan associated with the run is a [speculative plan](/terraform/cloud-docs/run/remote-operations#speculative-plans) only. ### Value: `target_addrs` * **Value Type:** An array of strings representing [resource addresses](/terraform/cli/state/resource-addressing). Provides the targets specified using the [`-target`](/terraform/cli/commands/plan#resource-targeting) flag in the CLI or the `target-addrs` attribute in the API. Will be null if no resource targets are specified. To prohibit targeted runs altogether, make sure the `target_addrs` value is null or empty: ``` import "tfrun" main = tfrun.target_addrs is null or tfrun.target_addrs is empty ``` ### Value: `variables` * **Value Type:** A string-keyed map of values. Provides the names of the variables that are configured within the run and the [sensitivity](/terraform/cloud-docs/workspaces/variables/managing-variables#sensitive-values) state of the value. ``` variables (map of keys) └── name (string) └── category (string) └── sensitive (boolean) ``` ## Namespace: project The **project namespace** contains data associated with the current run's [projects](/terraform/cloud-docs/api-docs/projects). ### Value: `id` * **Value Type:** String. Specifies the ID that is associated with the current project. ### Value: `name` * **Value Type:** String. Specifies the name assigned to the HCP Terraform project. ## Namespace: organization The **organization namespace** contains data associated with the current run's HCP Terraform [organization](/terraform/cloud-docs/users-teams-organizations/organizations). ### Value: `name` * **Value Type:** String. Specifies the name assigned to the HCP Terraform organization. ## Namespace: workspace The **workspace namespace** contains data associated with the current run's workspace. ### Value: `id` * **Value Type:** String. Specifies the ID that is associated with the Terraform workspace. ### Value: `name` * **Value Type:** String. The name of the workspace, which can only include letters, numbers, `-`, and `_`. As an example, in a workspace named `app-us-east-dev` the following policy would evaluate to `true`: ``` # Enforces production rules on all non-development workspaces import "tfrun" import "strings" # (Actual policy logic omitted) evaluate_production_policy = rule { ... } main = rule when strings.has_suffix(tfrun.workspace.name, "-dev") is false { evaluate_production_policy } ``` ### Value: `created_at` * **Value Type:** String. Specifies the time that the workspace was created. The timestamp returned follows the format outlined in [RFC3339](https://datatracker.ietf.org/doc/html/rfc3339). Users can use the `time` import to [load](https://docs.hashicorp.com/sentinel/imports/time#time-load-timeish) a workspace timestamp, and create a new timespace from the specified value. See the `time` import [documentation](https://docs.hashicorp.com/sentinel/imports/time#import-time) for available actions that can be performed on timespaces. ### Value: `description` * **Value Type:** String. Contains the description for the workspace. This value can be `null`. ### Value: `auto_apply` * **Value Type:** Boolean. Contains the workspace's [auto-apply](/terraform/cloud-docs/workspaces/settings#auto-apply-and-manual-apply) setting. ### Value: `tags` * **Value Type:** Array of strings. Contains the list of tag names for the workspace, as well as the keys from tag bindings. ### Value: `tag_bindings` * **Value Type:** Array of objects. Contains the complete list of tag bindings for the workspace, which includes inherited tag bindings, as well as the workspace key-only tags. Each binding has a string `key`, a nullable string `value`, as well as a boolean `inherited` properties. ``` tag_bindings (array of objects) ├── key (string) ├── value (string or null) └── inherited (boolean) ``` ### Value: `working_directory` * **Value Type:** String. Contains the configured [Terraform working directory](/terraform/cloud-docs/workspaces/settings#terraform-working-directory) of the workspace. This value can be `null`. ### Value: `execution_mode` * **Value Type:** String. Contains the configured [Terraform execution mode](/terraform/cloud-docs/workspaces/settings#execution-mode) of the workspace. The default value is `remote`. ### Value: `vcs_repo` * **Value Type:** A string-keyed map of values. Contains data associated with a VCS repository connected to the workspace. Details regarding each attribute can be found in the documentation for the HCP Terraform [Workspaces API](/terraform/cloud-docs/api-docs/workspaces). This value can be `null`. ``` vcs_repo (map of keys) ├── identifier (string) ├── display_identifier (string) ├── branch (string) └── ingress_submodules (bool) ``` ## Namespace: cost_estimate The **cost_estimation namespace** contains data associated with the current run's cost estimate. This namespace is only present if a cost estimate is available. -> Cost estimation is disabled for runs using [resource targeting](/terraform/cli/commands/plan#resource-targeting), which may cause unexpected failures. -> **Note:** Cost estimates are not available for Terraform 0.11. ### Value: `prior_monthly_cost` * **Value Type:** String. Contains the monthly cost estimate at the beginning of a plan. This value contains a positive decimal and can be `"0.0"`. ### Value: `proposed_monthly_cost` * **Value Type:** String. Contains the monthly cost estimate if the plan were to be applied. This value contains a positive decimal and can be `"0.0"`. ### Value: `delta_monthly_cost` * **Value Type:** String. Contains the difference between the prior and proposed monthly cost estimates. This value may contain a positive or negative decimal and can be `"0.0"`.
terraform
page title tfrun Imports Sentinel HCP Terraform description The tfrun import provides access to data associated with a Terraform run Import tfrun The tfrun import provides access to data associated with a Terraform run run glossary BEGIN TFC only name pnp callout include tfc package callouts policies mdx END TFC only name pnp callout This import currently consists of run attributes as well as namespaces for the organization workspace and cost estimate Each namespace provides static data regarding the HCP Terraform application that can then be consumed by Sentinel during a policy evaluation tfrun 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 tag bindings array of objects working directory string vcs repo map of keys cost estimate prior monthly cost string proposed monthly cost string delta monthly cost string Note When writing policies using this import keep in mind that workspace data is generally editable by users outside of the context of policy enforcement For example consider the case of omitting the enforcement of policy rules for development workspaces by the workspace name allowing the policy to pass if the workspace ends in dev While this is useful for extremely granular exceptions the workspace name could be edited by workspace admins effectively bypassing the policy In this case where an extremely strict separation of policy managers vs workspace practitioners is required using policy sets terraform cloud docs policy enforcement manage policy sets to only enforce the policy on non development workspaces is more appropriate run glossary terraform docs glossary run workspace glossary terraform docs glossary workspace Namespace root The root namespace contains data associated with the current run Value id Value Type String Specifies the ID that is associated with the current Terraform run Value created at Value Type String The created at value within the root namespace namespace root specifies the time that the run was created The timestamp returned follows the format outlined in RFC3339 https datatracker ietf org doc html rfc3339 Users can use the time import to load https docs hashicorp com sentinel imports time time load timeish a run timestamp and create a new timespace from the specified value See the time import documentation https docs hashicorp com sentinel imports time import time for available actions that can be performed on timespaces Value created by Value Type String The created by value within the root namespace namespace root is string that specifies the user name of the HCP Terraform user for the specific run Value message Value Type String Specifies the message that is associated with the Terraform run The default value is Queued manually via the Terraform Enterprise API Value commit sha Value Type String Specifies the checksum hash SHA that identifies the commit Value is destroy Value Type Boolean Specifies if the plan is a destroy plan which will destroy all provisioned resources Value refresh Value Type Boolean Specifies whether the state was refreshed prior to the plan Value refresh only Value Type Boolean Specifies whether the plan is in refresh only mode which ignores configuration changes and updates state with any changes made outside of Terraform Value replace addrs Value Type An array of strings representing resource addresses terraform cli state resource addressing Provides the targets specified using the replace terraform cli commands plan resource targeting flag in the CLI or the replace addrs attribute in the API Will be null if no resource targets are specified Value speculative Value Type Boolean Specifies whether the plan associated with the run is a speculative plan terraform cloud docs run remote operations speculative plans only Value target addrs Value Type An array of strings representing resource addresses terraform cli state resource addressing Provides the targets specified using the target terraform cli commands plan resource targeting flag in the CLI or the target addrs attribute in the API Will be null if no resource targets are specified To prohibit targeted runs altogether make sure the target addrs value is null or empty import tfrun main tfrun target addrs is null or tfrun target addrs is empty Value variables Value Type A string keyed map of values Provides the names of the variables that are configured within the run and the sensitivity terraform cloud docs workspaces variables managing variables sensitive values state of the value variables map of keys name string category string sensitive boolean Namespace project The project namespace contains data associated with the current run s projects terraform cloud docs api docs projects Value id Value Type String Specifies the ID that is associated with the current project Value name Value Type String Specifies the name assigned to the HCP Terraform project Namespace organization The organization namespace contains data associated with the current run s HCP Terraform organization terraform cloud docs users teams organizations organizations Value name Value Type String Specifies the name assigned to the HCP Terraform organization Namespace workspace The workspace namespace contains data associated with the current run s workspace Value id Value Type String Specifies the ID that is associated with the Terraform workspace Value name Value Type String The name of the workspace which can only include letters numbers and As an example in a workspace named app us east dev the following policy would evaluate to true Enforces production rules on all non development workspaces import tfrun import strings Actual policy logic omitted evaluate production policy rule main rule when strings has suffix tfrun workspace name dev is false evaluate production policy Value created at Value Type String Specifies the time that the workspace was created The timestamp returned follows the format outlined in RFC3339 https datatracker ietf org doc html rfc3339 Users can use the time import to load https docs hashicorp com sentinel imports time time load timeish a workspace timestamp and create a new timespace from the specified value See the time import documentation https docs hashicorp com sentinel imports time import time for available actions that can be performed on timespaces Value description Value Type String Contains the description for the workspace This value can be null Value auto apply Value Type Boolean Contains the workspace s auto apply terraform cloud docs workspaces settings auto apply and manual apply setting Value tags Value Type Array of strings Contains the list of tag names for the workspace as well as the keys from tag bindings Value tag bindings Value Type Array of objects Contains the complete list of tag bindings for the workspace which includes inherited tag bindings as well as the workspace key only tags Each binding has a string key a nullable string value as well as a boolean inherited properties tag bindings array of objects key string value string or null inherited boolean Value working directory Value Type String Contains the configured Terraform working directory terraform cloud docs workspaces settings terraform working directory of the workspace This value can be null Value execution mode Value Type String Contains the configured Terraform execution mode terraform cloud docs workspaces settings execution mode of the workspace The default value is remote Value vcs repo Value Type A string keyed map of values Contains data associated with a VCS repository connected to the workspace Details regarding each attribute can be found in the documentation for the HCP Terraform Workspaces API terraform cloud docs api docs workspaces This value can be null vcs repo map of keys identifier string display identifier string branch string ingress submodules bool Namespace cost estimate The cost estimation namespace contains data associated with the current run s cost estimate This namespace is only present if a cost estimate is available Cost estimation is disabled for runs using resource targeting terraform cli commands plan resource targeting which may cause unexpected failures Note Cost estimates are not available for Terraform 0 11 Value prior monthly cost Value Type String Contains the monthly cost estimate at the beginning of a plan This value contains a positive decimal and can be 0 0 Value proposed monthly cost Value Type String Contains the monthly cost estimate if the plan were to be applied This value contains a positive decimal and can be 0 0 Value delta monthly cost Value Type String Contains the difference between the prior and proposed monthly cost estimates This value may contain a positive or negative decimal and can be 0 0
terraform Warning The tfconfig import is now deprecated and will be permanently removed in August 2025 We recommend that you start using the updated tfconfig v2 terraform cloud docs policy enforcement sentinel import tfconfig v2 import as soon as possible to avoid disruptions Import tfconfig The tfconfig v2 import offers improved functionality and is designed to better support your policy enforcement needs page title tfconfig Imports Sentinel HCP Terraform The tfconfig import provides access to a Terraform configuration
--- page_title: tfconfig - Imports - Sentinel - HCP Terraform description: The tfconfig import provides access to a Terraform configuration. --- # Import: tfconfig ~> **Warning:** The `tfconfig` import is now deprecated and will be permanently removed in August 2025. We recommend that you start using the updated [tfconfig/v2](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfconfig-v2) import as soon as possible to avoid disruptions. The `tfconfig/v2` import offers improved functionality and is designed to better support your policy enforcement needs. The `tfconfig` import provides access to a Terraform configuration. The Terraform configuration is the set of `*.tf` files that are used to describe the desired infrastructure state. Policies using the `tfconfig` import can access all aspects of the configuration: providers, resources, data sources, modules, and variables. <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/policies.mdx' <!-- END: TFC:only name:pnp-callout --> Some use cases for `tfconfig` include: * **Organizational naming conventions**: requiring that configuration elements are named in a way that conforms to some organization-wide standard. * **Required inputs and outputs**: organizations may require a particular set of input variable names across all workspaces or may require a particular set of outputs for asset management purposes. * **Enforcing particular modules**: organizations may provide a number of "building block" modules and require that each workspace be built only from combinations of these modules. * **Enforcing particular providers or resources**: an organization may wish to require or prevent the use of providers and/or resources so that configuration authors cannot use alternative approaches to work around policy restrictions. Note with these use cases that this import is concerned with object _names_ in the configuration. Since this is the configuration and not an invocation of Terraform, you can't see values for variables, the state, or the diff for a pending plan. If you want to write policy around expressions used within configuration blocks, you likely want to use the [`tfplan`](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfplan) import. ## Namespace Overview The following is a tree view of the import namespace. For more detail on a particular part of the namespace, see below. -> **Note:** The root-level alias keys shown here (`data`, `modules`, `providers`, `resources`, and `variables`) are shortcuts to a [module namespace](#namespace-module) scoped to the root module. For more details, see the section on [root namespace aliases](#root-namespace-aliases). ``` tfconfig ├── module() (function) │ └── (module namespace) │ ├── data │ │ └── TYPE.NAME │ │ ├── config (map of keys) │ │ ├── references (map of keys) (TF 0.12 and later) │ │ └── provisioners │ │ └── NUMBER │ │ ├── config (map of keys) │ │ ├── references (map of keys) (TF 0.12 and later) │ │ └── type (string) │ ├── modules │ │ └── NAME │ │ ├── config (map of keys) │ │ ├── references (map of keys) (TF 0.12 and later) │ │ ├── source (string) │ │ └── version (string) │ ├──outputs │ │ └── NAME │ │ ├── depends_on (list of strings) │ │ ├── description (string) │ │ ├── sensitive (boolean) │ │ ├── references (list of strings) (TF 0.12 and later) │ │ └── value (value) │ ├── providers │ │ └── TYPE │ │ ├── alias │ │ │ └── ALIAS │ │ │ ├── config (map of keys) │ │ | ├── references (map of keys) (TF 0.12 and later) │ │ │ └── version (string) │ │ ├── config (map of keys) │ │ ├── references (map of keys) (TF 0.12 and later) │ │ └── version (string) │ ├── resources │ │ └── TYPE.NAME │ │ ├── config (map of keys) │ │ ├── references (map of keys) (TF 0.12 and later) │ │ └── provisioners │ │ └── NUMBER │ │ ├── config (map of keys) │ │ ├── references (map of keys) (TF 0.12 and later) │ │ └── type (string) │ └── variables │ └── NAME │ ├── default (value) │ └── description (string) ├── module_paths ([][]string) │ ├── data (root module alias) ├── modules (root module alias) ├── outputs (root module alias) ├── providers (root module alias) ├── resources (root module alias) └── variables (root module alias) ``` ### `references` with Terraform 0.12 **With Terraform 0.11 or earlier**, if a configuration value is defined as an expression (and not a static value), the value will be accessible in its raw, non-interpolated string (just as with a constant value). As an example, consider the following resource block: ```hcl resource "local_file" "accounts" { content = "some text" filename = "${var.subdomain}.${var.domain}/accounts.txt" } ``` In this example, one might want to ensure `domain` and `subdomain` input variables are used within `filename` in this configuration. With Terraform 0.11 or earlier, the following policy would evaluate to `true`: ```python import "tfconfig" # filename_value is the raw, non-interpolated string filename_value = tfconfig.resources.local_file.accounts.config.filename main = rule { filename_value contains "${var.domain}" and filename_value contains "${var.subdomain}" } ``` **With Terraform 0.12 or later**, any non-static values (such as interpolated strings) are not present within the configuration value and `references` should be used instead: ```python import "tfconfig" # filename_references is a list of string values containing the references used in the expression filename_references = tfconfig.resources.local_file.accounts.references.filename main = rule { filename_references contains "var.domain" and filename_references contains "var.subdomain" } ``` The `references` value is present in any namespace where non-constant configuration values can be expressed. This is essentially every namespace which has a `config` value as well as the `outputs` namespace. -> **Note:** Remember, this import enforces policy around the literal Terraform configuration and not the final values as a result of invoking Terraform. If you want to write policy around the _result_ of expressions used within configuration blocks (for example, if you wanted to ensure the final value of `filename` above includes `accounts.txt`), you likely want to use the [`tfplan`](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfplan) import. ## Namespace: Root The root-level namespace consists of the values and functions documented below. In addition to this, the root-level `data`, `modules`, `providers`, `resources`, and `variables` keys all alias to their corresponding namespaces within the [module namespace](#namespace-module). <a id="root-function-module" /> ### Function: `module()` ``` module = func(ADDR) ``` * **Return Type:** A [module namespace](#namespace-module). The `module()` function in the [root namespace](#namespace-root) returns the [module namespace](#namespace-module) for a particular module address. The address must be a list and is the module address, split on the period (`.`), excluding the root module. Hence, a module with an address of simply `foo` (or `root.foo`) would be `["foo"]`, and a module within that (so address `foo.bar`) would be read as `["foo", "bar"]`. [`null`][ref-null] is returned if a module address is invalid, or if the module is not present in the configuration. [ref-null]: https://docs.hashicorp.com/sentinel/language/spec#null As an example, given the following module block: ```hcl module "foo" { # ... } ``` If the module contained the following content: ```hcl resource "null_resource" "foo" { triggers = { foo = "bar" } } ``` The following policy would evaluate to `true`: ```python import "tfconfig" main = rule { subject.module(["foo"]).resources.null_resource.foo.config.triggers[0].foo is "bar" } ``` <a id="root-value-module_paths" /> ### Value: `module_paths` * **Value Type:** List of a list of strings. The `module_paths` value within the [root namespace](#namespace-root) is a list of all of the modules within the Terraform configuration. Modules not present in the configuration will not be present here, even if they are present in the diff or state. This data is represented as a list of a list of strings, with the inner list being the module address, split on the period (`.`). The root module is included in this list, represented as an empty inner list. As an example, if the following module block was present within a Terraform configuration: ```hcl module "foo" { # ... } ``` The value of `module_paths` would be: ``` [ [], ["foo"], ] ``` And the following policy would evaluate to `true`: ```python import "tfconfig" main = rule { tfconfig.module_paths contains ["foo"] } ``` #### Iterating Through Modules Iterating through all modules to find particular resources can be useful. This [example][iterate-over-modules] shows how to use `module_paths` with the [`module()` function](#function-module-) to find all resources of a particular type from all modules using the `tfplan` import. By changing `tfplan` in this function to `tfconfig`, you could make a similar function find all resources of a specific type in the Terraform configuration. [iterate-over-modules]: /terraform/cloud-docs/policy-enforcement/sentinel#sentinel-imports ## Namespace: Module The **module namespace** can be loaded by calling [`module()`](#root-function-module) for a particular module. It can be used to load the following child namespaces: * `data` - Loads the [resource namespace](#namespace-resources-data-sources), filtered against data sources. * `modules` - Loads the [module configuration namespace](#namespace-module-configuration). * `outputs` - Loads the [output namespace](#namespace-outputs). * `providers` - Loads the [provider namespace](#namespace-providers). * `resources` - Loads the [resource namespace](#namespace-resources-data-sources), filtered against resources. * `variables` - Loads the [variable namespace](#namespace-variables). ### Root Namespace Aliases The root-level `data`, `modules`, `providers`, `resources`, and `variables` keys all alias to their corresponding namespaces within the module namespace, loaded for the root module. They are the equivalent of running `module([]).KEY`. <a id="namespace-resources"></a> ## Namespace: Resources/Data Sources The **resource namespace** is a namespace _type_ that applies to both resources (accessed by using the `resources` namespace key) and data sources (accessed using the `data` namespace key). Accessing an individual resource or data source within each respective namespace can be accomplished by specifying the type and name, in the syntax `[resources|data].TYPE.NAME`. In addition, each of these namespace levels is a map, allowing you to filter based on type and name. Some examples of multi-level access are below: * To fetch all `aws_instance` resources within the root module, you can specify `tfconfig.resources.aws_instance`. This would give you a map of resource namespaces indexed from the names of each resource (`foo`, `bar`, and so on). * To fetch all resources within the root module, irrespective of type, use `tfconfig.resources`. This is indexed by type, as shown above with `tfconfig.resources.aws_instance`, with names being the next level down. As an example, perhaps you wish to deny use of the `local_file` resource in your configuration. Consider the following resource block: ```hcl resource "local_file" "foo" { content = "foo!" filename = "${path.module}/foo.bar" } ``` The following policy would fail: ```python import "tfconfig" main = rule { tfconfig.resources not contains "local_file" } ``` Further explanation of the namespace will be in the context of resources. As mentioned, when operating on data sources, use the same syntax, except with `data` in place of `resources`. <a id="resources-value-config" /> ### Value: `config` * **Value Type:** A string-keyed map of values. The `config` value within the [resource namespace](#namespace-resources-data-sources) is a map of key-value pairs that directly map to Terraform config keys and values. -> **With Terraform 0.11 or earlier**, if the config value is defined as an expression (and not a static value), the value will be in its raw, non-interpolated string. **With Terraform 0.12 or later**, any non-static values (such as interpolated strings) are not present and [`references`](#resources-value-references) should be used instead. As an example, consider the following resource block: ```hcl resource "local_file" "accounts" { content = "some text" filename = "accounts.txt" } ``` In this example, one might want to access `filename` to validate that the correct file name is used. Given the above example, the following policy would evaluate to `true`: ```python import "tfconfig" main = rule { tfconfig.resources.local_file.accounts.config.filename is "accounts.txt" } ``` <a id="resources-value-references" /> ### Value: `references` * **Value Type:** A string-keyed map of list values containing strings. -> **Note:** This value is only present when using Terraform 0.12 or later. The `references` value within the [resource namespace](#namespace-resources-data-sources) contains the identifiers within non-constant expressions found in [`config`](#resources-value-config). See the [documentation on `references`](#references-with-terraform-0-12) for more information. <a id="resources-value-provisioners" /> ### Value: `provisioners` * **Value Type:** List of [provisioner namespaces](#namespace-provisioners). The `provisioners` value within the [resource namespace](#namespace-resources) represents the [provisioners][ref-tf-provisioners] within a specific resource. Provisioners are listed in the order they were provided in the configuration file. While the `provisioners` value will be present within data sources, it will always be an empty map (in Terraform 0.11) or `null` (in Terraform 0.12) since data sources cannot actually have provisioners. The data within a provisioner can be inspected via the returned [provisioner namespace](#namespace-provisioners). [ref-tf-provisioners]: /terraform/language/resources/provisioners/syntax ## Namespace: Provisioners The **provisioner namespace** represents the configuration for a particular [provisioner][ref-tf-provisioners] within a specific resource. <a id="provisioners-value-config" /> ### Value: `config` * **Value Type:** A string-keyed map of values. The `config` value within the [provisioner namespace](#namespace-provisioners) represents the values of the keys within the provisioner. -> **With Terraform 0.11 or earlier**, if the config value is defined as an expression (and not a static value), the value will be in its raw, non-interpolated string. **With Terraform 0.12 or later**, any non-static values (such as interpolated strings) are not present and [`references`](#provisioners-value-references) should be used instead. As an example, given the following resource block: ```hcl resource "null_resource" "foo" { # ... provisioner "local-exec" { command = "echo ${self.private_ip} > file.txt" } } ``` The following policy would evaluate to `true`: ```python import "tfconfig" main = rule { tfconfig.resources.null_resource.foo.provisioners[0].config.command is "echo ${self.private_ip} > file.txt" } ``` <a id="provisioners-value-references" /> ### Value: `references` * **Value Type:** A string-keyed map of list values containing strings. -> **Note:** This value is only present when using Terraform 0.12 or later. The `references` value within the [provisioner namespace](#namespace-provisioners) contains the identifiers within non-constant expressions found in [`config`](#provisioners-value-config). See the [documentation on `references`](#references-with-terraform-0-12) for more information. <a id="provisioners-value-type" /> ### Value: `type` * **Value Type:** String. The `type` value within the [provisioner namespace](#namespace-provisioners) represents the type of the specific provisioner. As an example, in the following resource block: ```hcl resource "null_resource" "foo" { # ... provisioner "local-exec" { command = "echo ${self.private_ip} > file.txt" } } ``` The following policy would evaluate to `true`: ```python import "tfconfig" main = rule { tfconfig.resources.null_resource.foo.provisioners[0].type is "local-exec" } ``` ## Namespace: Module Configuration The **module configuration** namespace displays data on _module configuration_ as it is given within a `module` block. This means that the namespace concerns itself with the contents of the declaration block (example: the `source` parameter and variable assignment keys), not the data within the module (example: any contained resources or data sources). For the latter, the module instance would need to be looked up with the [`module()` function](#root-function-module). <a id="modules-value-source" /> ### Value: `source` * **Value Type:** String. The `source` value within the [module configuration namespace](#namespace-module-configuration) represents the module source path as supplied to the module configuration. As an example, given the module declaration block: ```hcl module "foo" { source = "./foo" } ``` The following policy would evaluate to `true`: ```python import "tfconfig" main = rule { tfconfig.modules.foo.source is "./foo" } ``` <a id="modules-value-version" /> ### Value: `version` * **Value Type:** String. The `version` value within the [module configuration namespace](#namespace-module-configuration) represents the [version constraint][module-version-constraint] for modules that support it, such as modules within the [Terraform Module Registry][terraform-module-registry] or the [HCP Terraform private module registry][tfe-private-registry]. [module-version-constraint]: /terraform/language/modules#module-versions [terraform-module-registry]: https://registry.terraform.io/ [tfe-private-registry]: /terraform/cloud-docs/registry As an example, given the module declaration block: ```hcl module "foo" { source = "foo/bar" version = "~> 1.2" } ``` The following policy would evaluate to `true`: ```python import "tfconfig" main = rule { tfconfig.modules.foo.version is "~> 1.2" } ``` <a id="modules-value-config" /> ### Value: `config` * **Value Type:** A string-keyed map of values. -> **With Terraform 0.11 or earlier**, if the config value is defined as an expression (and not a static value), the value will be in its raw, non-interpolated string. **With Terraform 0.12 or later**, any non-static values (such as interpolated strings) are not present and [`references`](#modules-value-references) should be used instead. The `config` value within the [module configuration namespace](#namespace-module-configuration) represents the values of the keys within the module configuration. This is every key within a module declaration block except [`source`](#modules-value-source) and [`version`](#modules-value-version), which have their own values. As an example, given the module declaration block: ```hcl module "foo" { source = "./foo" bar = "baz" } ``` The following policy would evaluate to `true`: ```python import "tfconfig" main = rule { tfconfig.modules.foo.config.bar is "baz" } ``` <a id="modules-value-references" /> ### Value: `references` * **Value Type:** A string-keyed map of list values containing strings. -> **Note:** This value is only present when using Terraform 0.12 or later. The `references` value within the [module configuration namespace](#namespace-module-configuration) contains the identifiers within non-constant expressions found in [`config`](#modules-value-config). See the [documentation on `references`](#references-with-terraform-0-12) for more information. ## Namespace: Outputs The **output namespace** represents _declared_ output data within a configuration. As such, configuration for the [`value`](#outputs-value-value) attribute will be in its raw form, and not yet interpolated. For fully interpolated output values, see the [`tfstate` import][ref-tfe-sentinel-tfstate]. [ref-tfe-sentinel-tfstate]: /terraform/cloud-docs/policy-enforcement/sentinel/import/tfstate This namespace is indexed by output name. <a id="outputs-value-depends_on" /> ### Value: `depends_on` * **Value Type:** A list of strings. The `depends_on` value within the [output namespace](#namespace-outputs) represents any _explicit_ dependencies for this output. For more information, see the [depends_on output setting][ref-depends_on] within the general Terraform documentation. [ref-depends_on]: /terraform/language/values/outputs#depends_on As an example, given the following output declaration block: ```hcl output "id" { depends_on = ["null_resource.bar"] value = "${null_resource.foo.id}" } ``` The following policy would evaluate to `true`: ```python import "tfconfig" main = rule { tfconfig.outputs.id.depends_on[0] is "null_resource.bar" } ``` <a id="outputs-value-description" /> ### Value: `description` * **Value Type:** String. The `description` value within the [output namespace](#namespace-outputs) represents the defined description for this output. As an example, given the following output declaration block: ```hcl output "id" { description = "foobar" value = "${null_resource.foo.id}" } ``` The following policy would evaluate to `true`: ```python import "tfconfig" main = rule { tfconfig.outputs.id.description is "foobar" } ``` <a id="outputs-value-sensitive" /> ### Value: `sensitive` * **Value Type:** Boolean. The `sensitive` value within the [output namespace](#namespace-outputs) represents if this value has been marked as sensitive or not. As an example, given the following output declaration block: ```hcl output "id" { sensitive = true value = "${null_resource.foo.id}" } ``` The following policy would evaluate to `true`: ```python import "tfconfig" main = rule { subject.outputs.id.sensitive } ``` <a id="outputs-value-value" /> ### Value: `value` * **Value Type:** Any primitive type, list or map. The `value` value within the [output namespace](#namespace-outputs) represents the defined value for the output as declared in the configuration. Primitives will bear the implicit type of their declaration (string, int, float, or bool), and maps and lists will be represented as such. -> **With Terraform 0.11 or earlier**, if the config value is defined as an expression (and not a static value), the value will be in its raw, non-interpolated string. **With Terraform 0.12 or later**, any non-static values (such as interpolated strings) are not present and [`references`](#outputs-value-references) should be used instead. As an example, given the following output declaration block: ```hcl output "id" { value = "${null_resource.foo.id}" } ``` With Terraform 0.11 or earlier the following policy would evaluate to `true`: ```python import "tfconfig" main = rule { tfconfig.outputs.id.value is "${null_resource.foo.id}" } ``` <a id="outputs-value-references" /> ### Value: `references` * **Value Type:**. List of strings. -> **Note:** This value is only present when using Terraform 0.12 or later. The `references` value within the [output namespace](#namespace-outputs) contains the names of any referenced identifiers when [`value`](#outputs-value-value) is a non-constant expression. As an example, given the following output declaration block: ```hcl output "id" { value = "${null_resource.foo.id}" } ``` The following policy would evaluate to `true`: ```python import "tfconfig" main = rule { tfconfig.outputs.id.references contains "null_resource.foo.id" } ``` ## Namespace: Providers The **provider namespace** represents data on the declared providers within a namespace. This namespace is indexed by provider type and _only_ contains data about providers when actually declared. If you are using a completely implicit provider configuration, this namespace will be empty. This namespace is populated based on the following criteria: * The top-level namespace [`config`](#providers-value-config) and [`version`](#providers-value-version) values are populated with the configuration and version information from the default provider (the provider declaration that lacks an alias). * Any aliased providers are added as namespaces within the [`alias`](#providers-value-alias) value. * If a module lacks a default provider configuration, the top-level `config` and `version` values will be empty. <a id="providers-value-alias" /> ### Value: `alias` * **Value Type:** A map of [provider namespaces](#namespace-providers), indexed by alias. The `alias` value within the [provider namespace](#namespace-providers) represents all declared [non-default provider instances][ref-tf-provider-instances] for a specific provider type, indexed by their specific alias. [ref-tf-provider-instances]: /terraform/language/providers/configuration#alias-multiple-provider-configurations The return type is a provider namespace with the data for the instance in question loaded. The `alias` key will not be available within this namespace. As an example, given the following provider declaration block: ```hcl provider "aws" { alias = "east" region = "us-east-1" } ``` The following policy would evaluate to `true`: ```python import "tfconfig" main = rule { tfconfig.providers.aws.alias.east.config.region is "us-east-1" } ``` <a id="providers-value-config" /> ### Value: `config` * **Value Type:** A string-keyed map of values. -> **With Terraform 0.11 or earlier**, if the config value is defined as an expression (and not a static value), the value will be in its raw, non-interpolated string. **With Terraform 0.12 or later**, any non-static values (such as interpolated strings) are not present and [`references`](#providers-value-references) should be used instead. The `config` value within the [provider namespace](#namespace-providers) represents the values of the keys within the provider's configuration, with the exception of the provider version, which is represented by the [`version`](#providers-value-version) value. [`alias`](#providers-value-alias) is also not included when the provider is aliased. As an example, given the following provider declaration block: ```hcl provider "aws" { region = "us-east-1" } ``` The following policy would evaluate to `true`: ```python import "tfconfig" main = rule { tfconfig.providers.aws.config.region is "us-east-1" } ``` <a id="providers-value-references" /> ### Value: `references` * **Value Type:** A string-keyed map of list values containing strings. -> **Note:** This value is only present when using Terraform 0.12 or later. The `references` value within the [provider namespace](#namespace-providers) contains the identifiers within non-constant expressions found in [`config`](#providers-value-config). See the [documentation on `references`](#references-with-terraform-0-12) for more information. <a id="providers-value-version" /> ### Value: `version` * **Value Type:** String. The `version` value within the [provider namespace](#namespace-providers) represents the explicit expected version of the supplied provider. This includes the pessimistic operator. As an example, given the following provider declaration block: ```hcl provider "aws" { version = "~> 1.34" } ``` The following policy would evaluate to `true`: ```python import "tfconfig" main = rule { tfconfig.providers.aws.version is "~> 1.34" } ``` ## Namespace: Variables The **variable namespace** represents _declared_ variable data within a configuration. As such, static data can be extracted, such as defaults, but not dynamic data, such as the current value of a variable within a plan (although this can be extracted within the [`tfplan` import][ref-tfe-sentinel-tfplan]). [ref-tfe-sentinel-tfplan]: /terraform/cloud-docs/policy-enforcement/sentinel/import/tfplan This namespace is indexed by variable name. <a id="variables-value-default" /> ### Value: `default` * **Value Type:** Any primitive type, list, map, or `null`. The `default` value within the [variable namespace](#namespace-variables) represents the default for the variable as declared in the configuration. The actual value will be as configured. Primitives will bear the implicit type of their declaration (string, int, float, or bool), and maps and lists will be represented as such. If no default is present, the value will be [`null`][ref-sentinel-null] (not to be confused with [`undefined`][ref-sentinel-undefined]). [ref-sentinel-null]: https://docs.hashicorp.com/sentinel/language/spec#null [ref-sentinel-undefined]: https://docs.hashicorp.com/sentinel/language/undefined As an example, given the following variable blocks: ```hcl variable "foo" { default = "bar" } variable "number" { default = 42 } ``` The following policy would evaluate to `true`: ```python import "tfconfig" default_foo = rule { tfconfig.variables.foo.default is "bar" } default_number = rule { tfconfig.variables.number.default is 42 } main = rule { default_foo and default_number } ``` <a id="variables-value-description" /> ### Value: `description` * **Value Type:** String. The `description` value within the [variable namespace](#namespace-variables) represents the description of the variable, as provided in configuration. As an example, given the following variable block: ```hcl variable "foo" { description = "foobar" } ``` The following policy would evaluate to `true`: ```python import "tfconfig" main = rule { tfconfig.variables.foo.description is "foobar" } ```
terraform
page title tfconfig Imports Sentinel HCP Terraform description The tfconfig import provides access to a Terraform configuration Import tfconfig Warning The tfconfig import is now deprecated and will be permanently removed in August 2025 We recommend that you start using the updated tfconfig v2 terraform cloud docs policy enforcement sentinel import tfconfig v2 import as soon as possible to avoid disruptions The tfconfig v2 import offers improved functionality and is designed to better support your policy enforcement needs The tfconfig import provides access to a Terraform configuration The Terraform configuration is the set of tf files that are used to describe the desired infrastructure state Policies using the tfconfig import can access all aspects of the configuration providers resources data sources modules and variables BEGIN TFC only name pnp callout include tfc package callouts policies mdx END TFC only name pnp callout Some use cases for tfconfig include Organizational naming conventions requiring that configuration elements are named in a way that conforms to some organization wide standard Required inputs and outputs organizations may require a particular set of input variable names across all workspaces or may require a particular set of outputs for asset management purposes Enforcing particular modules organizations may provide a number of building block modules and require that each workspace be built only from combinations of these modules Enforcing particular providers or resources an organization may wish to require or prevent the use of providers and or resources so that configuration authors cannot use alternative approaches to work around policy restrictions Note with these use cases that this import is concerned with object names in the configuration Since this is the configuration and not an invocation of Terraform you can t see values for variables the state or the diff for a pending plan If you want to write policy around expressions used within configuration blocks you likely want to use the tfplan terraform cloud docs policy enforcement sentinel import tfplan import Namespace Overview The following is a tree view of the import namespace For more detail on a particular part of the namespace see below Note The root level alias keys shown here data modules providers resources and variables are shortcuts to a module namespace namespace module scoped to the root module For more details see the section on root namespace aliases root namespace aliases tfconfig module function module namespace data TYPE NAME config map of keys references map of keys TF 0 12 and later provisioners NUMBER config map of keys references map of keys TF 0 12 and later type string modules NAME config map of keys references map of keys TF 0 12 and later source string version string outputs NAME depends on list of strings description string sensitive boolean references list of strings TF 0 12 and later value value providers TYPE alias ALIAS config map of keys references map of keys TF 0 12 and later version string config map of keys references map of keys TF 0 12 and later version string resources TYPE NAME config map of keys references map of keys TF 0 12 and later provisioners NUMBER config map of keys references map of keys TF 0 12 and later type string variables NAME default value description string module paths string data root module alias modules root module alias outputs root module alias providers root module alias resources root module alias variables root module alias references with Terraform 0 12 With Terraform 0 11 or earlier if a configuration value is defined as an expression and not a static value the value will be accessible in its raw non interpolated string just as with a constant value As an example consider the following resource block hcl resource local file accounts content some text filename var subdomain var domain accounts txt In this example one might want to ensure domain and subdomain input variables are used within filename in this configuration With Terraform 0 11 or earlier the following policy would evaluate to true python import tfconfig filename value is the raw non interpolated string filename value tfconfig resources local file accounts config filename main rule filename value contains var domain and filename value contains var subdomain With Terraform 0 12 or later any non static values such as interpolated strings are not present within the configuration value and references should be used instead python import tfconfig filename references is a list of string values containing the references used in the expression filename references tfconfig resources local file accounts references filename main rule filename references contains var domain and filename references contains var subdomain The references value is present in any namespace where non constant configuration values can be expressed This is essentially every namespace which has a config value as well as the outputs namespace Note Remember this import enforces policy around the literal Terraform configuration and not the final values as a result of invoking Terraform If you want to write policy around the result of expressions used within configuration blocks for example if you wanted to ensure the final value of filename above includes accounts txt you likely want to use the tfplan terraform cloud docs policy enforcement sentinel import tfplan import Namespace Root The root level namespace consists of the values and functions documented below In addition to this the root level data modules providers resources and variables keys all alias to their corresponding namespaces within the module namespace namespace module a id root function module Function module module func ADDR Return Type A module namespace namespace module The module function in the root namespace namespace root returns the module namespace namespace module for a particular module address The address must be a list and is the module address split on the period excluding the root module Hence a module with an address of simply foo or root foo would be foo and a module within that so address foo bar would be read as foo bar null ref null is returned if a module address is invalid or if the module is not present in the configuration ref null https docs hashicorp com sentinel language spec null As an example given the following module block hcl module foo If the module contained the following content hcl resource null resource foo triggers foo bar The following policy would evaluate to true python import tfconfig main rule subject module foo resources null resource foo config triggers 0 foo is bar a id root value module paths Value module paths Value Type List of a list of strings The module paths value within the root namespace namespace root is a list of all of the modules within the Terraform configuration Modules not present in the configuration will not be present here even if they are present in the diff or state This data is represented as a list of a list of strings with the inner list being the module address split on the period The root module is included in this list represented as an empty inner list As an example if the following module block was present within a Terraform configuration hcl module foo The value of module paths would be foo And the following policy would evaluate to true python import tfconfig main rule tfconfig module paths contains foo Iterating Through Modules Iterating through all modules to find particular resources can be useful This example iterate over modules shows how to use module paths with the module function function module to find all resources of a particular type from all modules using the tfplan import By changing tfplan in this function to tfconfig you could make a similar function find all resources of a specific type in the Terraform configuration iterate over modules terraform cloud docs policy enforcement sentinel sentinel imports Namespace Module The module namespace can be loaded by calling module root function module for a particular module It can be used to load the following child namespaces data Loads the resource namespace namespace resources data sources filtered against data sources modules Loads the module configuration namespace namespace module configuration outputs Loads the output namespace namespace outputs providers Loads the provider namespace namespace providers resources Loads the resource namespace namespace resources data sources filtered against resources variables Loads the variable namespace namespace variables Root Namespace Aliases The root level data modules providers resources and variables keys all alias to their corresponding namespaces within the module namespace loaded for the root module They are the equivalent of running module KEY a id namespace resources a Namespace Resources Data Sources The resource namespace is a namespace type that applies to both resources accessed by using the resources namespace key and data sources accessed using the data namespace key Accessing an individual resource or data source within each respective namespace can be accomplished by specifying the type and name in the syntax resources data TYPE NAME In addition each of these namespace levels is a map allowing you to filter based on type and name Some examples of multi level access are below To fetch all aws instance resources within the root module you can specify tfconfig resources aws instance This would give you a map of resource namespaces indexed from the names of each resource foo bar and so on To fetch all resources within the root module irrespective of type use tfconfig resources This is indexed by type as shown above with tfconfig resources aws instance with names being the next level down As an example perhaps you wish to deny use of the local file resource in your configuration Consider the following resource block hcl resource local file foo content foo filename path module foo bar The following policy would fail python import tfconfig main rule tfconfig resources not contains local file Further explanation of the namespace will be in the context of resources As mentioned when operating on data sources use the same syntax except with data in place of resources a id resources value config Value config Value Type A string keyed map of values The config value within the resource namespace namespace resources data sources is a map of key value pairs that directly map to Terraform config keys and values With Terraform 0 11 or earlier if the config value is defined as an expression and not a static value the value will be in its raw non interpolated string With Terraform 0 12 or later any non static values such as interpolated strings are not present and references resources value references should be used instead As an example consider the following resource block hcl resource local file accounts content some text filename accounts txt In this example one might want to access filename to validate that the correct file name is used Given the above example the following policy would evaluate to true python import tfconfig main rule tfconfig resources local file accounts config filename is accounts txt a id resources value references Value references Value Type A string keyed map of list values containing strings Note This value is only present when using Terraform 0 12 or later The references value within the resource namespace namespace resources data sources contains the identifiers within non constant expressions found in config resources value config See the documentation on references references with terraform 0 12 for more information a id resources value provisioners Value provisioners Value Type List of provisioner namespaces namespace provisioners The provisioners value within the resource namespace namespace resources represents the provisioners ref tf provisioners within a specific resource Provisioners are listed in the order they were provided in the configuration file While the provisioners value will be present within data sources it will always be an empty map in Terraform 0 11 or null in Terraform 0 12 since data sources cannot actually have provisioners The data within a provisioner can be inspected via the returned provisioner namespace namespace provisioners ref tf provisioners terraform language resources provisioners syntax Namespace Provisioners The provisioner namespace represents the configuration for a particular provisioner ref tf provisioners within a specific resource a id provisioners value config Value config Value Type A string keyed map of values The config value within the provisioner namespace namespace provisioners represents the values of the keys within the provisioner With Terraform 0 11 or earlier if the config value is defined as an expression and not a static value the value will be in its raw non interpolated string With Terraform 0 12 or later any non static values such as interpolated strings are not present and references provisioners value references should be used instead As an example given the following resource block hcl resource null resource foo provisioner local exec command echo self private ip file txt The following policy would evaluate to true python import tfconfig main rule tfconfig resources null resource foo provisioners 0 config command is echo self private ip file txt a id provisioners value references Value references Value Type A string keyed map of list values containing strings Note This value is only present when using Terraform 0 12 or later The references value within the provisioner namespace namespace provisioners contains the identifiers within non constant expressions found in config provisioners value config See the documentation on references references with terraform 0 12 for more information a id provisioners value type Value type Value Type String The type value within the provisioner namespace namespace provisioners represents the type of the specific provisioner As an example in the following resource block hcl resource null resource foo provisioner local exec command echo self private ip file txt The following policy would evaluate to true python import tfconfig main rule tfconfig resources null resource foo provisioners 0 type is local exec Namespace Module Configuration The module configuration namespace displays data on module configuration as it is given within a module block This means that the namespace concerns itself with the contents of the declaration block example the source parameter and variable assignment keys not the data within the module example any contained resources or data sources For the latter the module instance would need to be looked up with the module function root function module a id modules value source Value source Value Type String The source value within the module configuration namespace namespace module configuration represents the module source path as supplied to the module configuration As an example given the module declaration block hcl module foo source foo The following policy would evaluate to true python import tfconfig main rule tfconfig modules foo source is foo a id modules value version Value version Value Type String The version value within the module configuration namespace namespace module configuration represents the version constraint module version constraint for modules that support it such as modules within the Terraform Module Registry terraform module registry or the HCP Terraform private module registry tfe private registry module version constraint terraform language modules module versions terraform module registry https registry terraform io tfe private registry terraform cloud docs registry As an example given the module declaration block hcl module foo source foo bar version 1 2 The following policy would evaluate to true python import tfconfig main rule tfconfig modules foo version is 1 2 a id modules value config Value config Value Type A string keyed map of values With Terraform 0 11 or earlier if the config value is defined as an expression and not a static value the value will be in its raw non interpolated string With Terraform 0 12 or later any non static values such as interpolated strings are not present and references modules value references should be used instead The config value within the module configuration namespace namespace module configuration represents the values of the keys within the module configuration This is every key within a module declaration block except source modules value source and version modules value version which have their own values As an example given the module declaration block hcl module foo source foo bar baz The following policy would evaluate to true python import tfconfig main rule tfconfig modules foo config bar is baz a id modules value references Value references Value Type A string keyed map of list values containing strings Note This value is only present when using Terraform 0 12 or later The references value within the module configuration namespace namespace module configuration contains the identifiers within non constant expressions found in config modules value config See the documentation on references references with terraform 0 12 for more information Namespace Outputs The output namespace represents declared output data within a configuration As such configuration for the value outputs value value attribute will be in its raw form and not yet interpolated For fully interpolated output values see the tfstate import ref tfe sentinel tfstate ref tfe sentinel tfstate terraform cloud docs policy enforcement sentinel import tfstate This namespace is indexed by output name a id outputs value depends on Value depends on Value Type A list of strings The depends on value within the output namespace namespace outputs represents any explicit dependencies for this output For more information see the depends on output setting ref depends on within the general Terraform documentation ref depends on terraform language values outputs depends on As an example given the following output declaration block hcl output id depends on null resource bar value null resource foo id The following policy would evaluate to true python import tfconfig main rule tfconfig outputs id depends on 0 is null resource bar a id outputs value description Value description Value Type String The description value within the output namespace namespace outputs represents the defined description for this output As an example given the following output declaration block hcl output id description foobar value null resource foo id The following policy would evaluate to true python import tfconfig main rule tfconfig outputs id description is foobar a id outputs value sensitive Value sensitive Value Type Boolean The sensitive value within the output namespace namespace outputs represents if this value has been marked as sensitive or not As an example given the following output declaration block hcl output id sensitive true value null resource foo id The following policy would evaluate to true python import tfconfig main rule subject outputs id sensitive a id outputs value value Value value Value Type Any primitive type list or map The value value within the output namespace namespace outputs represents the defined value for the output as declared in the configuration Primitives will bear the implicit type of their declaration string int float or bool and maps and lists will be represented as such With Terraform 0 11 or earlier if the config value is defined as an expression and not a static value the value will be in its raw non interpolated string With Terraform 0 12 or later any non static values such as interpolated strings are not present and references outputs value references should be used instead As an example given the following output declaration block hcl output id value null resource foo id With Terraform 0 11 or earlier the following policy would evaluate to true python import tfconfig main rule tfconfig outputs id value is null resource foo id a id outputs value references Value references Value Type List of strings Note This value is only present when using Terraform 0 12 or later The references value within the output namespace namespace outputs contains the names of any referenced identifiers when value outputs value value is a non constant expression As an example given the following output declaration block hcl output id value null resource foo id The following policy would evaluate to true python import tfconfig main rule tfconfig outputs id references contains null resource foo id Namespace Providers The provider namespace represents data on the declared providers within a namespace This namespace is indexed by provider type and only contains data about providers when actually declared If you are using a completely implicit provider configuration this namespace will be empty This namespace is populated based on the following criteria The top level namespace config providers value config and version providers value version values are populated with the configuration and version information from the default provider the provider declaration that lacks an alias Any aliased providers are added as namespaces within the alias providers value alias value If a module lacks a default provider configuration the top level config and version values will be empty a id providers value alias Value alias Value Type A map of provider namespaces namespace providers indexed by alias The alias value within the provider namespace namespace providers represents all declared non default provider instances ref tf provider instances for a specific provider type indexed by their specific alias ref tf provider instances terraform language providers configuration alias multiple provider configurations The return type is a provider namespace with the data for the instance in question loaded The alias key will not be available within this namespace As an example given the following provider declaration block hcl provider aws alias east region us east 1 The following policy would evaluate to true python import tfconfig main rule tfconfig providers aws alias east config region is us east 1 a id providers value config Value config Value Type A string keyed map of values With Terraform 0 11 or earlier if the config value is defined as an expression and not a static value the value will be in its raw non interpolated string With Terraform 0 12 or later any non static values such as interpolated strings are not present and references providers value references should be used instead The config value within the provider namespace namespace providers represents the values of the keys within the provider s configuration with the exception of the provider version which is represented by the version providers value version value alias providers value alias is also not included when the provider is aliased As an example given the following provider declaration block hcl provider aws region us east 1 The following policy would evaluate to true python import tfconfig main rule tfconfig providers aws config region is us east 1 a id providers value references Value references Value Type A string keyed map of list values containing strings Note This value is only present when using Terraform 0 12 or later The references value within the provider namespace namespace providers contains the identifiers within non constant expressions found in config providers value config See the documentation on references references with terraform 0 12 for more information a id providers value version Value version Value Type String The version value within the provider namespace namespace providers represents the explicit expected version of the supplied provider This includes the pessimistic operator As an example given the following provider declaration block hcl provider aws version 1 34 The following policy would evaluate to true python import tfconfig main rule tfconfig providers aws version is 1 34 Namespace Variables The variable namespace represents declared variable data within a configuration As such static data can be extracted such as defaults but not dynamic data such as the current value of a variable within a plan although this can be extracted within the tfplan import ref tfe sentinel tfplan ref tfe sentinel tfplan terraform cloud docs policy enforcement sentinel import tfplan This namespace is indexed by variable name a id variables value default Value default Value Type Any primitive type list map or null The default value within the variable namespace namespace variables represents the default for the variable as declared in the configuration The actual value will be as configured Primitives will bear the implicit type of their declaration string int float or bool and maps and lists will be represented as such If no default is present the value will be null ref sentinel null not to be confused with undefined ref sentinel undefined ref sentinel null https docs hashicorp com sentinel language spec null ref sentinel undefined https docs hashicorp com sentinel language undefined As an example given the following variable blocks hcl variable foo default bar variable number default 42 The following policy would evaluate to true python import tfconfig default foo rule tfconfig variables foo default is bar default number rule tfconfig variables number default is 42 main rule default foo and default number a id variables value description Value description Value Type String The description value within the variable namespace namespace variables represents the description of the variable as provided in configuration As an example given the following variable block hcl variable foo description foobar The following policy would evaluate to true python import tfconfig main rule tfconfig variables foo description is foobar
terraform Import tfplan page title tfplan Imports Sentinel HCP Terraform The tfplan import provides access to a Terraform plan A Terraform plan is the file created as a result of terraform plan and is the input to terraform apply The plan represents the changes that Terraform needs to make to infrastructure to reach the desired state represented by the configuration
--- page_title: tfplan - Imports - Sentinel - HCP Terraform description: >- The tfplan import provides access to a Terraform plan. A Terraform plan is the file created as a result of `terraform plan` and is the input to `terraform apply`. The plan represents the changes that Terraform needs to make to infrastructure to reach the desired state represented by the configuration. --- # Import: tfplan ~> **Warning:** The `tfplan` import is now deprecated and will be permanently removed in August 2025. We recommend that you start using the updated [tfplan/v2](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfplan-v2) import as soon as possible to avoid disruptions. The `tfplan/v2` import offers improved functionality and is designed to better support your policy enforcement needs. The `tfplan` import provides access to a Terraform plan. A Terraform plan is the file created as a result of `terraform plan` and is the input to `terraform apply`. The plan represents the changes that Terraform needs to make to infrastructure to reach the desired state represented by the configuration. In addition to the diff data available in the plan, there is an [`applied`](#value-applied) state available that merges the plan with the state to create the planned state after apply. Finally, this import also allows you to access the configuration files and the Terraform state at the time the plan was run. See the section on [accessing a plan's state and configuration data](#accessing-a-plan-39-s-state-and-configuration-data) for more information. <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/policies.mdx' <!-- END: TFC:only name:pnp-callout --> ## Namespace Overview The following is a tree view of the import namespace. For more detail on a particular part of the namespace, see below. -> Note that the root-level alias keys shown here (`data`, `path`, and `resources`) are shortcuts to a [module namespace](#namespace-module) scoped to the root module. For more details, see the section on [root namespace aliases](#root-namespace-aliases). ``` tfplan ├── module() (function) │ └── (module namespace) │ ├── path ([]string) │ ├── data │ │ └── TYPE.NAME[NUMBER] │ │ ├── applied (map of keys) │ │ └── diff │ │ └── KEY │ │ ├── computed (bool) │ │ ├── new (string) │ │ └── old (string) │ └── resources │ └── TYPE.NAME[NUMBER] │ ├── applied (map of keys) │ ├── destroy (bool) │ ├── requires_new (bool) │ └── diff │ └── KEY │ ├── computed (bool) │ ├── new (string) │ └── old (string) ├── module_paths ([][]string) ├── terraform_version (string) ├── variables (map of keys) │ ├── data (root module alias) ├── path (root module alias) ├── resources (root module alias) │ ├── config (tfconfig namespace alias) └── state (tfstate import alias) ``` ## Namespace: Root The root-level namespace consists of the values and functions documented below. In addition to this, the root-level `data`, `path`, and `resources` keys alias to their corresponding namespaces or values within the [module namespace](#namespace-module). ### Accessing a Plan's State and Configuration Data The `config` and `state` keys alias to the [`tfconfig`][import-tfconfig] and [`tfstate`][import-tfstate] namespaces, respectively, with the data sourced from the Terraform _plan_ (as opposed to actual configuration and state). [import-tfconfig]: /terraform/cloud-docs/policy-enforcement/sentinel/import/tfconfig [import-tfstate]: /terraform/cloud-docs/policy-enforcement/sentinel/import/tfstate -> Note that these aliases are not represented as maps. While they will appear empty when viewed as maps, the specific import namespace keys will still be accessible. -> Note that while current versions of HCP Terraform source configuration and state data from the plan for the Terraform run in question, future versions may source data accessed through the `tfconfig` and `tfstate` imports (as opposed to `tfplan.config` and `tfplan.state`) from actual config bundles, or state as stored by HCP Terraform. When this happens, the distinction here will be useful - the data in the aliased namespaces will be the config and state data as the _plan_ sees it, versus the actual "physical" data. ### Function: `module()` ``` module = func(ADDR) ``` * **Return Type:** A [module namespace](#namespace-module). The `module()` function in the [root namespace](#namespace-root) returns the [module namespace](#namespace-module) for a particular module address. The address must be a list and is the module address, split on the period (`.`), excluding the root module. Hence, a module with an address of simply `foo` (or `root.foo`) would be `["foo"]`, and a module within that (so address `foo.bar`) would be read as `["foo", "bar"]`. [`null`][ref-null] is returned if a module address is invalid, or if the module is not present in the diff. [ref-null]: https://docs.hashicorp.com/sentinel/language/spec#null As an example, given the following module block: ```hcl module "foo" { # ... } ``` If the module contained the following content: ```hcl resource "null_resource" "foo" { triggers = { foo = "bar" } } ``` The following policy would evaluate to `true`: ```python import "tfplan" main = rule { tfplan.module(["foo"]).resources.null_resource.foo[0].applied.triggers.foo is "bar" } ``` ### Value: `module_paths` * **Value Type:** List of a list of strings. The `module_paths` value within the [root namespace](#namespace-root) is a list of all of the modules within the Terraform diff for the current plan. Modules not present in the diff will not be present here, even if they are present in the configuration or state. This data is represented as a list of a list of strings, with the inner list being the module address, split on the period (`.`). The root module is included in this list, represented as an empty inner list, as long as there are changes. As an example, if the following module block was present within a Terraform configuration: ```hcl module "foo" { # ... } ``` The value of `module_paths` would be: ``` [ [], ["foo"], ] ``` And the following policy would evaluate to `true`: ```python import "tfplan" main = rule { tfplan.module_paths contains ["foo"] } ``` -> Note the above example only applies if the module is present in the diff. #### Iterating Through Modules Iterating through all modules to find particular resources can be useful. This [example][iterate-over-modules] shows how to use `module_paths` with the [`module()` function](#function-module-) to find all resources of a particular type from all modules that have pending changes using the `tfplan` import. [iterate-over-modules]: /terraform/cloud-docs/policy-enforcement/sentinel#sentinel-imports ### Value: `terraform_version` * **Value Type:** String. The `terraform_version` value within the [root namespace](#namespace-root) represents the version of Terraform used to create the plan. This can be used to enforce a specific version of Terraform in a policy check. As an example, the following policy would evaluate to `true`, as long as the plan was made with a version of Terraform in the 0.11.x series, excluding any pre-release versions (example: `-beta1` or `-rc1`): ```python import "tfplan" main = rule { tfplan.terraform_version matches "^0\\.11\\.\\d+$" } ``` ### Value: `variables` * **Value Type:** A string-keyed map of values. The `variables` value within the [root namespace](#namespace-root) represents all of the variables that were set when creating the plan. This will only contain variables set for the root module. Note that unlike the [`default`][import-tfconfig-variables-default] value in the [`tfconfig` variables namespace][import-tfconfig-variables], primitive values here are stringified, and type conversion will need to be performed to perform comparison for int, float, or boolean values. This only applies to variables that are primitives themselves and not primitives within maps and lists, which will be their original types. [import-tfconfig-variables-default]: /terraform/cloud-docs/policy-enforcement/sentinel/import/tfconfig#value-default [import-tfconfig-variables]: /terraform/cloud-docs/policy-enforcement/sentinel/import/tfconfig#namespace-variables If a default was accepted for the particular variable, the default value will be populated here. As an example, given the following variable blocks: ```hcl variable "foo" { default = "bar" } variable "number" { default = 42 } variable "map" { default = { foo = "bar" number = 42 } } ``` The following policy would evaluate to `true`, if no values were entered to change these variables: ```python import "tfplan" default_foo = rule { tfplan.variables.foo is "bar" } default_number = rule { tfplan.variables.number is "42" } default_map_string = rule { tfplan.variables.map["foo"] is "bar" } default_map_int = rule { tfplan.variables.map["number"] is 42 } main = rule { default_foo and default_number and default_map_string and default_map_int } ``` ## Namespace: Module The **module namespace** can be loaded by calling [`module()`](#function-module-) for a particular module. It can be used to load the following child namespaces, in addition to the values documented below: * `data` - Loads the [resource namespace](#namespace-resources-data-sources), filtered against data sources. * `resources` - Loads the [resource namespace](#namespace-resources-data-sources), filtered against resources. ### Root Namespace Aliases The root-level `data` and `resources` keys both alias to their corresponding namespaces within the module namespace, loaded for the root module. They are the equivalent of running `module([]).KEY`. ### Value: `path` * **Value Type:** List of strings. The `path` value within the [module namespace](#namespace-module) contains the path of the module that the namespace represents. This is represented as a list of strings. As an example, if the following module block was present within a Terraform configuration: ```hcl module "foo" { # ... } ``` The following policy would evaluate to `true` _only_ if the diff had changes for that module: ```python import "tfplan" main = rule { tfplan.module(["foo"]).path contains "foo" } ``` ## Namespace: Resources/Data Sources The **resource namespace** is a namespace _type_ that applies to both resources (accessed by using the `resources` namespace key) and data sources (accessed using the `data` namespace key). Accessing an individual resource or data source within each respective namespace can be accomplished by specifying the type, name, and resource number (as if the resource or data source had a `count` value in it) in the syntax `[resources|data].TYPE.NAME[NUMBER]`. Note that NUMBER is always needed, even if you did not use `count` in the resource. In addition, each of these namespace levels is a map, allowing you to filter based on type and name. -> The (somewhat strange) notation here of `TYPE.NAME[NUMBER]` may imply that the inner resource index map is actually a list, but it's not - using the square bracket notation over the dotted notation (`TYPE.NAME.NUMBER`) is required here as an identifier cannot start with a number. Some examples of multi-level access are below: * To fetch all `aws_instance.foo` resource instances within the root module, you can specify `tfplan.resources.aws_instance.foo`. This would then be indexed by resource count index (`0`, `1`, `2`, and so on). Note that as mentioned above, these elements must be accessed using square-bracket map notation (so `[0]`, `[1]`, `[2]`, and so on) instead of dotted notation. * To fetch all `aws_instance` resources within the root module, you can specify `tfplan.resources.aws_instance`. This would be indexed from the names of each resource (`foo`, `bar`, and so on), with each of those maps containing instances indexed by resource count index as per above. * To fetch all resources within the root module, irrespective of type, use `tfplan.resources`. This is indexed by type, as shown above with `tfplan.resources.aws_instance`, with names being the next level down, and so on. ~> When [resource targeting](/terraform/cli/commands/plan#resource-targeting) is in effect, `tfplan.resources` will only include the resources specified as targets for the run. This may lead to unexpected outcomes if a policy expects a resource to be present in the plan. To prohibit targeted runs altogether, ensure [`tfrun.target_addrs`](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfrun#value-target_addrs) is undefined or empty. Further explanation of the namespace will be in the context of resources. As mentioned, when operating on data sources, use the same syntax, except with `data` in place of `resources`. ### Value: `applied` * **Value Type:** A string-keyed map of values. The `applied` value within the [resource namespace](#namespace-resources-data-sources) contains a "predicted" representation of the resource's state post-apply. It's created by merging the pending resource's diff on top of the existing data from the resource's state (if any). The map is a complex representation of these values with data going as far down as needed to represent any state values such as maps, lists, and sets. As an example, given the following resource: ```hcl resource "null_resource" "foo" { triggers = { foo = "bar" } } ``` The following policy would evaluate to `true` if the resource was in the diff: ```python import "tfplan" main = rule { tfplan.resources.null_resource.foo[0].applied.triggers.foo is "bar" } ``` -> Note that some values will not be available in the `applied` state because they cannot be known until the plan is actually applied. In Terraform 0.11 or earlier, these values are represented by a placeholder (the UUID value `74D93920-ED26-11E3-AC10-0800200C9A66`) and in Terraform 0.12 or later they are `undefined`. **In either case**, you should instead use the [`computed`](#value-computed) key within the [diff namespace](#namespace-resource-diff) to determine that a computed value will exist. -> If a resource is being destroyed, its `applied` value is omitted from the namespace and trying to fetch it will return undefined. ### Value: `diff` * **Value Type:** A map of [diff namespaces](#namespace-resource-diff). The `diff` value within the [resource namespace](#namespace-resources-data-sources) contains the diff for a particular resource. Each key within the map links to a [diff namespace](#namespace-resource-diff) for that particular key. Note that unlike the [`applied`](#value-applied) value, this map is not complex; the map is only 1 level deep with each key possibly representing a diff for a particular complex value within the resource. See the below section for more details on the diff namespace, in addition to usage examples. ### Value: `destroy` * **Value Type:** Boolean. The `destroy` value within the [resource namespace](#namespace-resources-data-sources) is `true` if a resource is being destroyed for _any_ reason, including cases where it's being deleted as part of a resource re-creation, in which case [`requires_new`](#value-requires_new) will also be set. As an example, given the following resource: ```hcl resource "null_resource" "foo" { triggers = { foo = "bar" } } ``` The following policy would evaluate to `true` when `null_resource.foo` is being destroyed: ```python import "tfplan" main = rule { tfplan.resources.null_resource.foo[0].destroy } ``` ### Value: `requires_new` * **Value Type:** Boolean. The `requires_new` value within the [resource namespace](#namespace-resources-data-sources) is `true` if the resource is still present in the configuration, but must be replaced to satisfy its current diff. Whenever `requires_new` is `true`, [`destroy`](#value-destroy) is also `true`. As an example, given the following resource: ```hcl resource "null_resource" "foo" { triggers = { foo = "bar" } } ``` The following policy would evaluate to `true` if one of the `triggers` in `null_resource.foo` was being changed: ```python import "tfplan" main = rule { tfplan.resources.null_resource.foo[0].requires_new } ``` ## Namespace: Resource Diff The **diff namespace** is a namespace that represents the diff for a specific attribute within a resource. For details on reading a particular attribute, see the [`diff`](#value-diff) value in the [resource namespace](#namespace-resources-data-sources). ### Value: `computed` * **Value Type:** Boolean. The `computed` value within the [diff namespace](#namespace-resource-diff) is `true` if the resource key in question depends on another value that isn't yet known. Typically, that means the value it depends on belongs to a resource that either doesn't exist yet, or is changing state in such a way as to affect the dependent value so that it can't be known until the apply is complete. -> Keep in mind that when using `computed` with complex structures such as maps, lists, and sets, it's sometimes necessary to test the count attribute for the structure, versus a key within it, depending on whether or not the diff has marked the whole structure as computed. This is demonstrated in the example below. Count keys are `%` for maps, and `#` for lists and sets. If you are having trouble determining the type of specific field within a resource, contact the support team. As an example, given the following resource: ```hcl resource "null_resource" "foo" { triggers = { foo = "bar" } } resource "null_resource" "bar" { triggers = { foo_id = "${null_resource.foo.id}" } } ``` The following policy would evaluate to `true`, if the `id` of `null_resource.foo` was currently not known, such as when the resource is pending creation, or is being deleted and re-created: ```python import "tfplan" main = rule { tfplan.resources.null_resource.bar[0].diff["triggers.%"].computed } ``` ### Value: `new` * **Value Type:** String. The `new` value within the [diff namespace](#namespace-resource-diff) contains the new value of a changing attribute, _if_ the value is known at plan time. -> `new` will be an empty string if the attribute's value is currently unknown. For more details on detecting unknown values, see [`computed`](#value-computed). Note that this value is _always_ a string, regardless of the actual type of the value changing. [Type conversion][ref-sentinel-type-conversion] within policy may be necessary to achieve the comparison needed. [ref-sentinel-type-conversion]: https://docs.hashicorp.com/sentinel/language/values#type-conversion As an example, given the following resource: ```hcl resource "null_resource" "foo" { triggers = { foo = "bar" } } ``` The following policy would evaluate to `true`, if the resource was in the diff and each of the concerned keys were changing to new values: ```python import "tfplan" main = rule { tfplan.resources.null_resource.foo[0].diff["triggers.foo"].new is "bar" } ``` ### Value: `old` * **Value Type:** String. The `old` value within the [diff namespace](#namespace-resource-diff) contains the old value of a changing attribute. Note that this value is _always_ a string, regardless of the actual type of the value changing. [Type conversion][ref-sentinel-type-conversion] within policy may be necessary to achieve the comparison needed. If the value did not exist in the previous state, `old` will always be an empty string. As an example, given the following resource: ```hcl resource "null_resource" "foo" { triggers = { foo = "baz" } } ``` If that resource was previously in config as: ```hcl resource "null_resource" "foo" { triggers = { foo = "bar" } } ``` The following policy would evaluate to `true`: ```python import "tfplan" main = rule { tfplan.resources.null_resource.foo[0].diff["triggers.foo"].old is "bar" } ```
terraform
page title tfplan Imports Sentinel HCP Terraform description The tfplan import provides access to a Terraform plan A Terraform plan is the file created as a result of terraform plan and is the input to terraform apply The plan represents the changes that Terraform needs to make to infrastructure to reach the desired state represented by the configuration Import tfplan Warning The tfplan import is now deprecated and will be permanently removed in August 2025 We recommend that you start using the updated tfplan v2 terraform cloud docs policy enforcement sentinel import tfplan v2 import as soon as possible to avoid disruptions The tfplan v2 import offers improved functionality and is designed to better support your policy enforcement needs The tfplan import provides access to a Terraform plan A Terraform plan is the file created as a result of terraform plan and is the input to terraform apply The plan represents the changes that Terraform needs to make to infrastructure to reach the desired state represented by the configuration In addition to the diff data available in the plan there is an applied value applied state available that merges the plan with the state to create the planned state after apply Finally this import also allows you to access the configuration files and the Terraform state at the time the plan was run See the section on accessing a plan s state and configuration data accessing a plan 39 s state and configuration data for more information BEGIN TFC only name pnp callout include tfc package callouts policies mdx END TFC only name pnp callout Namespace Overview The following is a tree view of the import namespace For more detail on a particular part of the namespace see below Note that the root level alias keys shown here data path and resources are shortcuts to a module namespace namespace module scoped to the root module For more details see the section on root namespace aliases root namespace aliases tfplan module function module namespace path string data TYPE NAME NUMBER applied map of keys diff KEY computed bool new string old string resources TYPE NAME NUMBER applied map of keys destroy bool requires new bool diff KEY computed bool new string old string module paths string terraform version string variables map of keys data root module alias path root module alias resources root module alias config tfconfig namespace alias state tfstate import alias Namespace Root The root level namespace consists of the values and functions documented below In addition to this the root level data path and resources keys alias to their corresponding namespaces or values within the module namespace namespace module Accessing a Plan s State and Configuration Data The config and state keys alias to the tfconfig import tfconfig and tfstate import tfstate namespaces respectively with the data sourced from the Terraform plan as opposed to actual configuration and state import tfconfig terraform cloud docs policy enforcement sentinel import tfconfig import tfstate terraform cloud docs policy enforcement sentinel import tfstate Note that these aliases are not represented as maps While they will appear empty when viewed as maps the specific import namespace keys will still be accessible Note that while current versions of HCP Terraform source configuration and state data from the plan for the Terraform run in question future versions may source data accessed through the tfconfig and tfstate imports as opposed to tfplan config and tfplan state from actual config bundles or state as stored by HCP Terraform When this happens the distinction here will be useful the data in the aliased namespaces will be the config and state data as the plan sees it versus the actual physical data Function module module func ADDR Return Type A module namespace namespace module The module function in the root namespace namespace root returns the module namespace namespace module for a particular module address The address must be a list and is the module address split on the period excluding the root module Hence a module with an address of simply foo or root foo would be foo and a module within that so address foo bar would be read as foo bar null ref null is returned if a module address is invalid or if the module is not present in the diff ref null https docs hashicorp com sentinel language spec null As an example given the following module block hcl module foo If the module contained the following content hcl resource null resource foo triggers foo bar The following policy would evaluate to true python import tfplan main rule tfplan module foo resources null resource foo 0 applied triggers foo is bar Value module paths Value Type List of a list of strings The module paths value within the root namespace namespace root is a list of all of the modules within the Terraform diff for the current plan Modules not present in the diff will not be present here even if they are present in the configuration or state This data is represented as a list of a list of strings with the inner list being the module address split on the period The root module is included in this list represented as an empty inner list as long as there are changes As an example if the following module block was present within a Terraform configuration hcl module foo The value of module paths would be foo And the following policy would evaluate to true python import tfplan main rule tfplan module paths contains foo Note the above example only applies if the module is present in the diff Iterating Through Modules Iterating through all modules to find particular resources can be useful This example iterate over modules shows how to use module paths with the module function function module to find all resources of a particular type from all modules that have pending changes using the tfplan import iterate over modules terraform cloud docs policy enforcement sentinel sentinel imports Value terraform version Value Type String The terraform version value within the root namespace namespace root represents the version of Terraform used to create the plan This can be used to enforce a specific version of Terraform in a policy check As an example the following policy would evaluate to true as long as the plan was made with a version of Terraform in the 0 11 x series excluding any pre release versions example beta1 or rc1 python import tfplan main rule tfplan terraform version matches 0 11 d Value variables Value Type A string keyed map of values The variables value within the root namespace namespace root represents all of the variables that were set when creating the plan This will only contain variables set for the root module Note that unlike the default import tfconfig variables default value in the tfconfig variables namespace import tfconfig variables primitive values here are stringified and type conversion will need to be performed to perform comparison for int float or boolean values This only applies to variables that are primitives themselves and not primitives within maps and lists which will be their original types import tfconfig variables default terraform cloud docs policy enforcement sentinel import tfconfig value default import tfconfig variables terraform cloud docs policy enforcement sentinel import tfconfig namespace variables If a default was accepted for the particular variable the default value will be populated here As an example given the following variable blocks hcl variable foo default bar variable number default 42 variable map default foo bar number 42 The following policy would evaluate to true if no values were entered to change these variables python import tfplan default foo rule tfplan variables foo is bar default number rule tfplan variables number is 42 default map string rule tfplan variables map foo is bar default map int rule tfplan variables map number is 42 main rule default foo and default number and default map string and default map int Namespace Module The module namespace can be loaded by calling module function module for a particular module It can be used to load the following child namespaces in addition to the values documented below data Loads the resource namespace namespace resources data sources filtered against data sources resources Loads the resource namespace namespace resources data sources filtered against resources Root Namespace Aliases The root level data and resources keys both alias to their corresponding namespaces within the module namespace loaded for the root module They are the equivalent of running module KEY Value path Value Type List of strings The path value within the module namespace namespace module contains the path of the module that the namespace represents This is represented as a list of strings As an example if the following module block was present within a Terraform configuration hcl module foo The following policy would evaluate to true only if the diff had changes for that module python import tfplan main rule tfplan module foo path contains foo Namespace Resources Data Sources The resource namespace is a namespace type that applies to both resources accessed by using the resources namespace key and data sources accessed using the data namespace key Accessing an individual resource or data source within each respective namespace can be accomplished by specifying the type name and resource number as if the resource or data source had a count value in it in the syntax resources data TYPE NAME NUMBER Note that NUMBER is always needed even if you did not use count in the resource In addition each of these namespace levels is a map allowing you to filter based on type and name The somewhat strange notation here of TYPE NAME NUMBER may imply that the inner resource index map is actually a list but it s not using the square bracket notation over the dotted notation TYPE NAME NUMBER is required here as an identifier cannot start with a number Some examples of multi level access are below To fetch all aws instance foo resource instances within the root module you can specify tfplan resources aws instance foo This would then be indexed by resource count index 0 1 2 and so on Note that as mentioned above these elements must be accessed using square bracket map notation so 0 1 2 and so on instead of dotted notation To fetch all aws instance resources within the root module you can specify tfplan resources aws instance This would be indexed from the names of each resource foo bar and so on with each of those maps containing instances indexed by resource count index as per above To fetch all resources within the root module irrespective of type use tfplan resources This is indexed by type as shown above with tfplan resources aws instance with names being the next level down and so on When resource targeting terraform cli commands plan resource targeting is in effect tfplan resources will only include the resources specified as targets for the run This may lead to unexpected outcomes if a policy expects a resource to be present in the plan To prohibit targeted runs altogether ensure tfrun target addrs terraform cloud docs policy enforcement sentinel import tfrun value target addrs is undefined or empty Further explanation of the namespace will be in the context of resources As mentioned when operating on data sources use the same syntax except with data in place of resources Value applied Value Type A string keyed map of values The applied value within the resource namespace namespace resources data sources contains a predicted representation of the resource s state post apply It s created by merging the pending resource s diff on top of the existing data from the resource s state if any The map is a complex representation of these values with data going as far down as needed to represent any state values such as maps lists and sets As an example given the following resource hcl resource null resource foo triggers foo bar The following policy would evaluate to true if the resource was in the diff python import tfplan main rule tfplan resources null resource foo 0 applied triggers foo is bar Note that some values will not be available in the applied state because they cannot be known until the plan is actually applied In Terraform 0 11 or earlier these values are represented by a placeholder the UUID value 74D93920 ED26 11E3 AC10 0800200C9A66 and in Terraform 0 12 or later they are undefined In either case you should instead use the computed value computed key within the diff namespace namespace resource diff to determine that a computed value will exist If a resource is being destroyed its applied value is omitted from the namespace and trying to fetch it will return undefined Value diff Value Type A map of diff namespaces namespace resource diff The diff value within the resource namespace namespace resources data sources contains the diff for a particular resource Each key within the map links to a diff namespace namespace resource diff for that particular key Note that unlike the applied value applied value this map is not complex the map is only 1 level deep with each key possibly representing a diff for a particular complex value within the resource See the below section for more details on the diff namespace in addition to usage examples Value destroy Value Type Boolean The destroy value within the resource namespace namespace resources data sources is true if a resource is being destroyed for any reason including cases where it s being deleted as part of a resource re creation in which case requires new value requires new will also be set As an example given the following resource hcl resource null resource foo triggers foo bar The following policy would evaluate to true when null resource foo is being destroyed python import tfplan main rule tfplan resources null resource foo 0 destroy Value requires new Value Type Boolean The requires new value within the resource namespace namespace resources data sources is true if the resource is still present in the configuration but must be replaced to satisfy its current diff Whenever requires new is true destroy value destroy is also true As an example given the following resource hcl resource null resource foo triggers foo bar The following policy would evaluate to true if one of the triggers in null resource foo was being changed python import tfplan main rule tfplan resources null resource foo 0 requires new Namespace Resource Diff The diff namespace is a namespace that represents the diff for a specific attribute within a resource For details on reading a particular attribute see the diff value diff value in the resource namespace namespace resources data sources Value computed Value Type Boolean The computed value within the diff namespace namespace resource diff is true if the resource key in question depends on another value that isn t yet known Typically that means the value it depends on belongs to a resource that either doesn t exist yet or is changing state in such a way as to affect the dependent value so that it can t be known until the apply is complete Keep in mind that when using computed with complex structures such as maps lists and sets it s sometimes necessary to test the count attribute for the structure versus a key within it depending on whether or not the diff has marked the whole structure as computed This is demonstrated in the example below Count keys are for maps and for lists and sets If you are having trouble determining the type of specific field within a resource contact the support team As an example given the following resource hcl resource null resource foo triggers foo bar resource null resource bar triggers foo id null resource foo id The following policy would evaluate to true if the id of null resource foo was currently not known such as when the resource is pending creation or is being deleted and re created python import tfplan main rule tfplan resources null resource bar 0 diff triggers computed Value new Value Type String The new value within the diff namespace namespace resource diff contains the new value of a changing attribute if the value is known at plan time new will be an empty string if the attribute s value is currently unknown For more details on detecting unknown values see computed value computed Note that this value is always a string regardless of the actual type of the value changing Type conversion ref sentinel type conversion within policy may be necessary to achieve the comparison needed ref sentinel type conversion https docs hashicorp com sentinel language values type conversion As an example given the following resource hcl resource null resource foo triggers foo bar The following policy would evaluate to true if the resource was in the diff and each of the concerned keys were changing to new values python import tfplan main rule tfplan resources null resource foo 0 diff triggers foo new is bar Value old Value Type String The old value within the diff namespace namespace resource diff contains the old value of a changing attribute Note that this value is always a string regardless of the actual type of the value changing Type conversion ref sentinel type conversion within policy may be necessary to achieve the comparison needed If the value did not exist in the previous state old will always be an empty string As an example given the following resource hcl resource null resource foo triggers foo baz If that resource was previously in config as hcl resource null resource foo triggers foo bar The following policy would evaluate to true python import tfplan main rule tfplan resources null resource foo 0 diff triggers foo old is bar
terraform Note This is documentation for the next version of the tfconfig Sentinel import designed specifically for Terraform 0 12 This import requires page title tfconfig v2 Imports Sentinel HCP Terraform example import tfconfig v2 as tfconfig The tfconfig v2 import provides access to a Terraform configuration Terraform 0 12 or higher and must currently be loaded by path using an alias
--- page_title: tfconfig/v2 - Imports - Sentinel - HCP Terraform description: The tfconfig/v2 import provides access to a Terraform configuration. --- -> **Note:** This is documentation for the next version of the `tfconfig` Sentinel import, designed specifically for Terraform 0.12. This import requires Terraform 0.12 or higher, and must currently be loaded by path, using an alias, example: `import "tfconfig/v2" as tfconfig`. # Import: tfconfig/v2 The `tfconfig/v2` import provides access to a Terraform configuration. The Terraform configuration is the set of `*.tf` files that are used to describe the desired infrastructure state. Policies using the `tfconfig` import can access all aspects of the configuration: providers, resources, data sources, modules, and variables. <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/policies.mdx' <!-- END: TFC:only name:pnp-callout --> Some use cases for `tfconfig` include: * **Organizational naming conventions**: requiring that configuration elements are named in a way that conforms to some organization-wide standard. * **Required inputs and outputs**: organizations may require a particular set of input variable names across all workspaces or may require a particular set of outputs for asset management purposes. * **Enforcing particular modules**: organizations may provide a number of "building block" modules and require that each workspace be built only from combinations of these modules. * **Enforcing particular providers or resources**: an organization may wish to require or prevent the use of providers and/or resources so that configuration authors cannot use alternative approaches to work around policy restrictions. The data in the `tfconfig/v2` import is sourced from the JSON configuration file that is generated by the [`terraform show -json`](/terraform/cli/commands/show#json-output) command. For more information on the file format, see the [JSON Output Format](/terraform/internals/json-format) page. ## Import Overview The `tfconfig/v2` import is structured as a series of _collections_, keyed as a specific format, such as resource address, module address, or a specifically-formatted provider key. ``` tfconfig/v2 ├── strip_index() (function) ├── providers │ └── (indexed by [module_address:]provider[.alias]) │ ├── provider_config_key (string) │ ├── name (string) │ ├── full_name (string) │ ├── alias (string) │ ├── module_address (string) │ ├── config (block expression representation) │ └── version_constraint (string) ├── resources │ └── (indexed by address) │ ├── address (string) │ ├── module_address (string) │ ├── mode (string) │ ├── type (string) │ ├── name (string) │ ├── provider_config_key (string) │ ├── provisioners (list) │ │ └── (ordered provisioners for this resource only) │ ├── config (block expression representation) │ ├── count (expression representation) │ ├── for_each (expression representation) │ └── depends_on (list of strings) ├── provisioners │ └── (indexed by resource_address:index) │ ├── resource_address (string) │ ├── type (string) │ ├── index (string) │ └── config (block expression representation) ├── variables │ └── (indexed by module_address:name) │ ├── module_address (string) │ ├── name (string) │ ├── default (value) │ └── description (string) ├── outputs │ └── (indexed by module_address:name) │ ├── module_address (string) │ ├── name (string) │ ├── sensitive (boolean) │ ├── value (expression representation) │ ├── description (string) │ └── depends_on (list of strings) └── module_calls └── (indexed by module_address:name) ├── module_address (string) ├── name (string) ├── source (string) ├── config (block expression representation) ├── count (expression representation) ├── depends_on (expression representation) ├── for_each (expression representation) └── version_constraint (string) ``` The collections are: * [`providers`](#the-providers-collection) - The configuration for all provider instances across all modules in the configuration. * [`resources`](#the-resources-collection) - The configuration of all resources across all modules in the configuration. * [`variables`](#the-variables-collection) - The configuration of all variable definitions across all modules in the configuration. * [`outputs`](#the-outputs-collection) - The configuration of all output definitions across all modules in the configuration. * [`module_calls`](#the-module_calls-collection) - The configuration of all module calls (individual [`module`](/terraform/language/modules) blocks) across all modules in the configuration. These collections are specifically designed to be used with the [`filter`](https://docs.hashicorp.com/sentinel/language/collection-operations#filter-expression) quantifier expression in Sentinel, so that one can collect a list of resources to perform policy checks on without having to write complex module or configuration traversal. As an example, the following code will return all `aws_instance` resource types within the configuration, regardless of what module they are in: ``` all_aws_instances = filter tfconfig.resources as _, r { r.mode is "managed" and r.type is "aws_instance" } ``` You can add specific attributes to the filter to narrow the search, such as the module address. The following code would return resources in a module named `foo` only: ``` all_aws_instances = filter tfconfig.resources as _, r { r.module_address is "module.foo" and r.mode is "managed" and r.type is "aws_instance" } ``` ### Address Differences Between `tfconfig`, `tfplan`, and `tfstate` This import deals with configuration before it is expanded into a resource graph by Terraform. As such, it is not possible to compute an index as the import is building its collections and computing addresses for resources and modules. As such, addresses found here may not always match the expanded addresses found in the [`tfplan/v2`](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfplan-v2) and [`tfstate/v2`](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfstate-v2) imports, specifically when [`count`](/terraform/language/resources#count-multiple-resource-instances-by-count) and [`for_each`](/terraform/language/resources#for_each-multiple-resource-instances-defined-by-a-map-or-set-of-strings), are used. As an example, consider a resource named `null_resource.foo` with a count of `2` located in a module named `bar`. While there will possibly be entries in the other imports for `module.bar.null_resource.foo[0]` and `module.bar.null_resource.foo[1]`, in `tfconfig/v2`, there will only be a `module.bar.null_resource.foo`. As mentioned in the start of this section, this is because configuration actually _defines_ this scaling, whereas _expansion_ actually happens when the resource graph is built, which happens as a natural part of the refresh and planning process. The `strip_index` helper function, found in this import, can assist in removing the indexes from addresses found in the `tfplan/v2` and `tfstate/v2` imports so that data from those imports can be used to reference data in this one. ## The `strip_index` Function The `strip_index` helper function can be used to remove indexes from addresses found in [`tfplan/v2`](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfplan-v2) and [`tfstate/v2`](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfstate-v2), by removing the indexes from each resource. This can be used to help facilitate cross-import lookups for data between plan, state, and config. ``` import "tfconfig/v2" as tfconfig import "tfplan/v2" as tfplan main = rule { all filter tfplan.resource_changes as _, rc { rc.mode is "managed" and rc.type is "aws_instance" } as _, rc { tfconfig.resources[tfconfig.strip_index(rc.address)].config.ami.constant_value is "ami-abcdefgh012345" } } ``` ## Expression Representations Most collections in this import will have one of two kinds of _expression representations_. This is a verbose format for expressing a (parsed) configuration value independent of the configuration source code, which is not 100% available to a policy check in HCP Terraform. ``` (expression representation) ├── constant_value (value) └── references (list of strings) ``` There are two major parts to an expression representation: * Any _strictly constant value_ is expressed as an expression with a `constant_value` field. * Any expression that requires some degree of evaluation to generate the final value - even if that value is known at plan time - is not expressed in configuration. Instead, any particular references that are made are added to the `references` field. More details on this field can be found in the [expression representation](/terraform/internals/json-format#expression-representation) section of the JSON output format documentation. For example, to determine if an output is based on a particular resource value, one could do: ``` import "tfconfig/v2" as tfconfig main = rule { tfconfig.outputs["instance_id"].value.references is ["aws_instance.foo"] } ``` -> **Note:** The representation does not account for complex interpolations or other expressions that combine constants with other expression data. For example, the partially constant data in `"foo${var.bar}"` would be lost. ### Block Expression Representation Expanding on the above, a multi-value expression representation (such as the kind found in a [`resources`](#the-resources-collection) collection element) is similar, but the root value is a keyed map of expression representations. This is repeated until a "scalar" expression value is encountered, ie: a field that is not a block in the resource's schema. ``` (block expression representation) └── (attribute key) ├── (child block expression representation) │ └── (...) ├── constant_value (value) └── references (list of strings) ``` As an example, one can validate expressions in an [`aws_instance`](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance) resource using the following: ``` import "tfconfig/v2" as tfconfig main = rule { tfconfig.resources["aws_instance.foo"].config.ami.constant_value is "ami-abcdefgh012345" } ``` Note that _nested blocks_, sometimes known as _sub-resources_, will be nested in configuration as a list of blocks (reflecting their ultimate nature as a list of objects). An example would be the `aws_instance` resource's [`ebs_block_device`](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance#ebs-ephemeral-and-root-block-devices) block: ``` import "tfconfig/v2" as tfconfig main = rule { tfconfig.resources["aws_instance.foo"].config.ebs_block_device[0].volume_size < 10 } ``` ## The `providers` Collection The `providers` collection is a collection representing the configurations of all provider instances across all modules in the configuration. This collection is indexed by an opaque key. This is currently `module_address:provider.alias`, the same value as found in the `provider_config_key` field. `module_address` and the colon delimiter are omitted for the root module. The `provider_config_key` field is also found in the `resources` collection and can be used to locate a provider that belongs to a configured resource. The fields in this collection are as follows: * `provider_config_key` - The opaque configuration key, used as the index key. * `name` - The name of the provider, ie: `aws`. * `full_name` - The fully-qualified name of the provider, e.g. `registry.terraform.io/hashicorp/aws`. * `alias` - The alias of the provider, ie: `east`. Empty for a default provider. * `module_address` - The address of the module this provider appears in. * `config` - A [block expression representation](#block-expression-representation) with provider configuration values. * `version_constraint` - The defined version constraint for this provider. ## The `resources` Collection The `resources` collection is a collection representing all of the resources found in all modules in the configuration. This collection is indexed by the resource address. The fields in this collection are as follows: * `address` - The resource address. This is the index of the collection. * `module_address` - The module address that this resource was found in. * `mode` - The resource mode, either `managed` (resources) or `data` (data sources). * `type` - The type of resource, ie: `null_resource` in `null_resource.foo`. * `name` - The name of the resource, ie: `foo` in `null_resource.foo`. * `provider_config_key` - The opaque configuration key that serves as the index of the [`providers`](#the-providers-collection) collection. * `provisioners` - The ordered list of provisioners for this resource. The syntax of the provisioners matches those found in the [`provisioners`](#the-provisioners-collection) collection, but is a list indexed by the order the provisioners show up in the resource. * `config` - The [block expression representation](#block-expression-representation) of the configuration values found in the resource. * `count` - The [expression data](#expression-representations) for the `count` value in the resource. * `for_each` - The [expression data](#expression-representations) for the `for_each` value in the resource. * `depends_on` - The contents of the `depends_on` config directive, which declares explicit dependencies for this resource. ## The `provisioners` Collection The `provisioners` collection is a collection of all of the provisioners found across all resources in the configuration. While normally bound to a resource in an ordered fashion, this collection allows for the filtering of provisioners within a single expression. This collection is indexed with a key following the format `resource_address:index`, with each field matching their respective field in the particular element below: * `resource_address`: The address of the resource that the provisioner was found in. This can be found in the [`resources`](#the-resources-collection) collection. * `type`: The provisioner type, ie: `local_exec`. * `index`: The provisioner index as it shows up in the resource provisioner order. * `config`: The [block expression representation](#block-expression-representation) of the configuration values in the provisioner. ## The `variables` Collection The `variables` collection is a collection of all variables across all modules in the configuration. Note that this tracks variable definitions, not values. See the [`tfplan/v2` `variables` collection](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfplan-v2#the-variables-collection) for variable values set within a plan. This collection is indexed by the key format `module_address:name`, with each field matching their respective name below. `module_address` and the colon delimiter are omitted for the root module. * `module_address` - The address of the module the variable was found in. * `name` - The name of the variable. * `default` - The defined default value of the variable. * `description` - The description of the variable. ## The `outputs` Collection The `outputs` collection is a collection of all outputs across all modules in the configuration. Note that this tracks variable definitions, not values. See the [`tfstate/v2` `outputs` collection](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfstate-v2#the-outputs-collection) for the final values of outputs set within a state. The [`tfplan/v2` `output_changes` collection](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfplan-v2#the-output_changes-collection) also contains a more complex collection of planned output changes. This collection is indexed by the key format `module_address:name`, with each field matching their respective name below. `module_address` and the colon delimiter are omitted for the root module. * `module_address` - The address of the module the output was found in. * `name` - The name of the output. * `sensitive` - Indicates whether or not the output was marked as [`sensitive`](/terraform/language/values/outputs#sensitive-suppressing-values-in-cli-output). * `value` - An [expression representation](#expression-representations) for the output. * `description` - The description of the output. * `depends_on` - A list of resource names that the output depends on. These are the hard-defined output dependencies as defined in the [`depends_on`](/terraform/language/values/outputs#depends_on-explicit-output-dependencies) field in an output declaration, not the dependencies that get derived from natural evaluation of the output expression (these can be found in the `references` field of the expression representation). ## The `module_calls` Collection The `module_calls` collection is a collection of all module declarations at all levels within the configuration. Note that this is the [`module`](/terraform/language/modules#calling-a-child-module) stanza in any particular configuration, and not the module itself. Hence, a declaration for `module.foo` would actually be declared in the root module, which would be represented by a blank field in `module_address`. This collection is indexed by the key format `module_address:name`, with each field matching their respective name below. `module_address` and the colon delimiter are omitted for the root module. * `module_address` - The address of the module the declaration was found in. * `name` - The name of the module. * `source` - The contents of the `source` field. * `config` - A [block expression representation](#block-expression-representation) for all parameter values sent to the module. * `count` - An [expression representation](#expression-representations) for the `count` field. * `depends_on`: An [expression representation](#expression-representations) for the `depends_on` field. * `for_each` - An [expression representation](#expression-representations) for the `for_each` field. * `version_constraint` - The string value found in the `version` field of the module declaration.
terraform
page title tfconfig v2 Imports Sentinel HCP Terraform description The tfconfig v2 import provides access to a Terraform configuration Note This is documentation for the next version of the tfconfig Sentinel import designed specifically for Terraform 0 12 This import requires Terraform 0 12 or higher and must currently be loaded by path using an alias example import tfconfig v2 as tfconfig Import tfconfig v2 The tfconfig v2 import provides access to a Terraform configuration The Terraform configuration is the set of tf files that are used to describe the desired infrastructure state Policies using the tfconfig import can access all aspects of the configuration providers resources data sources modules and variables BEGIN TFC only name pnp callout include tfc package callouts policies mdx END TFC only name pnp callout Some use cases for tfconfig include Organizational naming conventions requiring that configuration elements are named in a way that conforms to some organization wide standard Required inputs and outputs organizations may require a particular set of input variable names across all workspaces or may require a particular set of outputs for asset management purposes Enforcing particular modules organizations may provide a number of building block modules and require that each workspace be built only from combinations of these modules Enforcing particular providers or resources an organization may wish to require or prevent the use of providers and or resources so that configuration authors cannot use alternative approaches to work around policy restrictions The data in the tfconfig v2 import is sourced from the JSON configuration file that is generated by the terraform show json terraform cli commands show json output command For more information on the file format see the JSON Output Format terraform internals json format page Import Overview The tfconfig v2 import is structured as a series of collections keyed as a specific format such as resource address module address or a specifically formatted provider key tfconfig v2 strip index function providers indexed by module address provider alias provider config key string name string full name string alias string module address string config block expression representation version constraint string resources indexed by address address string module address string mode string type string name string provider config key string provisioners list ordered provisioners for this resource only config block expression representation count expression representation for each expression representation depends on list of strings provisioners indexed by resource address index resource address string type string index string config block expression representation variables indexed by module address name module address string name string default value description string outputs indexed by module address name module address string name string sensitive boolean value expression representation description string depends on list of strings module calls indexed by module address name module address string name string source string config block expression representation count expression representation depends on expression representation for each expression representation version constraint string The collections are providers the providers collection The configuration for all provider instances across all modules in the configuration resources the resources collection The configuration of all resources across all modules in the configuration variables the variables collection The configuration of all variable definitions across all modules in the configuration outputs the outputs collection The configuration of all output definitions across all modules in the configuration module calls the module calls collection The configuration of all module calls individual module terraform language modules blocks across all modules in the configuration These collections are specifically designed to be used with the filter https docs hashicorp com sentinel language collection operations filter expression quantifier expression in Sentinel so that one can collect a list of resources to perform policy checks on without having to write complex module or configuration traversal As an example the following code will return all aws instance resource types within the configuration regardless of what module they are in all aws instances filter tfconfig resources as r r mode is managed and r type is aws instance You can add specific attributes to the filter to narrow the search such as the module address The following code would return resources in a module named foo only all aws instances filter tfconfig resources as r r module address is module foo and r mode is managed and r type is aws instance Address Differences Between tfconfig tfplan and tfstate This import deals with configuration before it is expanded into a resource graph by Terraform As such it is not possible to compute an index as the import is building its collections and computing addresses for resources and modules As such addresses found here may not always match the expanded addresses found in the tfplan v2 terraform cloud docs policy enforcement sentinel import tfplan v2 and tfstate v2 terraform cloud docs policy enforcement sentinel import tfstate v2 imports specifically when count terraform language resources count multiple resource instances by count and for each terraform language resources for each multiple resource instances defined by a map or set of strings are used As an example consider a resource named null resource foo with a count of 2 located in a module named bar While there will possibly be entries in the other imports for module bar null resource foo 0 and module bar null resource foo 1 in tfconfig v2 there will only be a module bar null resource foo As mentioned in the start of this section this is because configuration actually defines this scaling whereas expansion actually happens when the resource graph is built which happens as a natural part of the refresh and planning process The strip index helper function found in this import can assist in removing the indexes from addresses found in the tfplan v2 and tfstate v2 imports so that data from those imports can be used to reference data in this one The strip index Function The strip index helper function can be used to remove indexes from addresses found in tfplan v2 terraform cloud docs policy enforcement sentinel import tfplan v2 and tfstate v2 terraform cloud docs policy enforcement sentinel import tfstate v2 by removing the indexes from each resource This can be used to help facilitate cross import lookups for data between plan state and config import tfconfig v2 as tfconfig import tfplan v2 as tfplan main rule all filter tfplan resource changes as rc rc mode is managed and rc type is aws instance as rc tfconfig resources tfconfig strip index rc address config ami constant value is ami abcdefgh012345 Expression Representations Most collections in this import will have one of two kinds of expression representations This is a verbose format for expressing a parsed configuration value independent of the configuration source code which is not 100 available to a policy check in HCP Terraform expression representation constant value value references list of strings There are two major parts to an expression representation Any strictly constant value is expressed as an expression with a constant value field Any expression that requires some degree of evaluation to generate the final value even if that value is known at plan time is not expressed in configuration Instead any particular references that are made are added to the references field More details on this field can be found in the expression representation terraform internals json format expression representation section of the JSON output format documentation For example to determine if an output is based on a particular resource value one could do import tfconfig v2 as tfconfig main rule tfconfig outputs instance id value references is aws instance foo Note The representation does not account for complex interpolations or other expressions that combine constants with other expression data For example the partially constant data in foo var bar would be lost Block Expression Representation Expanding on the above a multi value expression representation such as the kind found in a resources the resources collection collection element is similar but the root value is a keyed map of expression representations This is repeated until a scalar expression value is encountered ie a field that is not a block in the resource s schema block expression representation attribute key child block expression representation constant value value references list of strings As an example one can validate expressions in an aws instance https registry terraform io providers hashicorp aws latest docs resources instance resource using the following import tfconfig v2 as tfconfig main rule tfconfig resources aws instance foo config ami constant value is ami abcdefgh012345 Note that nested blocks sometimes known as sub resources will be nested in configuration as a list of blocks reflecting their ultimate nature as a list of objects An example would be the aws instance resource s ebs block device https registry terraform io providers hashicorp aws latest docs resources instance ebs ephemeral and root block devices block import tfconfig v2 as tfconfig main rule tfconfig resources aws instance foo config ebs block device 0 volume size 10 The providers Collection The providers collection is a collection representing the configurations of all provider instances across all modules in the configuration This collection is indexed by an opaque key This is currently module address provider alias the same value as found in the provider config key field module address and the colon delimiter are omitted for the root module The provider config key field is also found in the resources collection and can be used to locate a provider that belongs to a configured resource The fields in this collection are as follows provider config key The opaque configuration key used as the index key name The name of the provider ie aws full name The fully qualified name of the provider e g registry terraform io hashicorp aws alias The alias of the provider ie east Empty for a default provider module address The address of the module this provider appears in config A block expression representation block expression representation with provider configuration values version constraint The defined version constraint for this provider The resources Collection The resources collection is a collection representing all of the resources found in all modules in the configuration This collection is indexed by the resource address The fields in this collection are as follows address The resource address This is the index of the collection module address The module address that this resource was found in mode The resource mode either managed resources or data data sources type The type of resource ie null resource in null resource foo name The name of the resource ie foo in null resource foo provider config key The opaque configuration key that serves as the index of the providers the providers collection collection provisioners The ordered list of provisioners for this resource The syntax of the provisioners matches those found in the provisioners the provisioners collection collection but is a list indexed by the order the provisioners show up in the resource config The block expression representation block expression representation of the configuration values found in the resource count The expression data expression representations for the count value in the resource for each The expression data expression representations for the for each value in the resource depends on The contents of the depends on config directive which declares explicit dependencies for this resource The provisioners Collection The provisioners collection is a collection of all of the provisioners found across all resources in the configuration While normally bound to a resource in an ordered fashion this collection allows for the filtering of provisioners within a single expression This collection is indexed with a key following the format resource address index with each field matching their respective field in the particular element below resource address The address of the resource that the provisioner was found in This can be found in the resources the resources collection collection type The provisioner type ie local exec index The provisioner index as it shows up in the resource provisioner order config The block expression representation block expression representation of the configuration values in the provisioner The variables Collection The variables collection is a collection of all variables across all modules in the configuration Note that this tracks variable definitions not values See the tfplan v2 variables collection terraform cloud docs policy enforcement sentinel import tfplan v2 the variables collection for variable values set within a plan This collection is indexed by the key format module address name with each field matching their respective name below module address and the colon delimiter are omitted for the root module module address The address of the module the variable was found in name The name of the variable default The defined default value of the variable description The description of the variable The outputs Collection The outputs collection is a collection of all outputs across all modules in the configuration Note that this tracks variable definitions not values See the tfstate v2 outputs collection terraform cloud docs policy enforcement sentinel import tfstate v2 the outputs collection for the final values of outputs set within a state The tfplan v2 output changes collection terraform cloud docs policy enforcement sentinel import tfplan v2 the output changes collection also contains a more complex collection of planned output changes This collection is indexed by the key format module address name with each field matching their respective name below module address and the colon delimiter are omitted for the root module module address The address of the module the output was found in name The name of the output sensitive Indicates whether or not the output was marked as sensitive terraform language values outputs sensitive suppressing values in cli output value An expression representation expression representations for the output description The description of the output depends on A list of resource names that the output depends on These are the hard defined output dependencies as defined in the depends on terraform language values outputs depends on explicit output dependencies field in an output declaration not the dependencies that get derived from natural evaluation of the output expression these can be found in the references field of the expression representation The module calls Collection The module calls collection is a collection of all module declarations at all levels within the configuration Note that this is the module terraform language modules calling a child module stanza in any particular configuration and not the module itself Hence a declaration for module foo would actually be declared in the root module which would be represented by a blank field in module address This collection is indexed by the key format module address name with each field matching their respective name below module address and the colon delimiter are omitted for the root module module address The address of the module the declaration was found in name The name of the module source The contents of the source field config A block expression representation block expression representation for all parameter values sent to the module count An expression representation expression representations for the count field depends on An expression representation expression representations for the depends on field for each An expression representation expression representations for the for each field version constraint The string value found in the version field of the module declaration
terraform page title tfplan v2 Imports Sentinel HCP Terraform example import tfplan v2 as tfplan import designed specifically for Terraform 0 12 This import requires Note This is documentation for the next version of the tfplan Sentinel Terraform 0 12 or higher and must currently be loaded by path using an alias The tfplan v2 import provides access to a Terraform plan
--- page_title: tfplan/v2 - Imports - Sentinel - HCP Terraform description: The tfplan/v2 import provides access to a Terraform plan. --- -> **Note:** This is documentation for the next version of the `tfplan` Sentinel import, designed specifically for Terraform 0.12. This import requires Terraform 0.12 or higher, and must currently be loaded by path, using an alias, example: `import "tfplan/v2" as tfplan`. # Import: tfplan/v2 The `tfplan/v2` import provides access to a Terraform plan. A Terraform plan is the file created as a result of `terraform plan` and is the input to `terraform apply`. The plan represents the changes that Terraform needs to make to infrastructure to reach the desired state represented by the configuration. <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/policies.mdx' <!-- END: TFC:only name:pnp-callout --> In addition to the diff data available in the plan, there is a "planned state" that is available through this import, via the [`planned_values`](#the-planned_values-collection) collection. This collection presents the Terraform state as how it might look after the plan data is applied, but is not guaranteed to be the final state. The data in the `tfplan/v2` import is sourced from the JSON configuration file that is generated by the [`terraform show -json`](/terraform/cli/commands/show#json-output) command. For more information on the file format, see the [JSON Output Format](/terraform/internals/json-format) page. The entirety of the JSON output file is exposed as a Sentinel map via the [`raw`](#the-raw-collection) collection. This allows direct, low-level access to the JSON data, but should only be used in complex situations where the higher-level collections do not serve the purpose. ## Import Overview The `tfplan/v2` import is structured as a series of _collections_, keyed as a specific format depending on the collection. ``` tfplan/v2 ├── terraform_version (string) ├── variables │ └── (indexed by name) │ ├── name (string) │ └── value (value) ├── planned_values │ ├── outputs (tfstate/v2 outputs representation) │ └── resources (tfstate/v2 resources representation) ├── resource_changes │ └── (indexed by address[:deposed]) │ ├── address (string) │ ├── module_address (string) │ ├── mode (string) │ ├── type (string) │ ├── name (string) │ ├── index (float (number) or string) │ ├── provider_name (string) │ ├── deposed (string) │ └── change (change representation) ├── resource_drift │ └── (indexed by address[:deposed]) │ ├── address (string) │ ├── module_address (string) │ ├── mode (string) │ ├── type (string) │ ├── name (string) │ ├── index (float (number) or string) │ ├── provider_name (string) │ ├── deposed (string) │ └── change (change representation) ├── output_changes │ └── (indexed by name) │ ├── name (string) │ └── change (change representation) └── raw (map) ``` The collections are: * [`variables`](#the-variables-collection) - The values of variables that have been set in the plan itself. This collection only contains variables set in the root module. * [`planned_values`](#the-planned_values-collection) - The state representation of _planned values_, or an estimation of what the state will look like after the plan is applied. * [`resource_changes`](#the-resource_changes-and-resource_drift-collections) - The set of change operations for resources and data sources within this plan. * [`resource_drift`](#the-resource_changes-and-resource_drift-collections) - A description of the changes Terraform detected when it compared the most recent state to the prior saved state. * [`output_changes`](#the-output_changes-collection) - The changes to outputs within this plan. This collection only contains outputs set in the root module. * [`raw`](#the-raw-collection) - Access to the raw plan data as stored by HCP Terraform. These collections are specifically designed to be used with the [`filter`](https://docs.hashicorp.com/sentinel/language/collection-operations#filter-expression) quantifier expression in Sentinel, so that one can collect a list of resources to perform policy checks on without having to write complex discovery code. As an example, the following code will return all `aws_instance` resource changes, across all modules in the plan: ``` all_aws_instances = filter tfplan.resource_changes as _, rc { rc.mode is "managed" and rc.type is "aws_instance" } ``` You can add specific attributes to the filter to narrow the search, such as the module address, or the operation being performed. The following code would return resources in a module named `foo` only, and further narrow the search down to only resources that were being created: ``` all_aws_instances = filter tfplan.resource_changes as _, rc { rc.module_address is "module.foo" and rc.mode is "managed" and rc.type is "aws_instance" and rc.change.actions is ["create"] } ``` ### Change Representation Certain collections in this import contain a _change representation_, an object with details about changes to a particular entity, such as a resource (within the [`resource_changes`](#the-resource_changes-collection) collection), or output (within the [`output_changes`](#the-output_changes-collection) collection). ``` (change representation) ├── actions (list) ├── before (value, or map) ├── after (value, or map) └── after_unknown (boolean, or map of booleans) ``` This change representation contains the following fields: * `actions` - A list of actions being carried out for this change. The order is important, for example a regular replace operation is denoted by `["delete", "create"]`, but a [`create_before_destroy`](/terraform/language/meta-arguments/lifecycle#create_before_destroy) resource will have an operation order of `["create", "delete"]`. * `before` - The representation of the resource data object value before the action. For create-only actions, this is unset. For no-op actions, this value will be identical with `after`. * `after` - The representation of the resource data object value after the action. For delete-only actions, this is unset. For no-op actions, this value will be identical with `before`. Note that unknown values will not show up in this field. * `after_unknown` - A deep object of booleans that denotes any values that are unknown in a resource. These values were previously referred to as "computed" values. If the value cannot be found in this map, then its value should be available within `after`, so long as the operation supports it. #### Actions As mentioned above, actions show up within the `actions` field of a change representation and indicate the type of actions being performed as part of the change, and the order that they are being performed in. The current list of actions are as follows: * `create` - The action will create the associated entity. Depending on the order this appears in, the entity may be created alongside a copy of the entity before replacing it. * `read` - The action will read the associated entity. In practice, seeing this change type should be rare, as reads generally happen before a plan is executed (usually during a refresh). * `update` - The action will update the associated entity in a way that alters its state in some way. * `delete` - The action will remove the associated entity, deleting any applicable state and associated real resources or infrastructure. * `no-op` - No action will be performed on the associated entity. The `actions` field is a list, as some real-world actions are actually a composite of more than one primitive action. At this point in time, this is generally only applicable to resource replacement, in which the following action orders apply: * **Normal replacement:** `["delete", "create"]` - Applies to default lifecycle configurations. * **Create-before-destroy:** `["create", "delete"]` - Applies when [`create_before_destroy`](/terraform/language/meta-arguments/lifecycle#create_before_destroy) is used in a lifecycle configuration. Note that, in most situations, the plan will list all "changes", including no-op changes. This makes filtering on change type crucial to the accurate selection of data if you are concerned with the state change of a particular resource. To filter on a change type, use exact list comparison. For example, the following example from the [Import Overview](#import-overview) filters on exactly the resources being created _only_: ``` all_aws_instances = filter tfplan.resource_changes as _, rc { rc.module_address is "module.foo" and rc.mode is "managed" and rc.type is "aws_instance" and rc.change.actions is ["create"] } ``` #### `before`, `after`, and `after_unknown` The exact attribute changes for a particular operation are outlined in the `before` and `after` attributes. Depending on the entity being operated on, this will either be a map (as with [`resource_changes`](#the-resource_changes-collection)) or a singular value (as with [`output_changes`](#the-output_changes-collection)). What you can expect in these fields varies depending on the operation: * For fresh create operations, `before` will generally be `null`, and `after` will contain the data you can expect to see after the change. * For full delete operations, this will be reversed - `before` will contain data, and `after` will be `null`. * Update or replace operations will have data in both fields relevant to their states before and after the operation. * No-op operations should have identical data in `before` and `after`. For resources, if a field cannot be found in `after`, it generally means one of two things: * The attribute does not exist in the resource schema. Generally, known attributes that do not have a value will show up as `null` or otherwise empty in `after`. * The attribute is _unknown_, that is, it was unable to be determined at plan time and will only be available after apply-time values have been able to be calculated. In the latter case, there should be a value for the particular attribute in `after_unknown`, which can be checked to assert that the value is indeed unknown, versus invalid: ``` import "tfplan/v2" as tfplan no_unknown_amis = rule { all filter tfplan.resource_changes as _, rc { rc.module_address is "module.foo" and rc.mode is "managed" and rc.type is "aws_instance" and rc.change.actions is ["create"] } as _, rc { rc.change.after_unknown.ami else false is false } } ``` For output changes, `after_unknown` will simply be `true` if the value won't be known until the plan is applied. ## The `terraform_version` Value The top-level `terraform_version` value in this import gives the Terraform version that made the plan. This can be used to do version validation. ``` import "tfplan/v2" as tfplan import "strings" v = strings.split(tfplan.terraform_version, ".") version_major = int(v[1]) version_minor = int(v[2]) main = rule { version_major is 12 and version_minor >= 19 } ``` -> **NOTE:** The above example will give errors when working with pre-release versions (example: `0.12.0beta1`). Future versions of this import will include helpers to assist with processing versions that will account for these kinds of exceptions. ## The `variables` Collection The `variables` collection is a collection of the variables set in the root module when creating the plan. This collection is indexed on the name of the variable. The valid values are: * `name` - The name of the variable, also used as the collection key. * `value` - The value of the variable assigned during the plan. ## The `planned_values` Collection The `planned_values` collection is a special collection in that it contains two fields that alias to state collections with the _planned_ state set. This is the best prediction of what the state will look like after the plan is executed. The two fields are: * `outputs` - The prediction of what output values will look like after the state is applied. For more details on the structure of this collection, see the [`outputs`](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfstate-v2#the-outputs-collection) collection in the [`tfstate/v2`](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfstate-v2) documentation. * `resources` - The prediction of what resource values will look like after the state is applied. For more details on the structure of this collection, see the [`resources`](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfstate-v2#the-resources-collection) collection in the [`tfstate/v2`](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfstate-v2) documentation. -> **NOTE:** Unknown values are omitted from the `planned_values` state representations, regardless of whether or not they existed before. Use [`resource_changes`](#the-resource_changes-collection) if awareness of unknown data is important. ## The `resource_changes` and `resource_drift` Collections The `resource_changes` and `resource_drift` collections are a set of change operations for resources and data sources within this plan. The `resource_drift` collection provides a description of the changes Terraform detected when it compared the most recent state to the prior saved state. The `resource_changes` collection includes all resources that have been found in the configuration and state, regardless of whether or not they are changing. ~> When [resource targeting](/terraform/cli/commands/plan#resource-targeting) is in effect, the `resource_changes` collection will only include the resources specified as targets for the run. This may lead to unexpected outcomes if a policy expects a resource to be present in the plan. To prohibit targeted runs altogether, ensure [`tfrun.target_addrs`](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfrun#value-target_addrs) is undefined or empty. This collection is indexed on the complete resource address as the key. If `deposed` is non-empty, it is appended to the end, and may look something like `aws_instance.foo:deposed-abc123`. An element contains the following fields: * `address` - The absolute resource address - also the key for the collection's index, if `deposed` is empty. * `module_address` - The module portion of the absolute resource address. * `mode` - The resource mode, either `managed` (resources) or `data` (data sources). * `type` - The resource type, example: `aws_instance` for `aws_instance.foo`. * `name` - The resource name, example: `foo` for `aws_instance.foo`. * `index` - The resource index. Can be either a number or a string. * `provider_name` - The name of the provider this resource belongs to. This allows the provider to be interpreted unambiguously in the unusual situation where a provider offers a resource type whose name does not start with its own name, such as the `googlebeta` provider offering `google_compute_instance`. -> **Note:** Starting with Terraform 0.13, the `provider_name` field contains the _full_ source address to the provider in the Terraform Registry. Example: `registry.terraform.io/hashicorp/null` for the null provider. * `deposed` - An identifier used during replacement operations, and can be used to identify the exact resource being replaced in state. * `change` - The data describing the change that will be made to this resource. For more details, see [Change Representation](#change-representation). ## The `output_changes` Collection The `output_changes` collection is a collection of the change operations for outputs within this plan. Only outputs for the root module are included. This collection is indexed by the name of the output. The fields in a collection value are below: * `name` - The name of the output, also the index key. * `change` - The data describing the change that will be made to this output. For more details, see [Change Representation](#change-representation). ## The `raw` Collection The `raw` collection exposes the raw, unprocessed plan data, direct from the data stored by HCP Terraform. This is the same data that is produced by [`terraform show -json`](/terraform/cli/commands/show#json-output) on the plan file for the run this policy check is attached to. Use of this data is only recommended in expert situations where the data the collections present may not exactly serve the needs of the policy. For more information on the file format, see the [JSON Output Format](/terraform/internals/json-format) page. -> **NOTE:** Although designed to be relatively stable, the actual makeup for the JSON output format is a Terraform CLI concern and as such not managed by HCP Terraform. Use at your own risk, follow the [Terraform CLI project](https://github.com/hashicorp/terraform), and watch the file format documentation for any changes.
terraform
page title tfplan v2 Imports Sentinel HCP Terraform description The tfplan v2 import provides access to a Terraform plan Note This is documentation for the next version of the tfplan Sentinel import designed specifically for Terraform 0 12 This import requires Terraform 0 12 or higher and must currently be loaded by path using an alias example import tfplan v2 as tfplan Import tfplan v2 The tfplan v2 import provides access to a Terraform plan A Terraform plan is the file created as a result of terraform plan and is the input to terraform apply The plan represents the changes that Terraform needs to make to infrastructure to reach the desired state represented by the configuration BEGIN TFC only name pnp callout include tfc package callouts policies mdx END TFC only name pnp callout In addition to the diff data available in the plan there is a planned state that is available through this import via the planned values the planned values collection collection This collection presents the Terraform state as how it might look after the plan data is applied but is not guaranteed to be the final state The data in the tfplan v2 import is sourced from the JSON configuration file that is generated by the terraform show json terraform cli commands show json output command For more information on the file format see the JSON Output Format terraform internals json format page The entirety of the JSON output file is exposed as a Sentinel map via the raw the raw collection collection This allows direct low level access to the JSON data but should only be used in complex situations where the higher level collections do not serve the purpose Import Overview The tfplan v2 import is structured as a series of collections keyed as a specific format depending on the collection tfplan v2 terraform version string variables indexed by name name string value value planned values outputs tfstate v2 outputs representation resources tfstate v2 resources representation resource changes indexed by address deposed address string module address string mode string type string name string index float number or string provider name string deposed string change change representation resource drift indexed by address deposed address string module address string mode string type string name string index float number or string provider name string deposed string change change representation output changes indexed by name name string change change representation raw map The collections are variables the variables collection The values of variables that have been set in the plan itself This collection only contains variables set in the root module planned values the planned values collection The state representation of planned values or an estimation of what the state will look like after the plan is applied resource changes the resource changes and resource drift collections The set of change operations for resources and data sources within this plan resource drift the resource changes and resource drift collections A description of the changes Terraform detected when it compared the most recent state to the prior saved state output changes the output changes collection The changes to outputs within this plan This collection only contains outputs set in the root module raw the raw collection Access to the raw plan data as stored by HCP Terraform These collections are specifically designed to be used with the filter https docs hashicorp com sentinel language collection operations filter expression quantifier expression in Sentinel so that one can collect a list of resources to perform policy checks on without having to write complex discovery code As an example the following code will return all aws instance resource changes across all modules in the plan all aws instances filter tfplan resource changes as rc rc mode is managed and rc type is aws instance You can add specific attributes to the filter to narrow the search such as the module address or the operation being performed The following code would return resources in a module named foo only and further narrow the search down to only resources that were being created all aws instances filter tfplan resource changes as rc rc module address is module foo and rc mode is managed and rc type is aws instance and rc change actions is create Change Representation Certain collections in this import contain a change representation an object with details about changes to a particular entity such as a resource within the resource changes the resource changes collection collection or output within the output changes the output changes collection collection change representation actions list before value or map after value or map after unknown boolean or map of booleans This change representation contains the following fields actions A list of actions being carried out for this change The order is important for example a regular replace operation is denoted by delete create but a create before destroy terraform language meta arguments lifecycle create before destroy resource will have an operation order of create delete before The representation of the resource data object value before the action For create only actions this is unset For no op actions this value will be identical with after after The representation of the resource data object value after the action For delete only actions this is unset For no op actions this value will be identical with before Note that unknown values will not show up in this field after unknown A deep object of booleans that denotes any values that are unknown in a resource These values were previously referred to as computed values If the value cannot be found in this map then its value should be available within after so long as the operation supports it Actions As mentioned above actions show up within the actions field of a change representation and indicate the type of actions being performed as part of the change and the order that they are being performed in The current list of actions are as follows create The action will create the associated entity Depending on the order this appears in the entity may be created alongside a copy of the entity before replacing it read The action will read the associated entity In practice seeing this change type should be rare as reads generally happen before a plan is executed usually during a refresh update The action will update the associated entity in a way that alters its state in some way delete The action will remove the associated entity deleting any applicable state and associated real resources or infrastructure no op No action will be performed on the associated entity The actions field is a list as some real world actions are actually a composite of more than one primitive action At this point in time this is generally only applicable to resource replacement in which the following action orders apply Normal replacement delete create Applies to default lifecycle configurations Create before destroy create delete Applies when create before destroy terraform language meta arguments lifecycle create before destroy is used in a lifecycle configuration Note that in most situations the plan will list all changes including no op changes This makes filtering on change type crucial to the accurate selection of data if you are concerned with the state change of a particular resource To filter on a change type use exact list comparison For example the following example from the Import Overview import overview filters on exactly the resources being created only all aws instances filter tfplan resource changes as rc rc module address is module foo and rc mode is managed and rc type is aws instance and rc change actions is create before after and after unknown The exact attribute changes for a particular operation are outlined in the before and after attributes Depending on the entity being operated on this will either be a map as with resource changes the resource changes collection or a singular value as with output changes the output changes collection What you can expect in these fields varies depending on the operation For fresh create operations before will generally be null and after will contain the data you can expect to see after the change For full delete operations this will be reversed before will contain data and after will be null Update or replace operations will have data in both fields relevant to their states before and after the operation No op operations should have identical data in before and after For resources if a field cannot be found in after it generally means one of two things The attribute does not exist in the resource schema Generally known attributes that do not have a value will show up as null or otherwise empty in after The attribute is unknown that is it was unable to be determined at plan time and will only be available after apply time values have been able to be calculated In the latter case there should be a value for the particular attribute in after unknown which can be checked to assert that the value is indeed unknown versus invalid import tfplan v2 as tfplan no unknown amis rule all filter tfplan resource changes as rc rc module address is module foo and rc mode is managed and rc type is aws instance and rc change actions is create as rc rc change after unknown ami else false is false For output changes after unknown will simply be true if the value won t be known until the plan is applied The terraform version Value The top level terraform version value in this import gives the Terraform version that made the plan This can be used to do version validation import tfplan v2 as tfplan import strings v strings split tfplan terraform version version major int v 1 version minor int v 2 main rule version major is 12 and version minor 19 NOTE The above example will give errors when working with pre release versions example 0 12 0beta1 Future versions of this import will include helpers to assist with processing versions that will account for these kinds of exceptions The variables Collection The variables collection is a collection of the variables set in the root module when creating the plan This collection is indexed on the name of the variable The valid values are name The name of the variable also used as the collection key value The value of the variable assigned during the plan The planned values Collection The planned values collection is a special collection in that it contains two fields that alias to state collections with the planned state set This is the best prediction of what the state will look like after the plan is executed The two fields are outputs The prediction of what output values will look like after the state is applied For more details on the structure of this collection see the outputs terraform cloud docs policy enforcement sentinel import tfstate v2 the outputs collection collection in the tfstate v2 terraform cloud docs policy enforcement sentinel import tfstate v2 documentation resources The prediction of what resource values will look like after the state is applied For more details on the structure of this collection see the resources terraform cloud docs policy enforcement sentinel import tfstate v2 the resources collection collection in the tfstate v2 terraform cloud docs policy enforcement sentinel import tfstate v2 documentation NOTE Unknown values are omitted from the planned values state representations regardless of whether or not they existed before Use resource changes the resource changes collection if awareness of unknown data is important The resource changes and resource drift Collections The resource changes and resource drift collections are a set of change operations for resources and data sources within this plan The resource drift collection provides a description of the changes Terraform detected when it compared the most recent state to the prior saved state The resource changes collection includes all resources that have been found in the configuration and state regardless of whether or not they are changing When resource targeting terraform cli commands plan resource targeting is in effect the resource changes collection will only include the resources specified as targets for the run This may lead to unexpected outcomes if a policy expects a resource to be present in the plan To prohibit targeted runs altogether ensure tfrun target addrs terraform cloud docs policy enforcement sentinel import tfrun value target addrs is undefined or empty This collection is indexed on the complete resource address as the key If deposed is non empty it is appended to the end and may look something like aws instance foo deposed abc123 An element contains the following fields address The absolute resource address also the key for the collection s index if deposed is empty module address The module portion of the absolute resource address mode The resource mode either managed resources or data data sources type The resource type example aws instance for aws instance foo name The resource name example foo for aws instance foo index The resource index Can be either a number or a string provider name The name of the provider this resource belongs to This allows the provider to be interpreted unambiguously in the unusual situation where a provider offers a resource type whose name does not start with its own name such as the googlebeta provider offering google compute instance Note Starting with Terraform 0 13 the provider name field contains the full source address to the provider in the Terraform Registry Example registry terraform io hashicorp null for the null provider deposed An identifier used during replacement operations and can be used to identify the exact resource being replaced in state change The data describing the change that will be made to this resource For more details see Change Representation change representation The output changes Collection The output changes collection is a collection of the change operations for outputs within this plan Only outputs for the root module are included This collection is indexed by the name of the output The fields in a collection value are below name The name of the output also the index key change The data describing the change that will be made to this output For more details see Change Representation change representation The raw Collection The raw collection exposes the raw unprocessed plan data direct from the data stored by HCP Terraform This is the same data that is produced by terraform show json terraform cli commands show json output on the plan file for the run this policy check is attached to Use of this data is only recommended in expert situations where the data the collections present may not exactly serve the needs of the policy For more information on the file format see the JSON Output Format terraform internals json format page NOTE Although designed to be relatively stable the actual makeup for the JSON output format is a Terraform CLI concern and as such not managed by HCP Terraform Use at your own risk follow the Terraform CLI project https github com hashicorp terraform and watch the file format documentation for any changes
terraform The tfstate import provides access to a Terraform state Warning The tfstate import is now deprecated and will be permanently removed in August 2025 page title tfstate Imports Sentinel HCP Terraform Import tfstate We recommend that you start using the updated tfstate v2 terraform cloud docs policy enforcement sentinel import tfstate v2 import as soon as possible to avoid disruptions The tfstate v2 import offers improved functionality and is designed to better support your policy enforcement needs
--- page_title: tfstate - Imports - Sentinel - HCP Terraform description: The tfstate import provides access to a Terraform state. --- # Import: tfstate ~> **Warning:** The `tfstate` import is now deprecated and will be permanently removed in August 2025. We recommend that you start using the updated [tfstate/v2](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfstate-v2) import as soon as possible to avoid disruptions. The `tfstate/v2` import offers improved functionality and is designed to better support your policy enforcement needs. The `tfstate` import provides access to the Terraform state. <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/policies.mdx' <!-- END: TFC:only name:pnp-callout --> The _state_ is the data that Terraform has recorded about a workspace at a particular point in its lifecycle, usually after an apply. You can read more general information about how Terraform uses state [here][ref-tf-state]. [ref-tf-state]: /terraform/language/state -> **Note:** Since HCP Terraform currently only supports policy checks at plan time, the usefulness of this import is somewhat limited, as it will usually give you the state _prior_ to the plan the policy check is currently being run for. Depending on your needs, you may find the [`applied`](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfplan#value-applied) collection in `tfplan` more useful, which will give you a _predicted_ state by applying plan data to the data found here. The one exception to this rule is _data sources_, which will always give up to date data here, as long as the data source could be evaluated at plan time. ## Namespace Overview The following is a tree view of the import namespace. For more detail on a particular part of the namespace, see below. -> Note that the root-level alias keys shown here (`data`, `outputs`, `path`, and `resources`) are shortcuts to a [module namespace](#namespace-module) scoped to the root module. For more details, see the section on [root namespace aliases](#root-namespace-aliases). ``` tfstate ├── module() (function) │ └── (module namespace) │ ├── path ([]string) │ ├── data │ │ └── TYPE.NAME[NUMBER] │ │ ├── attr (map of keys) │ │ ├── depends_on ([]string) │ │ ├── id (string) │ │ └── tainted (boolean) │ ├── outputs (root module only in TF 0.12 or later) │ │ └── NAME │ │ ├── sensitive (bool) │ │ ├── type (string) │ │ └── value (value) │ └── resources │ └── TYPE.NAME[NUMBER] │ ├── attr (map of keys) │ ├── depends_on ([]string) │ ├── id (string) │ └── tainted (boolean) │ ├── module_paths ([][]string) ├── terraform_version (string) │ ├── data (root module alias) ├── outputs (root module alias) ├── path (root module alias) └── resources (root module alias) ``` ## Namespace: Root The root-level namespace consists of the values and functions documented below. In addition to this, the root-level `data`, `outputs`, `path`, and `resources` keys alias to their corresponding namespaces or values within the [module namespace](#namespace-module). ### Function: `module()` ``` module = func(ADDR) ``` * **Return Type:** A [module namespace](#namespace-module). The `module()` function in the [root namespace](#namespace-root) returns the [module namespace](#namespace-module) for a particular module address. The address must be a list and is the module address, split on the period (`.`), excluding the root module. Hence, a module with an address of simply `foo` (or `root.foo`) would be `["foo"]`, and a module within that (so address `foo.bar`) would be read as `["foo", "bar"]`. [`null`][ref-null] is returned if a module address is invalid, or if the module is not present in the state. [ref-null]: https://docs.hashicorp.com/sentinel/language/spec#null As an example, given the following module block: ```hcl module "foo" { # ... } ``` If the module contained the following content: ```hcl resource "null_resource" "foo" { triggers = { foo = "bar" } } ``` The following policy would evaluate to `true` if the resource was present in the state: ```python import "tfstate" main = rule { tfstate.module(["foo"]).resources.null_resource.foo[0].attr.triggers.foo is "bar" } ``` ### Value: `module_paths` * **Value Type:** List of a list of strings. The `module_paths` value within the [root namespace](#namespace-root) is a list of all of the modules within the Terraform state at plan-time. Modules not present in the state will not be present here, even if they are present in the configuration or the diff. This data is represented as a list of a list of strings, with the inner list being the module address, split on the period (`.`). The root module is included in this list, represented as an empty inner list, as long as it is present in state. As an example, if the following module block was present within a Terraform configuration: ```hcl module "foo" { # ... } ``` The value of `module_paths` would be: ``` [ [], ["foo"], ] ``` And the following policy would evaluate to `true`: ```python import "tfstate" main = rule { tfstate.module_paths contains ["foo"] } ``` -> Note the above example only applies if the module is present in the state. #### Iterating Through Modules Iterating through all modules to find particular resources can be useful. This [example][iterate-over-modules] shows how to use `module_paths` with the [`module()` function](#function-module-) to find all resources of a particular type from all modules using the `tfplan` import. By changing `tfplan` in this function to `tfstate`, you could make a similar function find all resources of a specific type in the current state. [iterate-over-modules]: /terraform/cloud-docs/policy-enforcement/sentinel#sentinel-imports ### Value: `terraform_version` * **Value Type:** String. The `terraform_version` value within the [root namespace](#namespace-root) represents the version of Terraform in use when the state was saved. This can be used to enforce a specific version of Terraform in a policy check. As an example, the following policy would evaluate to `true` as long as the state was made with a version of Terraform in the 0.11.x series, excluding any pre-release versions (example: `-beta1` or `-rc1`): ```python import "tfstate" main = rule { tfstate.terraform_version matches "^0\\.11\\.\\d+$" } ``` -> **NOTE:** This value is also available via the [`tfplan`](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfplan) import, which will be more current when a policy check is run against a plan. It's recommended you use the value in `tfplan` until HCP Terraform supports policy checks in other stages of the workspace lifecycle. See the [`terraform_version`][import-tfplan-terraform-version] reference within the `tfplan` import for more details. [import-tfplan-terraform-version]: /terraform/cloud-docs/policy-enforcement/sentinel/import/tfplan#value-terraform_version ## Namespace: Module The **module namespace** can be loaded by calling [`module()`](#function-module-) for a particular module. It can be used to load the following child namespaces, in addition to the values documented below: * `data` - Loads the [resource namespace](#namespace-resources-data-sources), filtered against data sources. * `outputs` - Loads the [output namespace](#namespace-outputs), which supply the outputs present in this module's state. Note that with Terraform 0.12 or later, this value is only available for the root namespace. * `resources` - Loads the [resource namespace](#namespace-resources-data-sources), filtered against resources. ### Root Namespace Aliases The root-level `data`, `outputs`, and `resources` keys both alias to their corresponding namespaces within the module namespace, loaded for the root module. They are the equivalent of running `module([]).KEY`. ### Value: `path` * **Value Type:** List of strings. The `path` value within the [module namespace](#namespace-module) contains the path of the module that the namespace represents. This is represented as a list of strings. As an example, if the following module block was present within a Terraform configuration: ```hcl module "foo" { # ... } ``` The following policy would evaluate to `true`, _only_ if the module was present in the state: ```python import "tfstate" main = rule { tfstate.module(["foo"]).path contains "foo" } ``` ## Namespace: Resources/Data Sources The **resource namespace** is a namespace _type_ that applies to both resources (accessed by using the `resources` namespace key) and data sources (accessed using the `data` namespace key). Accessing an individual resource or data source within each respective namespace can be accomplished by specifying the type, name, and resource number (as if the resource or data source had a `count` value in it) in the syntax `[resources|data].TYPE.NAME[NUMBER]`. Note that NUMBER is always needed, even if you did not use `count` in the resource. In addition, each of these namespace levels is a map, allowing you to filter based on type and name. -> The (somewhat strange) notation here of `TYPE.NAME[NUMBER]` may imply that the inner resource index map is actually a list, but it's not - using the square bracket notation over the dotted notation (`TYPE.NAME.NUMBER`) is required here as an identifier cannot start with number. Some examples of multi-level access are below: * To fetch all `aws_instance.foo` resource instances within the root module, you can specify `tfstate.resources.aws_instance.foo`. This would then be indexed by resource count index (`0`, `1`, `2`, and so on). Note that as mentioned above, these elements must be accessed using square-bracket map notation (so `[0]`, `[1]`, `[2]`, and so on) instead of dotted notation. * To fetch all `aws_instance` resources within the root module, you can specify `tfstate.resources.aws_instance`. This would be indexed from the names of each resource (`foo`, `bar`, and so on), with each of those maps containing instances indexed by resource count index as per above. * To fetch all resources within the root module, irrespective of type, use `tfstate.resources`. This is indexed by type, as shown above with `tfstate.resources.aws_instance`, with names being the next level down, and so on. Further explanation of the namespace will be in the context of resources. As mentioned, when operating on data sources, use the same syntax, except with `data` in place of `resources`. ### Value: `attr` * **Value Type:** A string-keyed map of values. The `attr` value within the [resource namespace](#namespace-resources-data-sources) is a direct mapping to the state of the resource. The map is a complex representation of these values with data going as far down as needed to represent any state values such as maps, lists, and sets. As an example, given the following resource: ```hcl resource "null_resource" "foo" { triggers = { foo = "bar" } } ``` The following policy would evaluate to `true` if the resource was in the state: ```python import "tfstate" main = rule { tfstate.resources.null_resource.foo[0].attr.triggers.foo is "bar" } ``` ### Value: `depends_on` * **Value Type:** A list of strings. The `depends_on` value within the [resource namespace](#namespace-resources-data-sources) contains the dependencies for the resource. This is a list of full resource addresses, relative to the module (example: `null_resource.foo`). As an example, given the following resources: ```hcl resource "null_resource" "foo" { triggers = { foo = "bar" } } resource "null_resource" "bar" { # ... depends_on = [ "null_resource.foo", ] } ``` The following policy would evaluate to `true` if the resource was in the state: ```python import "tfstate" main = rule { tfstate.resources.null_resource.bar[0].depends_on contains "null_resource.foo" } ``` ### Value: `id` * **Value Type:** String. The `id` value within the [resource namespace](#namespace-resources-data-sources) contains the id of the resource. -> **NOTE:** The example below uses a _data source_ here because the [`null_data_source`][ref-tf-null-data-source] data source gives a static ID, which makes documenting the example easier. As previously mentioned, data sources share the same namespace as resources, but need to be loaded with the `data` key. For more information, see the [synopsis](#namespace-resources-data-sources) for the namespace itself. [ref-tf-null-data-source]: https://registry.terraform.io/providers/hashicorp/null/latest/docs/data-sources/data_source As an example, given the following data source: ```hcl data "null_data_source" "foo" { # ... } ``` The following policy would evaluate to `true`: ```python import "tfstate" main = rule { tfstate.data.null_data_source.foo[0].id is "static" } ``` ### Value: `tainted` * **Value Type:** Boolean. The `tainted` value within the [resource namespace](#namespace-resources-data-sources) is `true` if the resource is marked as tainted in Terraform state. As an example, given the following resource: ```hcl resource "null_resource" "foo" { triggers = { foo = "bar" } } ``` The following policy would evaluate to `true`, if the resource was marked as tainted in the state: ```python import "tfstate" main = rule { tfstate.resources.null_resource.foo[0].tainted } ``` ## Namespace: Outputs The **output namespace** represents all of the outputs present within a [module](#namespace-module). Outputs are present in a state if they were saved during a previous apply, or if they were updated with known values during the pre-plan refresh. **With Terraform 0.11 or earlier** this can be used to fetch both the outputs of the root module, and the outputs of any module in the state below the root. This makes it possible to see outputs that have not been threaded to the root module. **With Terraform 0.12 or later** outputs are available in the top-level (root module) namespace only and not accessible within submodules. This namespace is indexed by output name. ### Value: `sensitive` * **Value Type:** Boolean. The `sensitive` value within the [output namespace](#namespace-outputs) is `true` when the output has been [marked as sensitive][ref-tf-sensitive-outputs]. [ref-tf-sensitive-outputs]: /terraform/language/values/outputs#sensitive-suppressing-values-in-cli-output As an example, given the following output: ```hcl output "foo" { sensitive = true value = "bar" } ``` The following policy would evaluate to `true`: ```python import "tfstate" main = rule { tfstate.outputs.foo.sensitive } ``` ### Value: `type` * **Value Type:** String. The `type` value within the [output namespace](#namespace-outputs) gives the output's type. This will be one of `string`, `list`, or `map`. These are currently the only types available for outputs in Terraform. As an example, given the following output: ```hcl output "string" { value = "foo" } output "list" { value = [ "foo", "bar", ] } output "map" { value = { foo = "bar" } } ``` The following policy would evaluate to `true`: ```python import "tfstate" type_string = rule { tfstate.outputs.string.type is "string" } type_list = rule { tfstate.outputs.list.type is "list" } type_map = rule { tfstate.outputs.map.type is "map" } main = rule { type_string and type_list and type_map } ``` ### Value: `value` * **Value Type:** String, list, or map. The `value` value within the [output namespace](#namespace-outputs) is the value of the output in question. Note that the only valid primitive output type in Terraform is currently a string, which means that any int, float, or boolean value will need to be converted before it can be used in comparison. This does not apply to primitives within maps and lists, which will be their original types. As an example, given the following output blocks: ```hcl output "foo" { value = "bar" } output "number" { value = "42" } output "map" { value = { foo = "bar" number = 42 } } ``` The following policy would evaluate to `true`: ```python import "tfstate" value_foo = rule { tfstate.outputs.foo.value is "bar" } value_number = rule { int(tfstate.outputs.number.value) is 42 } value_map_string = rule { tfstate.outputs.map.value["foo"] is "bar" } value_map_int = rule { tfstate.outputs.map.value["number"] is 42 } main = rule { value_foo and value_number and value_map_string and value_map_int } ```
terraform
page title tfstate Imports Sentinel HCP Terraform description The tfstate import provides access to a Terraform state Import tfstate Warning The tfstate import is now deprecated and will be permanently removed in August 2025 We recommend that you start using the updated tfstate v2 terraform cloud docs policy enforcement sentinel import tfstate v2 import as soon as possible to avoid disruptions The tfstate v2 import offers improved functionality and is designed to better support your policy enforcement needs The tfstate import provides access to the Terraform state BEGIN TFC only name pnp callout include tfc package callouts policies mdx END TFC only name pnp callout The state is the data that Terraform has recorded about a workspace at a particular point in its lifecycle usually after an apply You can read more general information about how Terraform uses state here ref tf state ref tf state terraform language state Note Since HCP Terraform currently only supports policy checks at plan time the usefulness of this import is somewhat limited as it will usually give you the state prior to the plan the policy check is currently being run for Depending on your needs you may find the applied terraform cloud docs policy enforcement sentinel import tfplan value applied collection in tfplan more useful which will give you a predicted state by applying plan data to the data found here The one exception to this rule is data sources which will always give up to date data here as long as the data source could be evaluated at plan time Namespace Overview The following is a tree view of the import namespace For more detail on a particular part of the namespace see below Note that the root level alias keys shown here data outputs path and resources are shortcuts to a module namespace namespace module scoped to the root module For more details see the section on root namespace aliases root namespace aliases tfstate module function module namespace path string data TYPE NAME NUMBER attr map of keys depends on string id string tainted boolean outputs root module only in TF 0 12 or later NAME sensitive bool type string value value resources TYPE NAME NUMBER attr map of keys depends on string id string tainted boolean module paths string terraform version string data root module alias outputs root module alias path root module alias resources root module alias Namespace Root The root level namespace consists of the values and functions documented below In addition to this the root level data outputs path and resources keys alias to their corresponding namespaces or values within the module namespace namespace module Function module module func ADDR Return Type A module namespace namespace module The module function in the root namespace namespace root returns the module namespace namespace module for a particular module address The address must be a list and is the module address split on the period excluding the root module Hence a module with an address of simply foo or root foo would be foo and a module within that so address foo bar would be read as foo bar null ref null is returned if a module address is invalid or if the module is not present in the state ref null https docs hashicorp com sentinel language spec null As an example given the following module block hcl module foo If the module contained the following content hcl resource null resource foo triggers foo bar The following policy would evaluate to true if the resource was present in the state python import tfstate main rule tfstate module foo resources null resource foo 0 attr triggers foo is bar Value module paths Value Type List of a list of strings The module paths value within the root namespace namespace root is a list of all of the modules within the Terraform state at plan time Modules not present in the state will not be present here even if they are present in the configuration or the diff This data is represented as a list of a list of strings with the inner list being the module address split on the period The root module is included in this list represented as an empty inner list as long as it is present in state As an example if the following module block was present within a Terraform configuration hcl module foo The value of module paths would be foo And the following policy would evaluate to true python import tfstate main rule tfstate module paths contains foo Note the above example only applies if the module is present in the state Iterating Through Modules Iterating through all modules to find particular resources can be useful This example iterate over modules shows how to use module paths with the module function function module to find all resources of a particular type from all modules using the tfplan import By changing tfplan in this function to tfstate you could make a similar function find all resources of a specific type in the current state iterate over modules terraform cloud docs policy enforcement sentinel sentinel imports Value terraform version Value Type String The terraform version value within the root namespace namespace root represents the version of Terraform in use when the state was saved This can be used to enforce a specific version of Terraform in a policy check As an example the following policy would evaluate to true as long as the state was made with a version of Terraform in the 0 11 x series excluding any pre release versions example beta1 or rc1 python import tfstate main rule tfstate terraform version matches 0 11 d NOTE This value is also available via the tfplan terraform cloud docs policy enforcement sentinel import tfplan import which will be more current when a policy check is run against a plan It s recommended you use the value in tfplan until HCP Terraform supports policy checks in other stages of the workspace lifecycle See the terraform version import tfplan terraform version reference within the tfplan import for more details import tfplan terraform version terraform cloud docs policy enforcement sentinel import tfplan value terraform version Namespace Module The module namespace can be loaded by calling module function module for a particular module It can be used to load the following child namespaces in addition to the values documented below data Loads the resource namespace namespace resources data sources filtered against data sources outputs Loads the output namespace namespace outputs which supply the outputs present in this module s state Note that with Terraform 0 12 or later this value is only available for the root namespace resources Loads the resource namespace namespace resources data sources filtered against resources Root Namespace Aliases The root level data outputs and resources keys both alias to their corresponding namespaces within the module namespace loaded for the root module They are the equivalent of running module KEY Value path Value Type List of strings The path value within the module namespace namespace module contains the path of the module that the namespace represents This is represented as a list of strings As an example if the following module block was present within a Terraform configuration hcl module foo The following policy would evaluate to true only if the module was present in the state python import tfstate main rule tfstate module foo path contains foo Namespace Resources Data Sources The resource namespace is a namespace type that applies to both resources accessed by using the resources namespace key and data sources accessed using the data namespace key Accessing an individual resource or data source within each respective namespace can be accomplished by specifying the type name and resource number as if the resource or data source had a count value in it in the syntax resources data TYPE NAME NUMBER Note that NUMBER is always needed even if you did not use count in the resource In addition each of these namespace levels is a map allowing you to filter based on type and name The somewhat strange notation here of TYPE NAME NUMBER may imply that the inner resource index map is actually a list but it s not using the square bracket notation over the dotted notation TYPE NAME NUMBER is required here as an identifier cannot start with number Some examples of multi level access are below To fetch all aws instance foo resource instances within the root module you can specify tfstate resources aws instance foo This would then be indexed by resource count index 0 1 2 and so on Note that as mentioned above these elements must be accessed using square bracket map notation so 0 1 2 and so on instead of dotted notation To fetch all aws instance resources within the root module you can specify tfstate resources aws instance This would be indexed from the names of each resource foo bar and so on with each of those maps containing instances indexed by resource count index as per above To fetch all resources within the root module irrespective of type use tfstate resources This is indexed by type as shown above with tfstate resources aws instance with names being the next level down and so on Further explanation of the namespace will be in the context of resources As mentioned when operating on data sources use the same syntax except with data in place of resources Value attr Value Type A string keyed map of values The attr value within the resource namespace namespace resources data sources is a direct mapping to the state of the resource The map is a complex representation of these values with data going as far down as needed to represent any state values such as maps lists and sets As an example given the following resource hcl resource null resource foo triggers foo bar The following policy would evaluate to true if the resource was in the state python import tfstate main rule tfstate resources null resource foo 0 attr triggers foo is bar Value depends on Value Type A list of strings The depends on value within the resource namespace namespace resources data sources contains the dependencies for the resource This is a list of full resource addresses relative to the module example null resource foo As an example given the following resources hcl resource null resource foo triggers foo bar resource null resource bar depends on null resource foo The following policy would evaluate to true if the resource was in the state python import tfstate main rule tfstate resources null resource bar 0 depends on contains null resource foo Value id Value Type String The id value within the resource namespace namespace resources data sources contains the id of the resource NOTE The example below uses a data source here because the null data source ref tf null data source data source gives a static ID which makes documenting the example easier As previously mentioned data sources share the same namespace as resources but need to be loaded with the data key For more information see the synopsis namespace resources data sources for the namespace itself ref tf null data source https registry terraform io providers hashicorp null latest docs data sources data source As an example given the following data source hcl data null data source foo The following policy would evaluate to true python import tfstate main rule tfstate data null data source foo 0 id is static Value tainted Value Type Boolean The tainted value within the resource namespace namespace resources data sources is true if the resource is marked as tainted in Terraform state As an example given the following resource hcl resource null resource foo triggers foo bar The following policy would evaluate to true if the resource was marked as tainted in the state python import tfstate main rule tfstate resources null resource foo 0 tainted Namespace Outputs The output namespace represents all of the outputs present within a module namespace module Outputs are present in a state if they were saved during a previous apply or if they were updated with known values during the pre plan refresh With Terraform 0 11 or earlier this can be used to fetch both the outputs of the root module and the outputs of any module in the state below the root This makes it possible to see outputs that have not been threaded to the root module With Terraform 0 12 or later outputs are available in the top level root module namespace only and not accessible within submodules This namespace is indexed by output name Value sensitive Value Type Boolean The sensitive value within the output namespace namespace outputs is true when the output has been marked as sensitive ref tf sensitive outputs ref tf sensitive outputs terraform language values outputs sensitive suppressing values in cli output As an example given the following output hcl output foo sensitive true value bar The following policy would evaluate to true python import tfstate main rule tfstate outputs foo sensitive Value type Value Type String The type value within the output namespace namespace outputs gives the output s type This will be one of string list or map These are currently the only types available for outputs in Terraform As an example given the following output hcl output string value foo output list value foo bar output map value foo bar The following policy would evaluate to true python import tfstate type string rule tfstate outputs string type is string type list rule tfstate outputs list type is list type map rule tfstate outputs map type is map main rule type string and type list and type map Value value Value Type String list or map The value value within the output namespace namespace outputs is the value of the output in question Note that the only valid primitive output type in Terraform is currently a string which means that any int float or boolean value will need to be converted before it can be used in comparison This does not apply to primitives within maps and lists which will be their original types As an example given the following output blocks hcl output foo value bar output number value 42 output map value foo bar number 42 The following policy would evaluate to true python import tfstate value foo rule tfstate outputs foo value is bar value number rule int tfstate outputs number value is 42 value map string rule tfstate outputs map value foo is bar value map int rule tfstate outputs map value number is 42 main rule value foo and value number and value map string and value map int
terraform Learn how to use Sentinel policy language to create custom policies including Define custom Sentinel policies imports to define rules and useful functions This topic describes how to create and manage custom policies using Sentinel policy language For instructions about how to use pre written Sentinel policies from the registry refer to Run pre written Sentinel policies terraform cloud docs policy enforcement define policies prewritten sentinel page title Define custom Sentinel policies
--- page_title: Define custom Sentinel policies description: >- Learn how to use Sentinel policy language to create custom policies, including imports to define rules and useful functions. --- # Define custom Sentinel policies This topic describes how to create and manage custom policies using Sentinel policy language. For instructions about how to use pre-written Sentinel policies from the registry, refer to [Run pre-written Sentinel policies](/terraform/cloud-docs/policy-enforcement/define-policies/prewritten-sentinel). ## Overview To define a policy, create a file and declare an `import` function to include reusable libraries, external data, and other functions. Sentinel policy language includes several types of elements you can import using the `import` function. Declare and configure additional Sentinel policy language elements. The details depend on which elements you want to use in your policy. Refer to the Sentinel documentation for additional information. <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/policies.mdx' <!-- END: TFC:only name:pnp-callout --> ## Declare an `import` function A policy can include imports that enable a policy to access reusable libraries, external data, and functions. Refer to [imports](https://docs.hashicorp.com/sentinel/concepts/imports) in the Sentinel documentation for more details. HCP Terraform provides four imports to define policy rules for the plan, configuration, state, and run associated with a policy check. - [tfplan](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfplan) - Access a Terraform plan, which is the file created as a result of the [`terraform plan` command](/terraform/cli/commands/plan). The plan represents the changes that Terraform must make to reach the desired infrastructure state described in the configuration. - [tfconfig](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfconfig) - Access a Terraform configuration. The configuration is the set of `.tf` files that describe the desired infrastructure state. - [tfstate](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfstate) - Access the Terraform [state](/terraform/language/state). Terraform uses state to map real-world resources to your configuration. - [tfrun](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfrun) - Access data associated with a [run in HCP Terraform](/terraform/cloud-docs/run/remote-operations). For example, you could retrieve the run's workspace. You can create mocks of these imports to use with the the [Sentinel CLI](https://docs.hashicorp.com/sentinel/commands) mocking and testing features. Refer to [Mocking Terraform Sentinel Data](/terraform/cloud-docs/policy-enforcement/sentinel/mock) for more details. <!-- BEGIN: TFC:only name:pnp-callout --> HCP Terraform does not support custom imports. <!-- END: TFC:only name:pnp-callout --> ## Declare additional elements The following functions and idioms will be useful as you start writing Sentinel policies for Terraform. ### Iterate over modules and find resources The most basic Sentinel task for Terraform is to enforce a rule on all resources of a given type. Before you can do that, you need to get a collection of all the relevant resources from all modules. The easiest way to do that is to copy and use a function like the following into your policies. The following example uses the `tfplan` import. You can find similar functions that iterate over the `tfconfig` and `tfstate` imports [here](https://github.com/hashicorp/terraform-guides/tree/master/governance/second-generation/common-functions). ```python import "tfplan" import "strings" # Find all resources of specific type from all modules using the tfplan import find_resources_from_plan = func(type) { resources = {} for tfplan.module_paths as path { for tfplan.module(path).resources[type] else {} as name, instances { for instances as index, r { # Get the address of the resource instance if length(path) == 0 { # root module address = type + "." + name + "[" + string(index) + "]" } else { # non-root module address = "module." + strings.join(path, ".module.") + "." + type + "." + name + "[" + string(index) + "]" } # Add the instance to resources, setting the key to the address resources[address] = r } } } return resources } ``` Call the function to get all resources of a desired type by passing the type as a string in quotation marks: ```python aws_instances = find_resources_from_plan("aws_instance") ``` This example function does several useful things while finding resources: - It checks every module (including the root module) for resources of the specified type by iterating over the `module_paths` namespace. The top-level `resources` namespace is more convenient, but it only reveals resources from the root module. - It iterates over the named resources and [resource instances](/terraform/language/expressions/references#resources) found in each module, starting with `tfplan.module(path).resources[type]` which is a series of nested maps keyed by resource names and instance counts. - It uses the Sentinel [`else` operator](https://docs.hashicorp.com/sentinel/language/spec#else-operator) to recover from `undefined` values which would occur for modules that don't have any resources of the specified type. - It builds a flat `resources` map of all resource instances of the specified type. Using a flat map simplifies the code used by Sentinel policies to evaluate rules. - It computes an `address` variable for each resource instance and uses this as the key in the `resources` map. This allows writers of Sentinel policies to print the full [address](/terraform/cli/state/resource-addressing) of each resource instance that violate a policy, using the same address format used in plan and apply logs. Doing this tells users who see violation messages exactly which resources they need to modify in their Terraform code to comply with the Sentinel policies. - It sets the value of the `resources` map to the data associated with the resource instance (`r`). This is the data that Sentinel policies apply rules against. ### Validate resource attributes Once you have a collection of resources instances of a desired type indexed by their addresses, you usually want to validate that one or more resource attributes meets some conditions by iterating over the resource instances. While you could use Sentinel's [`all` and `any` expressions](https://docs.hashicorp.com/sentinel/language/boolexpr#any-all-expressions) directly inside Sentinel rules, your rules would only report the first violation because Sentinel uses short-circuit logic. It is therefore usually preferred to use a [`for` loop](https://docs.hashicorp.com/sentinel/language/loops) outside of your rules so that you can report all violations that occur. You can do this inside functions or directly in the policy itself. Here is a function that calls the `find_resources_from_plan` function and validates that the instance types of all EC2 instances being provisioned are in a given list: ```python # Validate that all EC2 instances have instance_type in the allowed_types list validate_ec2_instance_types = func(allowed_types) { validated = true aws_instances = find_resources_from_plan("aws_instance") for aws_instances as address, r { # Determine if the attribute is computed if r.diff["instance_type"].computed else false is true { print("EC2 instance", address, "has attribute, instance_type, that is computed.") } else { # Validate that each instance has allowed value if (r.applied.instance_type else "") not in allowed_types { print("EC2 instance", address, "has instance_type", r.applied.instance_type, "that is not in the allowed list:", allowed_types) validated = false } } } return validated } ``` The boolean variable `validated` is initially set to `true`, but it is set to `false` if any resource instance violates the condition requiring that the `instance_type` attribute be in the `allowed_types` list. Since the function returns `true` or `false`, it can be called inside Sentinel rules. Note that this function prints a warning message for **every** resource instance that violates the condition. This allows writers of Terraform code to fix all violations after just one policy check. It also prints warnings when the attribute being evaluated is [computed](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfplan#value-computed) and does not evaluate the condition in this case since the applied value will not be known. While this function allows a rule to validate an attribute against a list, some rules will only need to validate an attribute against a single value; in those cases, you could either use a list with a single value or embed that value inside the function itself, drop the `allowed_types` parameter from the function definition, and use the `is` operator instead of the `in` operator to compare the resource attribute against the embedded value. ### Write Rules Having used the standardized `find_resources_from_plan` function and having written your own function to validate that resources instances of a specific type satisfy some condition, you can define a list with allowed values and write a rule that evaluates the value returned by your validation function. ```python # Allowed Types allowed_types = [ "t2.small", "t2.medium", "t2.large", ] # Main rule main = rule { validate_ec2_instance_types(allowed_types) } ``` ### Validate multiple conditions in a single policy If you want a policy to validate multiple conditions against resources of a specific type, you could define a separate validation function for each condition or use a single function to evaluate all the conditions. In the latter case, you would make this function return a list of boolean values, using one for each condition. You can then use multiple Sentinel rules that evaluate those boolean values or evaluate all of them in your `main` rule. Here is a partial example: ```python # Function to validate that S3 buckets have private ACL and use KMS encryption validate_private_acl_and_kms_encryption = func() { result = { "private": true, "encrypted_by_kms": true, } s3_buckets = find_resources_from_plan("aws_s3_bucket") # Iterate over resource instances and check that S3 buckets # have private ACL and are encrypted by a KMS key # If an S3 bucket is not private, set result["private"] to false # If an S3 bucket is not encrypted, set result["encrypted_by_kms"] to false for s3_buckets as joined_path, resource_map { #... } return result } # Call the validation function validations = validate_private_acl_and_kms_encryption() # ACL rule is_private = rule { validations["private"] } # KMS Encryption Rule is_encrypted_by_kms = rule { validations["encrypted_by_kms"] } # Main rule main = rule { is_private and is_encrypted_by_kms } ``` You can write similar functions and policies to restrict Terraform configurations using the `tfconfig` import and to restrict Terraform state using the `tfstate` import. ## Next steps 1. 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. 1. 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. 1. 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 Define custom Sentinel policies description Learn how to use Sentinel policy language to create custom policies including imports to define rules and useful functions Define custom Sentinel policies This topic describes how to create and manage custom policies using Sentinel policy language For instructions about how to use pre written Sentinel policies from the registry refer to Run pre written Sentinel policies terraform cloud docs policy enforcement define policies prewritten sentinel Overview To define a policy create a file and declare an import function to include reusable libraries external data and other functions Sentinel policy language includes several types of elements you can import using the import function Declare and configure additional Sentinel policy language elements The details depend on which elements you want to use in your policy Refer to the Sentinel documentation for additional information BEGIN TFC only name pnp callout include tfc package callouts policies mdx END TFC only name pnp callout Declare an import function A policy can include imports that enable a policy to access reusable libraries external data and functions Refer to imports https docs hashicorp com sentinel concepts imports in the Sentinel documentation for more details HCP Terraform provides four imports to define policy rules for the plan configuration state and run associated with a policy check tfplan terraform cloud docs policy enforcement sentinel import tfplan Access a Terraform plan which is the file created as a result of the terraform plan command terraform cli commands plan The plan represents the changes that Terraform must make to reach the desired infrastructure state described in the configuration tfconfig terraform cloud docs policy enforcement sentinel import tfconfig Access a Terraform configuration The configuration is the set of tf files that describe the desired infrastructure state tfstate terraform cloud docs policy enforcement sentinel import tfstate Access the Terraform state terraform language state Terraform uses state to map real world resources to your configuration tfrun terraform cloud docs policy enforcement sentinel import tfrun Access data associated with a run in HCP Terraform terraform cloud docs run remote operations For example you could retrieve the run s workspace You can create mocks of these imports to use with the the Sentinel CLI https docs hashicorp com sentinel commands mocking and testing features Refer to Mocking Terraform Sentinel Data terraform cloud docs policy enforcement sentinel mock for more details BEGIN TFC only name pnp callout HCP Terraform does not support custom imports END TFC only name pnp callout Declare additional elements The following functions and idioms will be useful as you start writing Sentinel policies for Terraform Iterate over modules and find resources The most basic Sentinel task for Terraform is to enforce a rule on all resources of a given type Before you can do that you need to get a collection of all the relevant resources from all modules The easiest way to do that is to copy and use a function like the following into your policies The following example uses the tfplan import You can find similar functions that iterate over the tfconfig and tfstate imports here https github com hashicorp terraform guides tree master governance second generation common functions python import tfplan import strings Find all resources of specific type from all modules using the tfplan import find resources from plan func type resources for tfplan module paths as path for tfplan module path resources type else as name instances for instances as index r Get the address of the resource instance if length path 0 root module address type name string index else non root module address module strings join path module type name string index Add the instance to resources setting the key to the address resources address r return resources Call the function to get all resources of a desired type by passing the type as a string in quotation marks python aws instances find resources from plan aws instance This example function does several useful things while finding resources It checks every module including the root module for resources of the specified type by iterating over the module paths namespace The top level resources namespace is more convenient but it only reveals resources from the root module It iterates over the named resources and resource instances terraform language expressions references resources found in each module starting with tfplan module path resources type which is a series of nested maps keyed by resource names and instance counts It uses the Sentinel else operator https docs hashicorp com sentinel language spec else operator to recover from undefined values which would occur for modules that don t have any resources of the specified type It builds a flat resources map of all resource instances of the specified type Using a flat map simplifies the code used by Sentinel policies to evaluate rules It computes an address variable for each resource instance and uses this as the key in the resources map This allows writers of Sentinel policies to print the full address terraform cli state resource addressing of each resource instance that violate a policy using the same address format used in plan and apply logs Doing this tells users who see violation messages exactly which resources they need to modify in their Terraform code to comply with the Sentinel policies It sets the value of the resources map to the data associated with the resource instance r This is the data that Sentinel policies apply rules against Validate resource attributes Once you have a collection of resources instances of a desired type indexed by their addresses you usually want to validate that one or more resource attributes meets some conditions by iterating over the resource instances While you could use Sentinel s all and any expressions https docs hashicorp com sentinel language boolexpr any all expressions directly inside Sentinel rules your rules would only report the first violation because Sentinel uses short circuit logic It is therefore usually preferred to use a for loop https docs hashicorp com sentinel language loops outside of your rules so that you can report all violations that occur You can do this inside functions or directly in the policy itself Here is a function that calls the find resources from plan function and validates that the instance types of all EC2 instances being provisioned are in a given list python Validate that all EC2 instances have instance type in the allowed types list validate ec2 instance types func allowed types validated true aws instances find resources from plan aws instance for aws instances as address r Determine if the attribute is computed if r diff instance type computed else false is true print EC2 instance address has attribute instance type that is computed else Validate that each instance has allowed value if r applied instance type else not in allowed types print EC2 instance address has instance type r applied instance type that is not in the allowed list allowed types validated false return validated The boolean variable validated is initially set to true but it is set to false if any resource instance violates the condition requiring that the instance type attribute be in the allowed types list Since the function returns true or false it can be called inside Sentinel rules Note that this function prints a warning message for every resource instance that violates the condition This allows writers of Terraform code to fix all violations after just one policy check It also prints warnings when the attribute being evaluated is computed terraform cloud docs policy enforcement sentinel import tfplan value computed and does not evaluate the condition in this case since the applied value will not be known While this function allows a rule to validate an attribute against a list some rules will only need to validate an attribute against a single value in those cases you could either use a list with a single value or embed that value inside the function itself drop the allowed types parameter from the function definition and use the is operator instead of the in operator to compare the resource attribute against the embedded value Write Rules Having used the standardized find resources from plan function and having written your own function to validate that resources instances of a specific type satisfy some condition you can define a list with allowed values and write a rule that evaluates the value returned by your validation function python Allowed Types allowed types t2 small t2 medium t2 large Main rule main rule validate ec2 instance types allowed types Validate multiple conditions in a single policy If you want a policy to validate multiple conditions against resources of a specific type you could define a separate validation function for each condition or use a single function to evaluate all the conditions In the latter case you would make this function return a list of boolean values using one for each condition You can then use multiple Sentinel rules that evaluate those boolean values or evaluate all of them in your main rule Here is a partial example python Function to validate that S3 buckets have private ACL and use KMS encryption validate private acl and kms encryption func result private true encrypted by kms true s3 buckets find resources from plan aws s3 bucket Iterate over resource instances and check that S3 buckets have private ACL and are encrypted by a KMS key If an S3 bucket is not private set result private to false If an S3 bucket is not encrypted set result encrypted by kms to false for s3 buckets as joined path resource map return result Call the validation function validations validate private acl and kms encryption ACL rule is private rule validations private KMS Encryption Rule is encrypted by kms rule validations encrypted by kms Main rule main rule is private and is encrypted by kms You can write similar functions and policies to restrict Terraform configurations using the tfconfig import and to restrict Terraform state using the tfstate import Next steps 1 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 1 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 1 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 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
--- 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
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
--- 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 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
--- 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
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
--- 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" {} ```
terraform
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
terraform Each plan and apply run passes through several stages of action pending plan cost estimation policy check apply and completion HCP Terraform shows a run s progress through each stage as a run state policy check apply and complete Learn what happens during each stage of a run pending plan cost estimation page title Run States and Stages Runs HCP Terraform Run States and Stages
--- page_title: Run States and Stages - Runs - HCP Terraform description: >- Learn what happens during each stage of a run: pending, plan, cost estimation, policy check, apply, and complete. --- # Run States and Stages Each plan and apply run passes through several stages of action: pending, plan, cost estimation, policy check, apply, and completion. HCP Terraform shows a run's progress through each stage as a run state. In the list of workspaces on HCP Terraform's main page, each workspace shows the state of the run it's currently processing. If no run is in progress, HCP Terraform displays the state of the most recently completed run. ## The Pending Stage _States in this stage:_ - **Pending:** HCP Terraform hasn't started action on a run yet. HCP Terraform processes each workspace's runs in the order they were queued, and a run remains pending until every run before it has completed. _Leaving this stage:_ - If the user discards the run before it starts, the run does not continue (**Discarded** state). - If the run is first in the queue, it proceeds automatically to the plan stage (**Planning** state). ## The Fetching Stage HCP Terraform may need to fetch the configuration from VCS prior to starting the plan. HCP Terraform automatically archives configuration versions created through VCS when all runs are complete and then re-fetches the files for subsequent runs. _States in this stage:_ - **Fetching:** If HCP Terraform has not yet fetched the configuration from VCS, the run will go into this state until the configuration is available. _Leaving this stage:_ - If HCP Terraform encounters an error when fetching the configuration from VCS, the run does not continue (**Plan Errored** state). - If Terraform successfully fetches the configuration, the run moves to the next stage. ## The Pre-Plan Stage The pre-plan phase only occurs if there are enabled [run tasks](/terraform/cloud-docs/workspaces/settings/run-tasks) in the workspace that are configured to begin before Terraform creates the plan. HCP Terraform sends information about the run to the configured external system and waits for a `passed` or `failed` response to determine whether the run can continue. The information sent to the external system includes the configuration version of the run. All runs can enter this phase, including [speculative plans](/terraform/cloud-docs/run/remote-operations#speculative-plans). _States in this stage:_ - **Pre-plan running:** HCP Terraform is waiting for a response from the configured external system(s). - External systems must respond initially with a `200 OK` acknowledging the request is in progress. After that, they have 10 minutes to return a status of `passed`, `running`, or `failed`. If the timeout expires, HCP Terraform assumes that the run tasks is in the `failed` status. _Leaving this stage:_ - If any mandatory tasks failed, the run skips to completion (**Plan Errored** state). - If any advisory tasks failed, the run proceeds to the **Planning** state, with a visible warning regarding the failed task. - If a single run has a combination of mandatory and advisory tasks, Terraform takes the most restrictive action. For example, the run fails if there are two advisory tasks that succeed and one mandatory task that fails. - If a user canceled the run, the run ends in the **Canceled** state. ## The Plan Stage A run goes through different steps during the plan stage depending on whether or not HCP Terraform needs to fetch the configuration from VCS. HCP Terraform automatically archives configuration versions created through VCS when all runs are complete and then re-fetches the files for subsequent runs. _States in this stage:_ - **Planning:** HCP Terraform is currently running `terraform plan`. - **Needs Confirmation:** `terraform plan` has finished. Runs sometimes pause in this state, depending on the workspace and organization settings. _Leaving this stage:_ - If the `terraform plan` command failed, the run does not continue (**Plan Errored** state). - If a user canceled the plan by pressing the "Cancel Run" button, the run does not continue (**Canceled** state). - If the plan succeeded with no changes and neither cost estimation nor Sentinel policy checks will be done, HCP Terraform considers the run complete (**Planned and Finished** state). - If the plan succeeded and requires changes: - If cost estimation is enabled, the run proceeds automatically to the cost estimation stage. - If cost estimation is disabled and [Sentinel policies](/terraform/enterprise/policy-enforcement/sentinel) are enabled, the run proceeds automatically to the policy check stage. - If there are no Sentinel policies and the plan can be auto-applied, the run proceeds automatically to the apply stage. Plans can be auto-applied if the auto-apply setting is enabled on the workspace and the plan was queued by a new VCS commit or by a user with permission to apply runs. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) - If there are no Sentinel policies and HCP Terraform cannot auto-apply the plan, the run pauses in the **Needs Confirmation** state until a user with permission to apply runs takes action. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) If an authorized user approves the apply, the run proceeds to the apply stage. If an authorized user rejects the apply, the run does not continue (**Discarded** state). [permissions-citation]: #intentionally-unused---keep-for-maintainers Note, if you want to directly integrate third-party tools and services between your plan and apply stages, see [Run Tasks](/terraform/cloud-docs/workspaces/settings/run-tasks). ## The Post-Plan Stage The post-plan phase only occurs if you configure [run tasks](/terraform/cloud-docs/workspaces/settings/run-tasks) on a workspace to begin after Terraform successfully completes a plan operation. All runs can enter this phase, including [speculative plans](/terraform/cloud-docs/run/remote-operations#speculative-plans). During this phase, HCP Terraform sends information about the run to the configured external system and waits for a `passed` or `failed` response to determine whether the run can continue. -> **Note:** The information sent to the configured external system includes the [JSON output](/terraform/internals/json-format) of the Terraform plan. _States in this stage:_ - **Post-plan running:** HCP Terraform is waiting for a response from the configured external system(s). - External systems must respond initially with a `200 OK` acknowledging the request is in progress. After that, they have 10 minutes to return a status of `passed`, `running`, or `failed`, or the timeout will expire and the task will be assumed to be in the `failed` status. _Leaving this stage:_ - If any mandatory tasks failed, the run skips to completion (**Plan Errored** state). - If any advisory tasks failed, the run proceeds to the **Applying** state, with a visible warning regarding the failed task. - If a single run has a combination of mandatory and advisory tasks, Terraform takes the most restrictive action. For example, if there are two advisory tasks that succeed and one mandatory task that failed, the run fails. If one mandatory task succeeds and two advisory tasks fail, the run succeeds with a warning. - If a user canceled the run, the run ends in the **Canceled** state. ## The OPA Policy Check Stage This stage only occurs if you enabled [Open Policy Agent (OPA) policies](/terraform/cloud-docs/policy-enforcement/opa) and runs after a successful `terraform plan` and before Cost Estimation. In this stage, HCP Terraform checks whether the plan adheres to the policies in the OPA policy sets for the workspace. _States in this stage:_ - **Policy Check:** HCP Terraform is checking the plan against the OPA policy sets. - **Policy Override:** The policy check finished, but a mandatory policy failed. The run pauses, and Terraform cannot perform an apply unless a user manually overrides the policy check failure. Refer to [Policy Results](/terraform/cloud-docs/policy-enforcement/policy-results) for details. - **Policy Checked:** The policy check succeeded, and Terraform can apply the plan. The run may pause in this state if the workspace is not set up to auto-apply runs. _Leaving this stage:_ If any mandatory policies failed, the run pauses in the **Policy Override** state. The run completes one of the following workflows: - The run stops and enters the **Discarded** state when a user with [permission to apply runs](/terraform/cloud-docs/users-teams-organizations/permissions#general-workspace-permissions#manage-policy-overrides) discards the run. - The run proceeds to the **Policy Checked** state when a user with [permission to manage policy overrides](/terraform/cloud-docs/users-teams-organizations/permissions) overrides the failed policy. The **Policy Checked** state means that no mandatory policies failed or that a user performed a manual override. Once the run reaches the **Policy Checked** state, the run completes one of the following workflows: - The run proceeds to the **Apply** stage if Terraform can automatically apply the plan. An auto-apply requires that the **Auto apply** setting is enabled on the workspace. - If Terraform cannot automatically apply the plan, the run pauses in the **Policy Checked** state until a user with permission to apply runs takes action. If the user approves the apply, the run proceeds to the **Apply** stage. If the user rejects the apply, the run stops and enters the **Discarded** state. ## The Cost Estimation Stage This stage only occurs if cost estimation is enabled. After a successful `terraform plan`, HCP Terraform uses plan data to estimate costs for each resource found in the plan. _States in this stage:_ - **Cost Estimating:** HCP Terraform is currently estimating the resources in the plan. - **Cost Estimated:** The cost estimate completed. _Leaving this stage:_ - If cost estimation succeeded or errors, the run moves to the next stage. - If there are no policy checks or applies, the run does not continue (**Planned and Finished** state). ## The Sentinel Policy Check Stage This stage only occurs if [Sentinel policies](/terraform/cloud-docs/policy-enforcement/sentinel) are enabled. After a successful `terraform plan`, HCP Terraform checks whether the plan obeys policy to determine whether it can be applied. _States in this stage:_ - **Policy Check:** HCP Terraform is currently checking the plan against the organization's policies. - **Policy Override:** The policy check finished, but a soft-mandatory policy failed, so an apply cannot proceed without approval from a user with permission to manage policy overrides for the organization. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) The run pauses in this state. - **Policy Checked:** The policy check succeeded, and Sentinel will allow an apply to proceed. The run sometimes pauses in this state, depending on workspace settings. [permissions-citation]: #intentionally-unused---keep-for-maintainers _Leaving this stage:_ - If any hard-mandatory policies failed, the run does not continue (**Plan Errored** state). - If any soft-mandatory policies failed, the run pauses in the **Policy Override** state. - If a user with permission to manage policy overrides, overrides the failed policy, the run proceeds to the **Policy Checked** state. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) - If a user with permission to apply runs discards the run, the run does not continue (**Discarded** state). ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) - If the run reaches the **Policy Checked** state (no mandatory policies failed, or soft-mandatory policies were overridden): - If the plan can be auto-applied, the run proceeds automatically to the apply stage. Plans can be auto-applied if the auto-apply setting is enabled on the workspace and the plan was queued by a new VCS commit or by a user with permission to apply runs. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) - If the plan can't be auto-applied, the run pauses in the **Policy Checked** state until a user with permission to apply runs takes action. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) The run proceeds to the apply stage if they approve the apply, or does not continue (**Discarded** state) if they reject the apply. [permissions-citation]: #intentionally-unused---keep-for-maintainers ## The Pre-Apply Stage The pre-apply phase only occurs if the workspace has [run tasks](/terraform/cloud-docs/workspaces/settings/run-tasks) configured to begin before Terraform creates the apply. HCP Terraform sends information about the run to the configured external system and waits for a `passed` or `failed` response to determine whether the run can continue. The information sent to the external system includes the configuration version of the run. Only confirmed runs can enter this phase. _States in this stage:_ - **Pre-apply running:** HCP Terraform is waiting for a response from the configured external system(s). - External systems must respond initially with a `200 OK` acknowledging the request is in progress. After that, they have 10 minutes to return a status of `passed`, `running`, or `failed`. If the timeout expires, HCP Terraform assumes that the run tasks is in the `failed` status. _Leaving this stage:_ - If any mandatory tasks failed, the run skips to completion. - If any advisory tasks failed, the run proceeds to the **Applying** state, with a visible warning regarding the failed task. - If a single run has a combination of mandatory and advisory tasks, Terraform takes the most restrictive action. For example, the run fails if there are two advisory tasks that succeed and one mandatory task that fails. - If a user canceled the run, the run ends in the **Canceled** state. ## The Apply Stage _States in this stage:_ - **Applying:** HCP Terraform is currently running `terraform apply`. _Leaving this stage:_ After applying, the run proceeds automatically to completion. - If the apply succeeded, the run ends in the **Applied** state. - If the apply failed, the run ends in the **Apply Errored** state. - If a user canceled the apply by pressing **Cancel Run**, the run ends in the **Canceled** state. ## The Post-Apply Stage The post-apply phase only occurs if you configure [run tasks](/terraform/cloud-docs/workspaces/settings/run-tasks) on a workspace to begin after Terraform successfully completes an apply operation. During this phase, HCP Terraform sends information about the run to the configured external system and waits for a `passed` or `failed` response. However, unlike other stages in the run task process, a failed outcome does not halt the run since HCP Terraform has already provisioned the infrastructure. _States in this stage:_ - **Post-apply running:** HCP Terraform is waiting for a response from the configured external system(s). - External systems must respond initially with a `200 OK` acknowledging the request is in progress. After that, they have 10 minutes to return a status of `passed`, `running`, or `failed`. If the timeout expires, HCP Terraform assumes that the run tasks is in the `failed` status. _Leaving this stage:_ - There are only advisory tasks on this stage. - If any advisory tasks failed, the run proceeds to the **Applied** state, with a visible warning regarding the failed task. - If a user cancels the run, the run ends in the **Canceled** state. ## Completion A run is complete if it finishes applying, if any part of the run fails, if there is nothing to do, or if a user chooses not to continue. Once a run completes, the next run in the queue can enter the plan stage. _States in this stage:_ - **Applied:** The run was successfully applied. - **Planned and Finished:** `terraform plan`'s output already matches the current infrastructure state, so `terraform apply` doesn't need to do anything. - **Apply Errored:** The `terraform apply` command failed, possibly due to a missing or misconfigured provider or an illegal operation on a provider. - **Plan Errored:** The `terraform plan` command failed (usually requiring fixes to variables or code), or a hard-mandatory Sentinel policy failed. The run cannot be applied. - **Discarded:** A user chose not to continue this run. - **Canceled:** A user interrupted the `terraform plan` or `terraform apply` command with the "Cancel Run" button.
terraform
page title Run States and Stages Runs HCP Terraform description Learn what happens during each stage of a run pending plan cost estimation policy check apply and complete Run States and Stages Each plan and apply run passes through several stages of action pending plan cost estimation policy check apply and completion HCP Terraform shows a run s progress through each stage as a run state In the list of workspaces on HCP Terraform s main page each workspace shows the state of the run it s currently processing If no run is in progress HCP Terraform displays the state of the most recently completed run The Pending Stage States in this stage Pending HCP Terraform hasn t started action on a run yet HCP Terraform processes each workspace s runs in the order they were queued and a run remains pending until every run before it has completed Leaving this stage If the user discards the run before it starts the run does not continue Discarded state If the run is first in the queue it proceeds automatically to the plan stage Planning state The Fetching Stage HCP Terraform may need to fetch the configuration from VCS prior to starting the plan HCP Terraform automatically archives configuration versions created through VCS when all runs are complete and then re fetches the files for subsequent runs States in this stage Fetching If HCP Terraform has not yet fetched the configuration from VCS the run will go into this state until the configuration is available Leaving this stage If HCP Terraform encounters an error when fetching the configuration from VCS the run does not continue Plan Errored state If Terraform successfully fetches the configuration the run moves to the next stage The Pre Plan Stage The pre plan phase only occurs if there are enabled run tasks terraform cloud docs workspaces settings run tasks in the workspace that are configured to begin before Terraform creates the plan HCP Terraform sends information about the run to the configured external system and waits for a passed or failed response to determine whether the run can continue The information sent to the external system includes the configuration version of the run All runs can enter this phase including speculative plans terraform cloud docs run remote operations speculative plans States in this stage Pre plan running HCP Terraform is waiting for a response from the configured external system s External systems must respond initially with a 200 OK acknowledging the request is in progress After that they have 10 minutes to return a status of passed running or failed If the timeout expires HCP Terraform assumes that the run tasks is in the failed status Leaving this stage If any mandatory tasks failed the run skips to completion Plan Errored state If any advisory tasks failed the run proceeds to the Planning state with a visible warning regarding the failed task If a single run has a combination of mandatory and advisory tasks Terraform takes the most restrictive action For example the run fails if there are two advisory tasks that succeed and one mandatory task that fails If a user canceled the run the run ends in the Canceled state The Plan Stage A run goes through different steps during the plan stage depending on whether or not HCP Terraform needs to fetch the configuration from VCS HCP Terraform automatically archives configuration versions created through VCS when all runs are complete and then re fetches the files for subsequent runs States in this stage Planning HCP Terraform is currently running terraform plan Needs Confirmation terraform plan has finished Runs sometimes pause in this state depending on the workspace and organization settings Leaving this stage If the terraform plan command failed the run does not continue Plan Errored state If a user canceled the plan by pressing the Cancel Run button the run does not continue Canceled state If the plan succeeded with no changes and neither cost estimation nor Sentinel policy checks will be done HCP Terraform considers the run complete Planned and Finished state If the plan succeeded and requires changes If cost estimation is enabled the run proceeds automatically to the cost estimation stage If cost estimation is disabled and Sentinel policies terraform enterprise policy enforcement sentinel are enabled the run proceeds automatically to the policy check stage If there are no Sentinel policies and the plan can be auto applied the run proceeds automatically to the apply stage Plans can be auto applied if the auto apply setting is enabled on the workspace and the plan was queued by a new VCS commit or by a user with permission to apply runs More about permissions terraform cloud docs users teams organizations permissions If there are no Sentinel policies and HCP Terraform cannot auto apply the plan the run pauses in the Needs Confirmation state until a user with permission to apply runs takes action More about permissions terraform cloud docs users teams organizations permissions If an authorized user approves the apply the run proceeds to the apply stage If an authorized user rejects the apply the run does not continue Discarded state permissions citation intentionally unused keep for maintainers Note if you want to directly integrate third party tools and services between your plan and apply stages see Run Tasks terraform cloud docs workspaces settings run tasks The Post Plan Stage The post plan phase only occurs if you configure run tasks terraform cloud docs workspaces settings run tasks on a workspace to begin after Terraform successfully completes a plan operation All runs can enter this phase including speculative plans terraform cloud docs run remote operations speculative plans During this phase HCP Terraform sends information about the run to the configured external system and waits for a passed or failed response to determine whether the run can continue Note The information sent to the configured external system includes the JSON output terraform internals json format of the Terraform plan States in this stage Post plan running HCP Terraform is waiting for a response from the configured external system s External systems must respond initially with a 200 OK acknowledging the request is in progress After that they have 10 minutes to return a status of passed running or failed or the timeout will expire and the task will be assumed to be in the failed status Leaving this stage If any mandatory tasks failed the run skips to completion Plan Errored state If any advisory tasks failed the run proceeds to the Applying state with a visible warning regarding the failed task If a single run has a combination of mandatory and advisory tasks Terraform takes the most restrictive action For example if there are two advisory tasks that succeed and one mandatory task that failed the run fails If one mandatory task succeeds and two advisory tasks fail the run succeeds with a warning If a user canceled the run the run ends in the Canceled state The OPA Policy Check Stage This stage only occurs if you enabled Open Policy Agent OPA policies terraform cloud docs policy enforcement opa and runs after a successful terraform plan and before Cost Estimation In this stage HCP Terraform checks whether the plan adheres to the policies in the OPA policy sets for the workspace States in this stage Policy Check HCP Terraform is checking the plan against the OPA policy sets Policy Override The policy check finished but a mandatory policy failed The run pauses and Terraform cannot perform an apply unless a user manually overrides the policy check failure Refer to Policy Results terraform cloud docs policy enforcement policy results for details Policy Checked The policy check succeeded and Terraform can apply the plan The run may pause in this state if the workspace is not set up to auto apply runs Leaving this stage If any mandatory policies failed the run pauses in the Policy Override state The run completes one of the following workflows The run stops and enters the Discarded state when a user with permission to apply runs terraform cloud docs users teams organizations permissions general workspace permissions manage policy overrides discards the run The run proceeds to the Policy Checked state when a user with permission to manage policy overrides terraform cloud docs users teams organizations permissions overrides the failed policy The Policy Checked state means that no mandatory policies failed or that a user performed a manual override Once the run reaches the Policy Checked state the run completes one of the following workflows The run proceeds to the Apply stage if Terraform can automatically apply the plan An auto apply requires that the Auto apply setting is enabled on the workspace If Terraform cannot automatically apply the plan the run pauses in the Policy Checked state until a user with permission to apply runs takes action If the user approves the apply the run proceeds to the Apply stage If the user rejects the apply the run stops and enters the Discarded state The Cost Estimation Stage This stage only occurs if cost estimation is enabled After a successful terraform plan HCP Terraform uses plan data to estimate costs for each resource found in the plan States in this stage Cost Estimating HCP Terraform is currently estimating the resources in the plan Cost Estimated The cost estimate completed Leaving this stage If cost estimation succeeded or errors the run moves to the next stage If there are no policy checks or applies the run does not continue Planned and Finished state The Sentinel Policy Check Stage This stage only occurs if Sentinel policies terraform cloud docs policy enforcement sentinel are enabled After a successful terraform plan HCP Terraform checks whether the plan obeys policy to determine whether it can be applied States in this stage Policy Check HCP Terraform is currently checking the plan against the organization s policies Policy Override The policy check finished but a soft mandatory policy failed so an apply cannot proceed without approval from a user with permission to manage policy overrides for the organization More about permissions terraform cloud docs users teams organizations permissions The run pauses in this state Policy Checked The policy check succeeded and Sentinel will allow an apply to proceed The run sometimes pauses in this state depending on workspace settings permissions citation intentionally unused keep for maintainers Leaving this stage If any hard mandatory policies failed the run does not continue Plan Errored state If any soft mandatory policies failed the run pauses in the Policy Override state If a user with permission to manage policy overrides overrides the failed policy the run proceeds to the Policy Checked state More about permissions terraform cloud docs users teams organizations permissions If a user with permission to apply runs discards the run the run does not continue Discarded state More about permissions terraform cloud docs users teams organizations permissions If the run reaches the Policy Checked state no mandatory policies failed or soft mandatory policies were overridden If the plan can be auto applied the run proceeds automatically to the apply stage Plans can be auto applied if the auto apply setting is enabled on the workspace and the plan was queued by a new VCS commit or by a user with permission to apply runs More about permissions terraform cloud docs users teams organizations permissions If the plan can t be auto applied the run pauses in the Policy Checked state until a user with permission to apply runs takes action More about permissions terraform cloud docs users teams organizations permissions The run proceeds to the apply stage if they approve the apply or does not continue Discarded state if they reject the apply permissions citation intentionally unused keep for maintainers The Pre Apply Stage The pre apply phase only occurs if the workspace has run tasks terraform cloud docs workspaces settings run tasks configured to begin before Terraform creates the apply HCP Terraform sends information about the run to the configured external system and waits for a passed or failed response to determine whether the run can continue The information sent to the external system includes the configuration version of the run Only confirmed runs can enter this phase States in this stage Pre apply running HCP Terraform is waiting for a response from the configured external system s External systems must respond initially with a 200 OK acknowledging the request is in progress After that they have 10 minutes to return a status of passed running or failed If the timeout expires HCP Terraform assumes that the run tasks is in the failed status Leaving this stage If any mandatory tasks failed the run skips to completion If any advisory tasks failed the run proceeds to the Applying state with a visible warning regarding the failed task If a single run has a combination of mandatory and advisory tasks Terraform takes the most restrictive action For example the run fails if there are two advisory tasks that succeed and one mandatory task that fails If a user canceled the run the run ends in the Canceled state The Apply Stage States in this stage Applying HCP Terraform is currently running terraform apply Leaving this stage After applying the run proceeds automatically to completion If the apply succeeded the run ends in the Applied state If the apply failed the run ends in the Apply Errored state If a user canceled the apply by pressing Cancel Run the run ends in the Canceled state The Post Apply Stage The post apply phase only occurs if you configure run tasks terraform cloud docs workspaces settings run tasks on a workspace to begin after Terraform successfully completes an apply operation During this phase HCP Terraform sends information about the run to the configured external system and waits for a passed or failed response However unlike other stages in the run task process a failed outcome does not halt the run since HCP Terraform has already provisioned the infrastructure States in this stage Post apply running HCP Terraform is waiting for a response from the configured external system s External systems must respond initially with a 200 OK acknowledging the request is in progress After that they have 10 minutes to return a status of passed running or failed If the timeout expires HCP Terraform assumes that the run tasks is in the failed status Leaving this stage There are only advisory tasks on this stage If any advisory tasks failed the run proceeds to the Applied state with a visible warning regarding the failed task If a user cancels the run the run ends in the Canceled state Completion A run is complete if it finishes applying if any part of the run fails if there is nothing to do or if a user chooses not to continue Once a run completes the next run in the queue can enter the plan stage States in this stage Applied The run was successfully applied Planned and Finished terraform plan s output already matches the current infrastructure state so terraform apply doesn t need to do anything Apply Errored The terraform apply command failed possibly due to a missing or misconfigured provider or an illegal operation on a provider Plan Errored The terraform plan command failed usually requiring fixes to variables or code or a hard mandatory Sentinel policy failed The run cannot be applied Discarded A user chose not to continue this run Canceled A user interrupted the terraform plan or terraform apply command with the Cancel Run button
terraform Run Terraform remotely through the UI API or CLI Learn how HCP Terraform page title Remote Operations HCP Terraform Hands on Try the Get Started HCP Terraform terraform tutorials cloud get started utm source WEBSITE utm medium WEB IO utm offer ARTICLE PAGE utm content DOCS tutorials Remote Operations manages runs
--- page_title: Remote Operations - HCP Terraform description: >- Run Terraform remotely through the UI, API, or CLI. Learn how HCP Terraform manages runs. --- # Remote Operations > **Hands-on:** Try the [Get Started — HCP Terraform](/terraform/tutorials/cloud-get-started?utm_source=WEBSITE&utm_medium=WEB_IO&utm_offer=ARTICLE_PAGE&utm_content=DOCS) tutorials. HCP Terraform provides a central interface for running Terraform within a large collaborative organization. If you're accustomed to running Terraform from your workstation, the way HCP Terraform manages runs can be unfamiliar. This page describes the basics of how runs work in HCP Terraform. ## Remote Operations HCP Terraform is designed as an execution platform for Terraform, and can perform Terraform runs on its own disposable virtual machines. This provides a consistent and reliable run environment, and enables advanced features like Sentinel policy enforcement, cost estimation, notifications, version control integration, and more. Terraform runs managed by HCP Terraform are called _remote operations._ Remote runs can be initiated by webhooks from your VCS provider, by UI controls within HCP Terraform, by API calls, or by Terraform CLI. When using Terraform CLI to perform remote operations, the progress of the run is streamed to the user's terminal, to provide an experience equivalent to local operations. ### Disabling Remote Operations [execution_mode]: /terraform/cloud-docs/workspaces/settings#execution-mode Many of HCP Terraform's features rely on remote execution and are not available when using local operations. This includes features like Sentinel policy enforcement, cost estimation, and notifications. You can disable remote operations for any workspace by changing its [Execution Mode][execution_mode] to **Local**. This causes the workspace to act only as a remote backend for Terraform state, with all execution occurring on your own workstations or continuous integration workers. ### Protecting Private Environments [HCP Terraform agents](/terraform/cloud-docs/agents) are a paid feature that allows HCP Terraform to communicate with isolated, private, or on-premises infrastructure. The agent polls HCP Terraform or Terraform Enterprise for any changes to your configuration and executes the changes locally, so you do not need to allow public ingress traffic to your resources. Agents allow you to control infrastructure in private environments without modifying your network perimeter. HCP Terraform agents also support running custom programs, called _hooks_, during strategic points of a Terraform run. For example, you may create a hook to dynamically download software required by the Terraform run or send an HTTP request to a system to kick off an external workflow. ## Runs and Workspaces HCP Terraform always performs Terraform runs in the context of a [workspace](/terraform/cloud-docs/run/remote-operations). The workspace serves the same role that a persistent working directory serves when running Terraform locally: it provides the configuration, state, and variables for the run. ### Configuration Versions Each workspace is associated with a particular Terraform configuration, but that configuration is expected to change over time. Thus, HCP Terraform manages configurations as a series of _configuration versions._ Most commonly, a workspace is linked to a VCS repository, and its configuration versions are tied to revisions in the specified VCS branch. In workspaces that aren't linked to a repository, new configuration versions can be uploaded via Terraform CLI or via the API. ### Ordering and Timing Each workspace in HCP Terraform maintains its own queue of runs, and processes those runs in order. Whenever a new run is initiated, it's added to the end of the queue. If there's already a run in progress, the new run won't start until the current one has completely finished — HCP Terraform won't even plan the run yet, because the current run might change what a future run would do. Runs that are waiting for other runs to finish are in a _pending_ state, and a workspace might have any number of pending runs. There are two exceptions to the run queue, which can proceed at any time and do not block the progress of other runs: - Plan-only runs. - The planning stages of [saved plan runs](/terraform/cloud-docs/run/modes-and-options/#saved-plans). You can only _apply_ a saved plan if no other run is in progress, and applying that plan blocks the run queue as usual. Terraform Enterprise does not yet support this workflow. When you initiate a run, HCP Terraform locks the run to a particular configuration version and set of variable values. If you change variables or commit new code before the run finishes, it will only affect future runs, not runs that are already pending, planning, or awaiting apply. ### Workspace Locks When a workspace is _locked,_ HCP Terraform can create new runs (automatically or manually), but those runs do not begin until you unlock the workspace. When a run is in progress, that run locks the workspace, as described above under "Ordering and Timing". There are two kinds of run operation that can ignore workspace locking: - Plan-only runs. - The planning stages of [saved plan runs](/terraform/cloud-docs/run/modes-and-options/#saved-plans). You can only _apply_ a saved plan if the workspace is unlocked, and applying that plan locks the workspace as usual. Terraform Enterprise does not yet support this workflow. A user or team can also deliberately lock a workspace, to perform maintenance or for any other reason. For more details, see [Locking Workspaces (Preventing Runs)](/terraform/cloud-docs/run/manage#locking-workspaces-preventing-runs-). ## Starting Runs HCP Terraform has three main workflows for managing runs, and your chosen workflow determines when and how Terraform runs occur. For detailed information, see: - 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](/terraform/cloud-docs/run/cli), which uses Terraform's standard CLI tools to execute runs in HCP Terraform. You can use the following methods to initiate HCP Terraform runs: - Click the **+ New run** button on the workspace's page - Implement VCS webhooks - Run the standard `terraform apply` command when the CLI integration is configured - Call [the Runs API](/terraform/cloud-docs/api-docs/run) using any API tool ## Plans and Applies HCP Terraform enforces Terraform's division between _plan_ and _apply_ operations. It always plans first, then uses that plan's output for the apply. In the default configuration, HCP Terraform waits for user approval before running an apply, but you can configure workspaces to [automatically apply](/terraform/cloud-docs/workspaces/settings#auto-apply-and-manual-apply) successful plans. Some plans can't be auto-applied, like plans queued by [run triggers](/terraform/cloud-docs/workspaces/settings/run-triggers) or by users without permission to apply runs for the workspace. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) [permissions-citation]: #intentionally-unused---keep-for-maintainers If a plan contains no changes, HCP Terraform does not attempt to apply it. Instead, the run ends with a status of "Planned and finished". The [allow empty apply](/terraform/cloud-docs/run/modes-and-options#allow-empty-apply) run mode can override this behavior. ### Speculative Plans In addition to normal runs, HCP Terraform can run _speculative plans_ to test changes to a configuration during editing and code review. Speculative plans are plan-only runs. They show possible changes, and policies affected by those changes, but cannot apply any changes. Speculative plans can begin without waiting for other runs to finish because they don't affect real infrastructure. HCP Terraform lists past speculative plan runs alongside a workspace's other runs. There are three ways to run speculative plans: - In VCS-backed workspaces, pull requests start speculative plans, and the VCS provider's pull request interface includes a link to the plan. See [UI/VCS Runs: Speculative Plans on Pull Requests](/terraform/cloud-docs/run/ui#speculative-plans-on-pull-requests) for more details. - With the [CLI integration](/terraform/cli/cloud) configured, running `terraform plan` on the command line starts a speculative plan. The plan output streams to the terminal, and a link to the plan is also included. - The runs API creates speculative plans whenever the specified configuration version is marked as speculative. See [the `configuration-versions` API](/terraform/cloud-docs/api-docs/configuration-versions#create-a-configuration-version) for more information. #### Retry a speculative plan in the UI If a speculative plan fails due to an external factor, you can run it again using the "Retry Run" button on its page: Retrying a plan requires permission to queue plans for that workspace. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) Only failed or canceled plans can be retried. [permissions-citation]: #intentionally-unused---keep-for-maintainers Retrying the run will create a new run with the same configuration version. If it is a VCS-backed workspace, the pull request interface will receive the status of the new run, along with a link to the new run. ### Saved Plans -> **Version note:** Using saved plans from the CLI with HCP Terraform requires at least Terraform CLI v1.6.0. HCP Terraform also supports saved plan runs. If you have configured the [CLI integration](/terraform/cli/cloud) you can use `terraform plan -out <FILE>` to perform and save a plan, `terraform apply <FILE>` to apply a saved plan, and `terraform show <FILE>` to inspect a saved plan before applying it. You can also create saved plan runs via the API by using the `save-plan` option. Saved plan runs affect the run queue differently from normal runs, and can sometimes be automatically discarded. For more details, refer to [Run Modes and Options: Saved Plans](/terraform/cloud-docs/run/modes-and-options#saved-plans). ## Planning Modes and Options In addition to the normal run workflows described above, HCP Terraform supports destroy runs, refresh-only runs, and several planning options that can modify the behavior of a run. For more details, see [Run Modes and Options](/terraform/cloud-docs/run/modes-and-options). ## Run States HCP Terraform shows the progress of each run as it passes through each run state (pending, plan, policy check, apply, and completion). In some states, the run might require confirmation before continuing or ending; see [Managing Runs: Interacting with Runs](/terraform/cloud-docs/run/manage#interacting-with-runs) for more information. In the list of workspaces on HCP Terraform's main page, each workspace shows the state of the run it's currently processing. (Or, if no run is in progress, the state of the most recent completed run.) For full details about the stages of a run, see [Run States and Stages][]. [Run States and Stages]: /terraform/cloud-docs/run/states ## Import We recommend using [`import` blocks](/terraform/language/import), introduced in Terraform 1.5, to import resources in HCP Terraform. HCP Terraform does not support remote execution for the `terraform import` command. For this command the workspace acts only as a remote backend for Terraform state, with all execution occurring on your own workstations or continuous integration workers. Since `terraform import` runs locally, environment variables defined in the workspace are not available. Any environment variables required by the provider you're importing from must be defined within your local execution scope.
terraform
page title Remote Operations HCP Terraform description Run Terraform remotely through the UI API or CLI Learn how HCP Terraform manages runs Remote Operations Hands on Try the Get Started HCP Terraform terraform tutorials cloud get started utm source WEBSITE utm medium WEB IO utm offer ARTICLE PAGE utm content DOCS tutorials HCP Terraform provides a central interface for running Terraform within a large collaborative organization If you re accustomed to running Terraform from your workstation the way HCP Terraform manages runs can be unfamiliar This page describes the basics of how runs work in HCP Terraform Remote Operations HCP Terraform is designed as an execution platform for Terraform and can perform Terraform runs on its own disposable virtual machines This provides a consistent and reliable run environment and enables advanced features like Sentinel policy enforcement cost estimation notifications version control integration and more Terraform runs managed by HCP Terraform are called remote operations Remote runs can be initiated by webhooks from your VCS provider by UI controls within HCP Terraform by API calls or by Terraform CLI When using Terraform CLI to perform remote operations the progress of the run is streamed to the user s terminal to provide an experience equivalent to local operations Disabling Remote Operations execution mode terraform cloud docs workspaces settings execution mode Many of HCP Terraform s features rely on remote execution and are not available when using local operations This includes features like Sentinel policy enforcement cost estimation and notifications You can disable remote operations for any workspace by changing its Execution Mode execution mode to Local This causes the workspace to act only as a remote backend for Terraform state with all execution occurring on your own workstations or continuous integration workers Protecting Private Environments HCP Terraform agents terraform cloud docs agents are a paid feature that allows HCP Terraform to communicate with isolated private or on premises infrastructure The agent polls HCP Terraform or Terraform Enterprise for any changes to your configuration and executes the changes locally so you do not need to allow public ingress traffic to your resources Agents allow you to control infrastructure in private environments without modifying your network perimeter HCP Terraform agents also support running custom programs called hooks during strategic points of a Terraform run For example you may create a hook to dynamically download software required by the Terraform run or send an HTTP request to a system to kick off an external workflow Runs and Workspaces HCP Terraform always performs Terraform runs in the context of a workspace terraform cloud docs run remote operations The workspace serves the same role that a persistent working directory serves when running Terraform locally it provides the configuration state and variables for the run Configuration Versions Each workspace is associated with a particular Terraform configuration but that configuration is expected to change over time Thus HCP Terraform manages configurations as a series of configuration versions Most commonly a workspace is linked to a VCS repository and its configuration versions are tied to revisions in the specified VCS branch In workspaces that aren t linked to a repository new configuration versions can be uploaded via Terraform CLI or via the API Ordering and Timing Each workspace in HCP Terraform maintains its own queue of runs and processes those runs in order Whenever a new run is initiated it s added to the end of the queue If there s already a run in progress the new run won t start until the current one has completely finished HCP Terraform won t even plan the run yet because the current run might change what a future run would do Runs that are waiting for other runs to finish are in a pending state and a workspace might have any number of pending runs There are two exceptions to the run queue which can proceed at any time and do not block the progress of other runs Plan only runs The planning stages of saved plan runs terraform cloud docs run modes and options saved plans You can only apply a saved plan if no other run is in progress and applying that plan blocks the run queue as usual Terraform Enterprise does not yet support this workflow When you initiate a run HCP Terraform locks the run to a particular configuration version and set of variable values If you change variables or commit new code before the run finishes it will only affect future runs not runs that are already pending planning or awaiting apply Workspace Locks When a workspace is locked HCP Terraform can create new runs automatically or manually but those runs do not begin until you unlock the workspace When a run is in progress that run locks the workspace as described above under Ordering and Timing There are two kinds of run operation that can ignore workspace locking Plan only runs The planning stages of saved plan runs terraform cloud docs run modes and options saved plans You can only apply a saved plan if the workspace is unlocked and applying that plan locks the workspace as usual Terraform Enterprise does not yet support this workflow A user or team can also deliberately lock a workspace to perform maintenance or for any other reason For more details see Locking Workspaces Preventing Runs terraform cloud docs run manage locking workspaces preventing runs Starting Runs HCP Terraform has three main workflows for managing runs and your chosen workflow determines when and how Terraform runs occur For detailed information see 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 terraform cloud docs run cli which uses Terraform s standard CLI tools to execute runs in HCP Terraform You can use the following methods to initiate HCP Terraform runs Click the New run button on the workspace s page Implement VCS webhooks Run the standard terraform apply command when the CLI integration is configured Call the Runs API terraform cloud docs api docs run using any API tool Plans and Applies HCP Terraform enforces Terraform s division between plan and apply operations It always plans first then uses that plan s output for the apply In the default configuration HCP Terraform waits for user approval before running an apply but you can configure workspaces to automatically apply terraform cloud docs workspaces settings auto apply and manual apply successful plans Some plans can t be auto applied like plans queued by run triggers terraform cloud docs workspaces settings run triggers or by users without permission to apply runs for the workspace More about permissions terraform cloud docs users teams organizations permissions permissions citation intentionally unused keep for maintainers If a plan contains no changes HCP Terraform does not attempt to apply it Instead the run ends with a status of Planned and finished The allow empty apply terraform cloud docs run modes and options allow empty apply run mode can override this behavior Speculative Plans In addition to normal runs HCP Terraform can run speculative plans to test changes to a configuration during editing and code review Speculative plans are plan only runs They show possible changes and policies affected by those changes but cannot apply any changes Speculative plans can begin without waiting for other runs to finish because they don t affect real infrastructure HCP Terraform lists past speculative plan runs alongside a workspace s other runs There are three ways to run speculative plans In VCS backed workspaces pull requests start speculative plans and the VCS provider s pull request interface includes a link to the plan See UI VCS Runs Speculative Plans on Pull Requests terraform cloud docs run ui speculative plans on pull requests for more details With the CLI integration terraform cli cloud configured running terraform plan on the command line starts a speculative plan The plan output streams to the terminal and a link to the plan is also included The runs API creates speculative plans whenever the specified configuration version is marked as speculative See the configuration versions API terraform cloud docs api docs configuration versions create a configuration version for more information Retry a speculative plan in the UI If a speculative plan fails due to an external factor you can run it again using the Retry Run button on its page Retrying a plan requires permission to queue plans for that workspace More about permissions terraform cloud docs users teams organizations permissions Only failed or canceled plans can be retried permissions citation intentionally unused keep for maintainers Retrying the run will create a new run with the same configuration version If it is a VCS backed workspace the pull request interface will receive the status of the new run along with a link to the new run Saved Plans Version note Using saved plans from the CLI with HCP Terraform requires at least Terraform CLI v1 6 0 HCP Terraform also supports saved plan runs If you have configured the CLI integration terraform cli cloud you can use terraform plan out FILE to perform and save a plan terraform apply FILE to apply a saved plan and terraform show FILE to inspect a saved plan before applying it You can also create saved plan runs via the API by using the save plan option Saved plan runs affect the run queue differently from normal runs and can sometimes be automatically discarded For more details refer to Run Modes and Options Saved Plans terraform cloud docs run modes and options saved plans Planning Modes and Options In addition to the normal run workflows described above HCP Terraform supports destroy runs refresh only runs and several planning options that can modify the behavior of a run For more details see Run Modes and Options terraform cloud docs run modes and options Run States HCP Terraform shows the progress of each run as it passes through each run state pending plan policy check apply and completion In some states the run might require confirmation before continuing or ending see Managing Runs Interacting with Runs terraform cloud docs run manage interacting with runs for more information In the list of workspaces on HCP Terraform s main page each workspace shows the state of the run it s currently processing Or if no run is in progress the state of the most recent completed run For full details about the stages of a run see Run States and Stages Run States and Stages terraform cloud docs run states Import We recommend using import blocks terraform language import introduced in Terraform 1 5 to import resources in HCP Terraform HCP Terraform does not support remote execution for the terraform import command For this command the workspace acts only as a remote backend for Terraform state with all execution occurring on your own workstations or continuous integration workers Since terraform import runs locally environment variables defined in the workspace are not available Any environment variables required by the provider you re importing from must be defined within your local execution scope
terraform Terraform relies on provider plugins to manage resources In most cases Terraform can automatically download the required plugins but there are cases where plugins must be managed explicitly Installing Software in the Run Environment Learn how to install Terraform providers and additional software on Terraform Cloud workers including cloud CLIs or configuration management tools page title Installing Software in the Run Environment Runs HCP Terraform
--- page_title: Installing Software in the Run Environment - Runs - HCP Terraform description: >- Learn how to install Terraform providers and additional software on Terraform Cloud workers, including cloud CLIs or configuration management tools. --- # Installing Software in the Run Environment Terraform relies on provider plugins to manage resources. In most cases, Terraform can automatically download the required plugins, but there are cases where plugins must be managed explicitly. In rare cases, it might also be necessary to install extra software on the Terraform worker, such as a configuration management tool or cloud CLI. ## Installing Terraform Providers The mechanics of provider installation changed in Terraform 0.13, thanks to the introduction of the [Terraform Registry][registry] for providers which allows custom and community providers to be installed via `terraform init`. Prior to Terraform 0.13, Terraform could only automatically install providers distributed by HashiCorp. ### Terraform 0.13 and later #### Providers From the Terraform Registry The [Terraform Registry][registry] allows anyone to publish and distribute providers which can be automatically downloaded and installed via `terraform init`. Terraform Enterprise instances must be able to access `registry.terraform.io` to use providers from the public registry; otherwise, you can install providers using [the `terraform-bundle` tool][bundle]. [registry]: https://registry.terraform.io/browse/providers #### In-House Providers If you have a custom provider that you'd rather not publish in the public Terraform Registry, you have a few options: - Add the provider binary to the VCS repo (or manually-uploaded configuration version). Place the compiled `linux_amd64` version of the plugin at `terraform.d/plugins/<SOURCE HOST>/<SOURCE NAMESPACE>/<PLUGIN NAME>/<VERSION>/linux_amd64`, relative to the root of the directory. The source host and namespace will need to match the source given in the `required_providers` block within the configuration, but can otherwise be arbitrary identifiers. For instance, if your `required_providers` block looks like this: ``` terraform { required_providers { custom = { source = "my-host/my-namespace/custom" version = "1.0.0" } } } ``` HCP Terraform will be able to use your compiled provider if you place it at `terraform.d/plugins/my-host/my-namespace/custom/1.0.0/linux_amd64/terraform-provider-custom`. - Use a privately-owned provider registry service which implements the [provider registry protocol](/terraform/internals/provider-registry-protocol) to distribute custom providers. Be sure to include the full [source address](/terraform/language/providers/requirements#source-addresses), including the hostname, when referencing providers. - **Terraform Enterprise only:** Use [the `terraform-bundle` tool][bundle] to add custom providers. -> **Note:** Using a [network mirror](/terraform/internals/provider-network-mirror-protocol) to host custom providers for installation is not currently supported in HCP Terraform, since the network mirror cannot be activated without a [`provider_installation`](/terraform/cli/config/config-file#explicit-installation-method-configuration) block in the CLI configuration file. ### Terraform 0.12 and earlier #### Providers Distributed by HashiCorp HCP Terraform can automatically install providers distributed by HashiCorp. Terraform Enterprise instances can do this as well as long as they can access `releases.hashicorp.com`. If that isn't feasible due to security requirements, you can manually install providers. Use [the `terraform-bundle` tool][bundle] to build a custom version of Terraform that includes the necessary providers, and configure your workspaces to use that bundled version. [bundle]: https://github.com/hashicorp/terraform/tree/master/tools/terraform-bundle#installing-a-bundle-in-on-premises-terraform-enterprise #### Custom and Community Providers To use community providers or your own custom providers with Terraform versions prior to 0.13, you must install them yourself. There are two ways to accomplish this: - Add the provider binary to the VCS repo (or manually-uploaded configuration version) for any workspace that uses it. Place the compiled `linux_amd64` version of the plugin at `terraform.d/plugins/linux_amd64/<PLUGIN NAME>` (as a relative path from the root of the working directory). The plugin name should follow the [naming scheme](/terraform/language/v1.1.x/configuration-0-11/providers#plugin-names-and-versions) and the plugin file must have read and execute permissions. (Third-party plugins are often distributed with an appropriate filename already set in the distribution archive.) You can add plugins directly to a configuration repo, or you can add them as Git submodules and symlink the executable files into `terraform.d/plugins/`. Submodules are a good choice when many workspaces use the same custom provider, since they keep your repos smaller. If using submodules, enable the ["Include submodules on clone" setting](/terraform/cloud-docs/workspaces/settings/vcs#include-submodules-on-clone) on any affected workspace. - **Terraform Enterprise only:** Use [the `terraform-bundle` tool][bundle] to add custom providers to a custom Terraform version. This keeps custom providers out of your configuration repos entirely, and is easier to update when many workspaces use the same provider. ## Installing Additional Tools ### Avoid Installing Extra Software Whenever possible, don't install software on the worker. There are a number of reasons for this: - Provisioners are a last resort in Terraform; they greatly increase the risk of creating unknown states with unmanaged and partially-managed infrastructure, and the `local-exec` provisioner is especially hazardous. [The Terraform CLI docs on provisioners](/terraform/language/resources/provisioners/syntax#provisioners-are-a-last-resort) explain the hazards in more detail, with more information about the preferred alternatives. (In summary: use Packer, use cloud-init, try to make your infrastructure more immutable, and always prefer real provider features.) - We don't guarantee the stability of the operating system on the Terraform build workers. It's currently the latest version of Ubuntu LTS, but we reserve the right to change that at any time. - The build workers are disposable and are destroyed after each use, which makes managing extra software even more complex than when running Terraform CLI in a persistent environment. Custom software must be installed on every run, which also increases run times. ### Only Install Standalone Binaries HCP Terraform does not allow you to elevate a command's permissions with `sudo` during Terraform runs. This means you cannot install packages using the worker OS's normal package management tools. However, you can install and execute standalone binaries in Terraform's working directory. You have two options for getting extra software into the configuration directory: - Include it in the configuration repository as a submodule. (Make sure the workspace is configured to clone submodules.) - Use `local-exec` to download it with `curl`. For example: ```hcl resource "aws_instance" "example" { ami = "${var.ami}" instance_type = "t2.micro" provisioner "local-exec" { command = <<EOH curl -o jq https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64 chmod 0755 jq # Do some kind of JSON processing with ./jq EOH } } ``` When downloading software with `local-exec`, try to associate the provisioner block with the resource(s) that the software will interact with. If you use a null resource with a `local-exec` provisioner, you must ensure it can be properly configured with [triggers](/terraform/language/resources/provisioners/null_resource#example-usage). Otherwise, a null resource with the `local-exec` provisioner will only install software on the initial run where the `null_resource` is created. The `null_resource` will not be automatically recreated in subsequent runs and the related software won't be installed, which may cause runs to encounter errors. -> **Note:** Terraform Enterprise instances can be configured to allow `sudo` commands during Terraform runs. However, even when `sudo` is allowed, using the worker OS's package tools during runs is still usually a bad idea. You will have a much better experience if you can move your provisioner actions into a custom provider or an immutable machine image.
terraform
page title Installing Software in the Run Environment Runs HCP Terraform description Learn how to install Terraform providers and additional software on Terraform Cloud workers including cloud CLIs or configuration management tools Installing Software in the Run Environment Terraform relies on provider plugins to manage resources In most cases Terraform can automatically download the required plugins but there are cases where plugins must be managed explicitly In rare cases it might also be necessary to install extra software on the Terraform worker such as a configuration management tool or cloud CLI Installing Terraform Providers The mechanics of provider installation changed in Terraform 0 13 thanks to the introduction of the Terraform Registry registry for providers which allows custom and community providers to be installed via terraform init Prior to Terraform 0 13 Terraform could only automatically install providers distributed by HashiCorp Terraform 0 13 and later Providers From the Terraform Registry The Terraform Registry registry allows anyone to publish and distribute providers which can be automatically downloaded and installed via terraform init Terraform Enterprise instances must be able to access registry terraform io to use providers from the public registry otherwise you can install providers using the terraform bundle tool bundle registry https registry terraform io browse providers In House Providers If you have a custom provider that you d rather not publish in the public Terraform Registry you have a few options Add the provider binary to the VCS repo or manually uploaded configuration version Place the compiled linux amd64 version of the plugin at terraform d plugins SOURCE HOST SOURCE NAMESPACE PLUGIN NAME VERSION linux amd64 relative to the root of the directory The source host and namespace will need to match the source given in the required providers block within the configuration but can otherwise be arbitrary identifiers For instance if your required providers block looks like this terraform required providers custom source my host my namespace custom version 1 0 0 HCP Terraform will be able to use your compiled provider if you place it at terraform d plugins my host my namespace custom 1 0 0 linux amd64 terraform provider custom Use a privately owned provider registry service which implements the provider registry protocol terraform internals provider registry protocol to distribute custom providers Be sure to include the full source address terraform language providers requirements source addresses including the hostname when referencing providers Terraform Enterprise only Use the terraform bundle tool bundle to add custom providers Note Using a network mirror terraform internals provider network mirror protocol to host custom providers for installation is not currently supported in HCP Terraform since the network mirror cannot be activated without a provider installation terraform cli config config file explicit installation method configuration block in the CLI configuration file Terraform 0 12 and earlier Providers Distributed by HashiCorp HCP Terraform can automatically install providers distributed by HashiCorp Terraform Enterprise instances can do this as well as long as they can access releases hashicorp com If that isn t feasible due to security requirements you can manually install providers Use the terraform bundle tool bundle to build a custom version of Terraform that includes the necessary providers and configure your workspaces to use that bundled version bundle https github com hashicorp terraform tree master tools terraform bundle installing a bundle in on premises terraform enterprise Custom and Community Providers To use community providers or your own custom providers with Terraform versions prior to 0 13 you must install them yourself There are two ways to accomplish this Add the provider binary to the VCS repo or manually uploaded configuration version for any workspace that uses it Place the compiled linux amd64 version of the plugin at terraform d plugins linux amd64 PLUGIN NAME as a relative path from the root of the working directory The plugin name should follow the naming scheme terraform language v1 1 x configuration 0 11 providers plugin names and versions and the plugin file must have read and execute permissions Third party plugins are often distributed with an appropriate filename already set in the distribution archive You can add plugins directly to a configuration repo or you can add them as Git submodules and symlink the executable files into terraform d plugins Submodules are a good choice when many workspaces use the same custom provider since they keep your repos smaller If using submodules enable the Include submodules on clone setting terraform cloud docs workspaces settings vcs include submodules on clone on any affected workspace Terraform Enterprise only Use the terraform bundle tool bundle to add custom providers to a custom Terraform version This keeps custom providers out of your configuration repos entirely and is easier to update when many workspaces use the same provider Installing Additional Tools Avoid Installing Extra Software Whenever possible don t install software on the worker There are a number of reasons for this Provisioners are a last resort in Terraform they greatly increase the risk of creating unknown states with unmanaged and partially managed infrastructure and the local exec provisioner is especially hazardous The Terraform CLI docs on provisioners terraform language resources provisioners syntax provisioners are a last resort explain the hazards in more detail with more information about the preferred alternatives In summary use Packer use cloud init try to make your infrastructure more immutable and always prefer real provider features We don t guarantee the stability of the operating system on the Terraform build workers It s currently the latest version of Ubuntu LTS but we reserve the right to change that at any time The build workers are disposable and are destroyed after each use which makes managing extra software even more complex than when running Terraform CLI in a persistent environment Custom software must be installed on every run which also increases run times Only Install Standalone Binaries HCP Terraform does not allow you to elevate a command s permissions with sudo during Terraform runs This means you cannot install packages using the worker OS s normal package management tools However you can install and execute standalone binaries in Terraform s working directory You have two options for getting extra software into the configuration directory Include it in the configuration repository as a submodule Make sure the workspace is configured to clone submodules Use local exec to download it with curl For example hcl resource aws instance example ami var ami instance type t2 micro provisioner local exec command EOH curl o jq https github com stedolan jq releases download jq 1 6 jq linux64 chmod 0755 jq Do some kind of JSON processing with jq EOH When downloading software with local exec try to associate the provisioner block with the resource s that the software will interact with If you use a null resource with a local exec provisioner you must ensure it can be properly configured with triggers terraform language resources provisioners null resource example usage Otherwise a null resource with the local exec provisioner will only install software on the initial run where the null resource is created The null resource will not be automatically recreated in subsequent runs and the related software won t be installed which may cause runs to encounter errors Note Terraform Enterprise instances can be configured to allow sudo commands during Terraform runs However even when sudo is allowed using the worker OS s package tools during runs is still usually a bad idea You will have a much better experience if you can move your provisioner actions into a custom provider or an immutable machine image
terraform HCP Terraform has three workflows for managing Terraform runs The UI and VCS driven Run Workflow page title UI VCS driven Runs Runs HCP Terraform Workspaces are associated with a VCS repository branch and HCP Terraform automatically queues runs when new commits are merged
--- page_title: UI/VCS-driven Runs - Runs - HCP Terraform description: >- Workspaces are associated with a VCS repository branch, and HCP Terraform automatically queues runs when new commits are merged. --- # The UI- and VCS-driven Run Workflow HCP Terraform has three workflows for managing Terraform runs. - The UI/VCS-driven run workflow described below, 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](/terraform/cloud-docs/run/cli), which uses Terraform's standard CLI tools to execute runs in HCP Terraform. ## Summary In the UI and VCS workflow, every workspace is associated with a specific branch of a VCS repo of Terraform configurations. HCP Terraform registers webhooks with your VCS provider when you create a workspace, then automatically queues a Terraform run whenever new commits are merged to that branch of workspace's linked repository. HCP Terraform also performs a [speculative plan][] when a pull request is opened against that branch. HCP Terraform posts a link to the plan in the pull request, and re-runs the plan if the pull request is updated. [speculative plan]: /terraform/cloud-docs/run/remote-operations#speculative-plans The Terraform code for a normal run always comes from version control, and is always associated with a specific commit. ## Automatically Starting Runs In a workspace linked to a VCS repository, runs start automatically when you merge or commit changes to version control. If you use GitHub as your VCS provider and merge a PR changing 300 or more files, HCP Terraform automatically triggers runs for every workspace connected to that repository. The GitHub API has a limit of 300 reported changed files for a PR merge. To address this, HCP Terraform initiates workspace runs proactively, preventing oversight of file changes beyond this limit. A workspace is linked to one branch of a VCS repository and ignores changes to other branches. You can specify which files and directories within your repository trigger runs. HCP Terraform can also automatically trigger runs when you create Git tags. Refer to [Automatic Run Triggering](/terraform/cloud-docs/workspaces/settings/vcs#automatic-run-triggering) for details. -> **Note:** A workspace with no runs will not accept new runs via VCS webhook. At least one run must be manually queued to confirm that the workspace is ready for further runs. A workspace will not process a webhook if the workspace previously processed a webhook with the same commit SHA and created a run. To trigger a run, create a new commit. If a workspace receives a webhook with a previously processed commit, HCP Terraform will add a new event to the [VCS Events](/terraform/cloud-docs/vcs#viewing-events) page documenting the received webhook. ## Manually Starting Runs You can manually trigger a run using the UI. Manual runs let you apply configuration changes when you update variable values but the configuration in version control is unchanged. You must manually trigger an initial run in any new VCS-driven workspace. To start a run, click the **+ New run** button on the workspace page. This opens a **Start a new run** dialog. Select the run mode and provide an optional message. Review the [run modes documentation](/terraform/cloud-docs/run/modes-and-options) for more detail on supported options. Run modes that have a plan phase support debugging mode. This is equivalent to setting the `TF_LOG` environment variable to `TRACE` for this run only. To enable debugging, click **Additional planning options** under the run mode and click **Enable debugging mode**. See [Debugging Terraform](/terraform/internals/debugging) for more information. To [replace](/terraform/cloud-docs/run/modes-and-options#replacing-selected-resources) specific resources as part of a standard plan and apply run, expand the **Additional planning options** section and select the resources to replace. Manually starting a run requires permission to queue plans for the workspace. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) [permissions-citation]: #intentionally-unused---keep-for-maintainers If the workspace has a plan that is still in the [plan stage](/terraform/cloud-docs/run/states#the-plan-stage) when a new plan is queued, you can either wait for it to complete, or visit the **Current Run** page and click **Run this plan now**. Be aware that this action terminates the current plan and unlocks the workspace, which can lead to anomalies in behavior, but can be useful if the plans are long-running and the current plan does not have all the desired changes. ## Automatically cancel plan-only runs triggered by outdated commits Refer to [Automatically cancel plan-only runs triggered by outdated commits](/terraform/cloud-docs/users-teams-organizations/organizations/vcs-speculative-plan-management) for additional information. ## Confirming or Discarding Plans By default, run plans require confirmation before HCP Terraform will apply them. Users with permission to apply runs for the workspace can navigate to a run that has finished planning and click the "Confirm & Apply" or "Discard Plan" button to finish or cancel a run. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) If necessary, use the "View Plan" button for more details about what the run will change. [permissions-citation]: #intentionally-unused---keep-for-maintainers ![confirm button](/img/docs/runs-confirm.png) Users can also leave comments if there's something unusual involved in a run. Note that once the plan stage is completed, until you apply or discard a plan, HCP Terraform can't start another run in that workspace. ### Auto apply If you would rather automatically apply plans that don't have errors, you can [enable auto apply](/terraform/cloud-docs/workspaces/settings#auto-apply-and-manual-apply) on the workspace's "General Settings" page. Some plans can't be auto-applied, like plans queued by [run triggers](/terraform/cloud-docs/workspaces/settings/run-triggers) or by users without permission to apply runs. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) [permissions-citation]: #intentionally-unused---keep-for-maintainers ## Speculative Plans on Pull Requests To help you review proposed changes, HCP Terraform can automatically run [speculative plans][speculative plan] for pull requests or merge requests. ### Viewing Pull Request Plans You can view speculative plans in a workspace's list of normal runs. Additionally, HCP Terraform adds a link to the run in the pull request itself, along with an indicator of the run's status. A single pull request can include links to multiple plans, depending on how many workspaces connect to the destination branch. If you update a pull request, HCP Terraform performs new speculative plans and update the links. Although any contributor to the repository can see the status indicators for pull request plans, only members of your HCP Terraform organization with permission to read runs for the affected workspaces can click through and view the complete plan output. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) [permissions-citation]: #intentionally-unused---keep-for-maintainers ### Rules for Triggering Pull Request Plans Whenever a pull request is _created or updated,_ HCP Terraform checks whether it should run speculative plans in workspaces connected to that repository, based on the following rules: - Only pull requests that originate from within the same repository can trigger speculative plans. To avoid executing malicious code or exposing sensitive information, HCP Terraform doesn't run speculative plans for pull requests that originate from forks of a repository. -> **Note:** On Terraform Enterprise, administrators can choose to allow speculative plans on pull requests that originate from forks. To learn more about this setting, refer to the [general settings documentation](/terraform/enterprise/admin/application/general#allow-speculative-plans-on-pull-requests-from-forks) - Pull requests can only trigger runs in workspaces where automatic speculative plans are allowed. You can [disable automatic speculative plans](/terraform/cloud-docs/workspaces/settings/vcs#automatic-speculative-plans) in a workspace's VCS settings. - A pull request will only trigger speculative plans in workspaces that are connected to that pull request's destination branch. The destination branch is the branch that a pull request proposes to make changes to; this is often the repository's main branch, but not always. - If a workspace is configured to only treat certain directories in a repository as relevant, pull requests that don't affect those directories won't trigger speculative plans in that workspace. For more information, see [VCS settings: automatic run triggering](/terraform/cloud-docs/workspaces/settings/vcs#automatic-run-triggering). -> **Note:** If HCP Terraform skips a plan because the changes weren't relevant, it will still post a passing commit status to the pull request. - HCP Terraform does not update the status checks on a pull request with the status of an associated apply. This means that a commit with a successful plan but an errored apply will still show the passing commit status from the plan. ### Contents of Pull Request Plans Speculative plans for pull requests use the contents of the head branch (the branch that the PR proposes to merge into the destination branch), and they compare against the workspace's current state at the time of the plan. This means that if the destination branch changes significantly after the head branch is created, the speculative plan might not accurately show the results of accepting the PR. To get a more accurate view, you can rebase the head branch onto a more recent commit, or merge the destination branch into the head branch. ## Testing Terraform Upgrades with Speculative Plans You can start a new [speculative plan][speculative plan] in the UI with the workspace's current configuration version and any Terraform version available to the organization. 1. Click **+ New run**. 1. Select **Plan only** as the run type. 1. Select a version from the **Choose Terraform version** menu. The speculative plan will use this version without changing the workspace's settings. 1. Click **Start run**. If the run is successful, you can change the workspace's Terraform version and [upgrade the state](/terraform/cloud-docs/workspaces/state#upgrading-state). ## Speculative Plans During Development You can also use the CLI to run speculative plans on demand before making a pull request. Refer to the [CLI-driven run workflow](/terraform/cloud-docs/run/cli#remote-speculative-plans) for more details.
terraform
page title UI VCS driven Runs Runs HCP Terraform description Workspaces are associated with a VCS repository branch and HCP Terraform automatically queues runs when new commits are merged The UI and VCS driven Run Workflow HCP Terraform has three workflows for managing Terraform runs The UI VCS driven run workflow described below 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 terraform cloud docs run cli which uses Terraform s standard CLI tools to execute runs in HCP Terraform Summary In the UI and VCS workflow every workspace is associated with a specific branch of a VCS repo of Terraform configurations HCP Terraform registers webhooks with your VCS provider when you create a workspace then automatically queues a Terraform run whenever new commits are merged to that branch of workspace s linked repository HCP Terraform also performs a speculative plan when a pull request is opened against that branch HCP Terraform posts a link to the plan in the pull request and re runs the plan if the pull request is updated speculative plan terraform cloud docs run remote operations speculative plans The Terraform code for a normal run always comes from version control and is always associated with a specific commit Automatically Starting Runs In a workspace linked to a VCS repository runs start automatically when you merge or commit changes to version control If you use GitHub as your VCS provider and merge a PR changing 300 or more files HCP Terraform automatically triggers runs for every workspace connected to that repository The GitHub API has a limit of 300 reported changed files for a PR merge To address this HCP Terraform initiates workspace runs proactively preventing oversight of file changes beyond this limit A workspace is linked to one branch of a VCS repository and ignores changes to other branches You can specify which files and directories within your repository trigger runs HCP Terraform can also automatically trigger runs when you create Git tags Refer to Automatic Run Triggering terraform cloud docs workspaces settings vcs automatic run triggering for details Note A workspace with no runs will not accept new runs via VCS webhook At least one run must be manually queued to confirm that the workspace is ready for further runs A workspace will not process a webhook if the workspace previously processed a webhook with the same commit SHA and created a run To trigger a run create a new commit If a workspace receives a webhook with a previously processed commit HCP Terraform will add a new event to the VCS Events terraform cloud docs vcs viewing events page documenting the received webhook Manually Starting Runs You can manually trigger a run using the UI Manual runs let you apply configuration changes when you update variable values but the configuration in version control is unchanged You must manually trigger an initial run in any new VCS driven workspace To start a run click the New run button on the workspace page This opens a Start a new run dialog Select the run mode and provide an optional message Review the run modes documentation terraform cloud docs run modes and options for more detail on supported options Run modes that have a plan phase support debugging mode This is equivalent to setting the TF LOG environment variable to TRACE for this run only To enable debugging click Additional planning options under the run mode and click Enable debugging mode See Debugging Terraform terraform internals debugging for more information To replace terraform cloud docs run modes and options replacing selected resources specific resources as part of a standard plan and apply run expand the Additional planning options section and select the resources to replace Manually starting a run requires permission to queue plans for the workspace More about permissions terraform cloud docs users teams organizations permissions permissions citation intentionally unused keep for maintainers If the workspace has a plan that is still in the plan stage terraform cloud docs run states the plan stage when a new plan is queued you can either wait for it to complete or visit the Current Run page and click Run this plan now Be aware that this action terminates the current plan and unlocks the workspace which can lead to anomalies in behavior but can be useful if the plans are long running and the current plan does not have all the desired changes Automatically cancel plan only runs triggered by outdated commits Refer to Automatically cancel plan only runs triggered by outdated commits terraform cloud docs users teams organizations organizations vcs speculative plan management for additional information Confirming or Discarding Plans By default run plans require confirmation before HCP Terraform will apply them Users with permission to apply runs for the workspace can navigate to a run that has finished planning and click the Confirm Apply or Discard Plan button to finish or cancel a run More about permissions terraform cloud docs users teams organizations permissions If necessary use the View Plan button for more details about what the run will change permissions citation intentionally unused keep for maintainers confirm button img docs runs confirm png Users can also leave comments if there s something unusual involved in a run Note that once the plan stage is completed until you apply or discard a plan HCP Terraform can t start another run in that workspace Auto apply If you would rather automatically apply plans that don t have errors you can enable auto apply terraform cloud docs workspaces settings auto apply and manual apply on the workspace s General Settings page Some plans can t be auto applied like plans queued by run triggers terraform cloud docs workspaces settings run triggers or by users without permission to apply runs More about permissions terraform cloud docs users teams organizations permissions permissions citation intentionally unused keep for maintainers Speculative Plans on Pull Requests To help you review proposed changes HCP Terraform can automatically run speculative plans speculative plan for pull requests or merge requests Viewing Pull Request Plans You can view speculative plans in a workspace s list of normal runs Additionally HCP Terraform adds a link to the run in the pull request itself along with an indicator of the run s status A single pull request can include links to multiple plans depending on how many workspaces connect to the destination branch If you update a pull request HCP Terraform performs new speculative plans and update the links Although any contributor to the repository can see the status indicators for pull request plans only members of your HCP Terraform organization with permission to read runs for the affected workspaces can click through and view the complete plan output More about permissions terraform cloud docs users teams organizations permissions permissions citation intentionally unused keep for maintainers Rules for Triggering Pull Request Plans Whenever a pull request is created or updated HCP Terraform checks whether it should run speculative plans in workspaces connected to that repository based on the following rules Only pull requests that originate from within the same repository can trigger speculative plans To avoid executing malicious code or exposing sensitive information HCP Terraform doesn t run speculative plans for pull requests that originate from forks of a repository Note On Terraform Enterprise administrators can choose to allow speculative plans on pull requests that originate from forks To learn more about this setting refer to the general settings documentation terraform enterprise admin application general allow speculative plans on pull requests from forks Pull requests can only trigger runs in workspaces where automatic speculative plans are allowed You can disable automatic speculative plans terraform cloud docs workspaces settings vcs automatic speculative plans in a workspace s VCS settings A pull request will only trigger speculative plans in workspaces that are connected to that pull request s destination branch The destination branch is the branch that a pull request proposes to make changes to this is often the repository s main branch but not always If a workspace is configured to only treat certain directories in a repository as relevant pull requests that don t affect those directories won t trigger speculative plans in that workspace For more information see VCS settings automatic run triggering terraform cloud docs workspaces settings vcs automatic run triggering Note If HCP Terraform skips a plan because the changes weren t relevant it will still post a passing commit status to the pull request HCP Terraform does not update the status checks on a pull request with the status of an associated apply This means that a commit with a successful plan but an errored apply will still show the passing commit status from the plan Contents of Pull Request Plans Speculative plans for pull requests use the contents of the head branch the branch that the PR proposes to merge into the destination branch and they compare against the workspace s current state at the time of the plan This means that if the destination branch changes significantly after the head branch is created the speculative plan might not accurately show the results of accepting the PR To get a more accurate view you can rebase the head branch onto a more recent commit or merge the destination branch into the head branch Testing Terraform Upgrades with Speculative Plans You can start a new speculative plan speculative plan in the UI with the workspace s current configuration version and any Terraform version available to the organization 1 Click New run 1 Select Plan only as the run type 1 Select a version from the Choose Terraform version menu The speculative plan will use this version without changing the workspace s settings 1 Click Start run If the run is successful you can change the workspace s Terraform version and upgrade the state terraform cloud docs workspaces state upgrading state Speculative Plans During Development You can also use the CLI to run speculative plans on demand before making a pull request Refer to the CLI driven run workflow terraform cloud docs run cli remote speculative plans for more details
terraform HCP Terraform has three workflows for managing Terraform runs trigger runs page title API driven Runs Runs HCP Terraform The API driven Run Workflow External tools communicate with HCP Terraform to upload configurations and
--- page_title: API-driven Runs - Runs - HCP Terraform description: >- External tools communicate with HCP Terraform to upload configurations and trigger runs. --- # The API-driven Run Workflow 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 described below, which is more flexible but requires you to create some tooling. - The [CLI-driven run workflow](/terraform/cloud-docs/run/cli), which uses Terraform's standard CLI tools to execute runs in HCP Terraform. ## Summary In the API-driven workflow, workspaces are not directly associated with a VCS repo, and runs are not driven by webhooks on your VCS provider. Instead, one of your organization's other tools is in charge of deciding when configuration has changed and a run should occur. Usually this is something like a CI system, or something else capable of monitoring changes to your Terraform code and performing actions in response. Once your other tooling has decided a run should occur, it must make a series of calls to HCP Terraform's `runs` and `configuration-versions` APIs to upload configuration files and perform a run with them. For the exact series of API calls, see the [pushing a new configuration version](#pushing-a-new-configuration-version) section. The most significant difference in this workflow is that HCP Terraform _does not_ fetch configuration files from version control. Instead, your own tooling must upload the configurations as a `.tar.gz` file. This allows you to work with configurations from unsupported version control systems, automatically generate Terraform configurations from some other source of data, or build a variety of other integrations. ~> **Important:** The script below is provided to illustrate the run process, and is not intended for production use. If you want to drive HCP Terraform runs from the command line, please see the [CLI-driven run workflow](/terraform/cloud-docs/run/cli). ## Pushing a New Configuration Version Pushing a new configuration to an existing workspace is a multi-step process. This section walks through each step in detail, using an example bash script to illustrate. You need queue plans permission to create new configuration versions for the workspace. Refer to the [permissions](/terraform/cloud-docs/users-teams-organizations/permissions#general-workspace-permissions) documentation for more details. [permissions-citation]: #intentionally-unused---keep-for-maintainers ### 1. Define Variables To perform an upload, a few user parameters must be set: - **path_to_content_directory** is the folder with the terraform configuration. There must be at least one `.tf` file in the root of this path. - **organization** is the organization name (not ID) for your HCP Terraform organization. - **workspace** is the workspace name (not ID) in the HCP Terraform organization. - **$TOKEN** is the API Token used for [authenticating with the HCP Terraform API](/terraform/cloud-docs/api-docs#authentication). This script extracts the `path_to_content_directory`, `organization`, and `workspace` from command line arguments, and expects the `$TOKEN` as an environment variable. ```bash #!/bin/bash if [ -z "$1" ] || [ -z "$2" ]; then echo "Usage: $0 <path_to_content_directory> <organization>/<workspace>" exit 0 fi CONTENT_DIRECTORY="$1" ORG_NAME="$(cut -d'/' -f1 <<<"$2")" WORKSPACE_NAME="$(cut -d'/' -f2 <<<"$2")" ``` ### 2. Create the File for Upload The [configuration version API](/terraform/cloud-docs/api-docs/configuration-versions) requires a `tar.gz` file to use the configuration version for a run, so you must package the directory containing the Terraform configuration into a `tar.gz` file. ~> **Important:** The configuration directory must be the root of the tar file, with no intermediate directories. In other words, when the tar file is extracted the result must be paths like `./main.tf` rather than `./terraform-appserver/main.tf`. ```bash UPLOAD_FILE_NAME="./content-$(date +%s).tar.gz" tar -zcvf "$UPLOAD_FILE_NAME" -C "$CONTENT_DIRECTORY" . ``` ### 3. Look Up the Workspace ID The first step identified the organization name and the workspace name; however, the [configuration version API](/terraform/cloud-docs/api-docs/configuration-versions) expects the workspace ID. As such, the ID has to be looked up. If the workspace ID is already known, this step can be skipped. This step uses the [`jq` tool](https://stedolan.github.io/jq/) to parse the JSON output and extract the ID value into the `WORKSPACE_ID` variable. ```bash WORKSPACE_ID=($(curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/organizations/$ORG_NAME/workspaces/$WORKSPACE_NAME \ | jq -r '.data.id')) ``` ### 4. Create a New Configuration Version Before uploading the configuration files, you must create a `configuration-version` to associate uploaded content with the workspace. This API call performs two tasks: it creates the new configuration version and it extracts the upload URL to be used in the next step. ```bash echo '{"data":{"type":"configuration-versions"}}' > ./create_config_version.json UPLOAD_URL=($(curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @create_config_version.json \ https://app.terraform.io/api/v2/workspaces/$WORKSPACE_ID/configuration-versions \ | jq -r '.data.attributes."upload-url"')) ``` ### 5. Upload the Configuration Content File Next, upload the configuration version `tar.gz` file to the upload URL extracted from the previous step. If a file is not uploaded, the configuration version will not be usable, since it will have no Terraform configuration files. HCP Terraform automatically creates a new run with a plan once the new file is uploaded. If the workspace is configured to auto-apply, it will also apply if the plan succeeds; otherwise, an apply can be triggered via the [Run Apply API](/terraform/cloud-docs/api-docs/run#apply). If the API token used for the upload lacks permission to apply runs for the workspace, the run can't be auto-applied. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) [permissions-citation]: #intentionally-unused---keep-for-maintainers ```bash curl \ --header "Content-Type: application/octet-stream" \ --request PUT \ --data-binary @"$UPLOAD_FILE_NAME" \ $UPLOAD_URL ``` ### 6. Delete Temporary Files In the previous steps a few files were created; they are no longer needed, so they should be deleted. ```bash rm "$UPLOAD_FILE_NAME" rm ./create_config_version.json ``` ### Complete Script Combine all of the code blocks into a single file, `./terraform-enterprise-push.sh` and give execution permission to create a combined bash script to perform all of the operations. ```shell chmod +x ./terraform-enterprise-push.sh ./terraform-enterprise-push.sh ./content my-organization/my-workspace ``` **Note**: This script does not have error handling, so for a more robust script consider adding error checking. **`./terraform-enterprise-push.sh`:** ```bash #!/bin/bash # Complete script for API-driven runs. # 1. Define Variables if [ -z "$1" ] || [ -z "$2" ]; then echo "Usage: $0 <path_to_content_directory> <organization>/<workspace>" exit 0 fi CONTENT_DIRECTORY="$1" ORG_NAME="$(cut -d'/' -f1 <<<"$2")" WORKSPACE_NAME="$(cut -d'/' -f2 <<<"$2")" # 2. Create the File for Upload UPLOAD_FILE_NAME="./content-$(date +%s).tar.gz" tar -zcvf "$UPLOAD_FILE_NAME" -C "$CONTENT_DIRECTORY" . # 3. Look Up the Workspace ID WORKSPACE_ID=($(curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/organizations/$ORG_NAME/workspaces/$WORKSPACE_NAME \ | jq -r '.data.id')) # 4. Create a New Configuration Version echo '{"data":{"type":"configuration-versions"}}' > ./create_config_version.json UPLOAD_URL=($(curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @create_config_version.json \ https://app.terraform.io/api/v2/workspaces/$WORKSPACE_ID/configuration-versions \ | jq -r '.data.attributes."upload-url"')) # 5. Upload the Configuration Content File curl \ --header "Content-Type: application/octet-stream" \ --request PUT \ --data-binary @"$UPLOAD_FILE_NAME" \ $UPLOAD_URL # 6. Delete Temporary Files rm "$UPLOAD_FILE_NAME" rm ./create_config_version.json ``` ## Advanced Use Cases For advanced use cases refer to the [Terraform Enterprise Automation Script](https://github.com/hashicorp/terraform-guides/tree/master/operations/automation-script) repository for automating interactions with HCP Terraform, including the creation of a workspace, uploading code, setting variables, and triggering the `plan` and `apply` operations. In addition to uploading configurations and starting runs, you can use HCP Terraform's APIs to create and modify workspaces, edit variable values, and more. See the [API documentation](/terraform/cloud-docs/api-docs) for more details.
terraform
page title API driven Runs Runs HCP Terraform description External tools communicate with HCP Terraform to upload configurations and trigger runs The API driven Run Workflow 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 described below which is more flexible but requires you to create some tooling The CLI driven run workflow terraform cloud docs run cli which uses Terraform s standard CLI tools to execute runs in HCP Terraform Summary In the API driven workflow workspaces are not directly associated with a VCS repo and runs are not driven by webhooks on your VCS provider Instead one of your organization s other tools is in charge of deciding when configuration has changed and a run should occur Usually this is something like a CI system or something else capable of monitoring changes to your Terraform code and performing actions in response Once your other tooling has decided a run should occur it must make a series of calls to HCP Terraform s runs and configuration versions APIs to upload configuration files and perform a run with them For the exact series of API calls see the pushing a new configuration version pushing a new configuration version section The most significant difference in this workflow is that HCP Terraform does not fetch configuration files from version control Instead your own tooling must upload the configurations as a tar gz file This allows you to work with configurations from unsupported version control systems automatically generate Terraform configurations from some other source of data or build a variety of other integrations Important The script below is provided to illustrate the run process and is not intended for production use If you want to drive HCP Terraform runs from the command line please see the CLI driven run workflow terraform cloud docs run cli Pushing a New Configuration Version Pushing a new configuration to an existing workspace is a multi step process This section walks through each step in detail using an example bash script to illustrate You need queue plans permission to create new configuration versions for the workspace Refer to the permissions terraform cloud docs users teams organizations permissions general workspace permissions documentation for more details permissions citation intentionally unused keep for maintainers 1 Define Variables To perform an upload a few user parameters must be set path to content directory is the folder with the terraform configuration There must be at least one tf file in the root of this path organization is the organization name not ID for your HCP Terraform organization workspace is the workspace name not ID in the HCP Terraform organization TOKEN is the API Token used for authenticating with the HCP Terraform API terraform cloud docs api docs authentication This script extracts the path to content directory organization and workspace from command line arguments and expects the TOKEN as an environment variable bash bin bash if z 1 z 2 then echo Usage 0 path to content directory organization workspace exit 0 fi CONTENT DIRECTORY 1 ORG NAME cut d f1 2 WORKSPACE NAME cut d f2 2 2 Create the File for Upload The configuration version API terraform cloud docs api docs configuration versions requires a tar gz file to use the configuration version for a run so you must package the directory containing the Terraform configuration into a tar gz file Important The configuration directory must be the root of the tar file with no intermediate directories In other words when the tar file is extracted the result must be paths like main tf rather than terraform appserver main tf bash UPLOAD FILE NAME content date s tar gz tar zcvf UPLOAD FILE NAME C CONTENT DIRECTORY 3 Look Up the Workspace ID The first step identified the organization name and the workspace name however the configuration version API terraform cloud docs api docs configuration versions expects the workspace ID As such the ID has to be looked up If the workspace ID is already known this step can be skipped This step uses the jq tool https stedolan github io jq to parse the JSON output and extract the ID value into the WORKSPACE ID variable bash WORKSPACE ID curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 organizations ORG NAME workspaces WORKSPACE NAME jq r data id 4 Create a New Configuration Version Before uploading the configuration files you must create a configuration version to associate uploaded content with the workspace This API call performs two tasks it creates the new configuration version and it extracts the upload URL to be used in the next step bash echo data type configuration versions create config version json UPLOAD URL curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data create config version json https app terraform io api v2 workspaces WORKSPACE ID configuration versions jq r data attributes upload url 5 Upload the Configuration Content File Next upload the configuration version tar gz file to the upload URL extracted from the previous step If a file is not uploaded the configuration version will not be usable since it will have no Terraform configuration files HCP Terraform automatically creates a new run with a plan once the new file is uploaded If the workspace is configured to auto apply it will also apply if the plan succeeds otherwise an apply can be triggered via the Run Apply API terraform cloud docs api docs run apply If the API token used for the upload lacks permission to apply runs for the workspace the run can t be auto applied More about permissions terraform cloud docs users teams organizations permissions permissions citation intentionally unused keep for maintainers bash curl header Content Type application octet stream request PUT data binary UPLOAD FILE NAME UPLOAD URL 6 Delete Temporary Files In the previous steps a few files were created they are no longer needed so they should be deleted bash rm UPLOAD FILE NAME rm create config version json Complete Script Combine all of the code blocks into a single file terraform enterprise push sh and give execution permission to create a combined bash script to perform all of the operations shell chmod x terraform enterprise push sh terraform enterprise push sh content my organization my workspace Note This script does not have error handling so for a more robust script consider adding error checking terraform enterprise push sh bash bin bash Complete script for API driven runs 1 Define Variables if z 1 z 2 then echo Usage 0 path to content directory organization workspace exit 0 fi CONTENT DIRECTORY 1 ORG NAME cut d f1 2 WORKSPACE NAME cut d f2 2 2 Create the File for Upload UPLOAD FILE NAME content date s tar gz tar zcvf UPLOAD FILE NAME C CONTENT DIRECTORY 3 Look Up the Workspace ID WORKSPACE ID curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 organizations ORG NAME workspaces WORKSPACE NAME jq r data id 4 Create a New Configuration Version echo data type configuration versions create config version json UPLOAD URL curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data create config version json https app terraform io api v2 workspaces WORKSPACE ID configuration versions jq r data attributes upload url 5 Upload the Configuration Content File curl header Content Type application octet stream request PUT data binary UPLOAD FILE NAME UPLOAD URL 6 Delete Temporary Files rm UPLOAD FILE NAME rm create config version json Advanced Use Cases For advanced use cases refer to the Terraform Enterprise Automation Script https github com hashicorp terraform guides tree master operations automation script repository for automating interactions with HCP Terraform including the creation of a workspace uploading code setting variables and triggering the plan and apply operations In addition to uploading configurations and starting runs you can use HCP Terraform s APIs to create and modify workspaces edit variable values and more See the API documentation terraform cloud docs api docs for more details
terraform customize behavior during runs Learn the effect of the Destroy and Refresh Only modes as well as options to Run Modes and Options HCP Terraform runs support many of the same modes and options available in the Terraform CLI page title Run Modes and Options Runs HCP Terraform
--- page_title: Run Modes and Options - Runs - HCP Terraform description: >- Learn the effect of the Destroy and Refresh-Only modes as well as options to customize behavior during runs. --- # Run Modes and Options HCP Terraform runs support many of the same modes and options available in the Terraform CLI. ## Plan and Apply (Standard) The default run mode of HCP Terraform is to perform a plan and then apply it. If you have enabled auto-apply, a successful plan applies immediately. Otherwise, the run waits for user confirmation before applying. - **CLI:** Use `terraform apply` (without providing a saved plan file). - **API:** Create a run without specifying any options that select a different mode. - **UI:** From the workspace's overview page, click **+ New run**, and then choose **Plan and apply (standard)** as the run type. - **VCS:** When a workspace is connected to a VCS repository, HCP Terraform automatically starts a standard plan and apply when you add new commits to the selected branch of that repository. ## Destroy Mode [Destroy mode](/terraform/cli/commands/plan#planning-modes) instructs Terraform to create a plan which destroys all objects, regardless of configuration changes. - **CLI:** Use `terraform plan -destroy` or `terraform destroy` - **API:** Use the `is-destroy` option. - **UI:** Use a workspace's **Destruction and Deletion** settings page. ## Plan Only/Speculative Plan This option creates a [speculative plan](/terraform/cloud-docs/run/remote-operations#speculative-plans). The speculative plan shows a set of possible changes and checks them against Sentinel policies, but Terraform can _not_ apply this plan. You can create speculative plans with a different Terraform version than the one currently selected for a workspace. This lets you check whether your configuration is compatible with a newer Terraform version without changing the workspace settings. Plan-only runs ignore the per-workspace run queue. Plan-only runs can proceed even if another run is in progress, can not become the workspace's current run, and do not block progress on a workspace's other runs. - **API:** Set the `plan-only` option to `true` and specify an available terraform version using the `terraform-version` field. - **UI:** From the workspace's overview page, click **+ New run**, and then choose **Plan only** as the run type. - **VCS:** When a workspace is connected to a VCS repository, HCP Terraform automatically starts a speculative plan when someone opens a pull request (or merge request) against the selected branch of that repository. The pull/merge request view in your VCS links to the speculative plan, and you can also find it in the workspace's run list. ## Saved Plans -> **Version note:** Using saved plans from the CLI with HCP Terraform requires at least Terraform CLI v1.6.0. Saved plan runs are very similar to standard plan and apply runs: they perform a plan and then optionally apply it. There are three main differences: 1. _No wait for planning._ Saved plan runs ignore the per-workspace run queue during their plan and checks. Like plan-only runs, saved plans can begin planning even if another run is in progress, without blocking progress on other runs. 2. _No auto-apply._ Saved plan runs are never auto-applied, even if you enabled auto-apply for the workspace. Saved plans only apply if you confirm them. 3. _Automatic discard for stale plans._ If another run is applied (or the state is otherwise modified) before a saved plan run is confirmed, HCP Terraform automatically discards that saved plan. HCP Terraform may also automatically discard saved plans if they are not confirmed within a few weeks. Saved plans are ideal for interactive CLI workflows, where you can perform many exploratory plans and then choose one to apply, or for custom continuous integration workflows where the default run queue behavior isn't suitable. - **CLI:** Use `terraform plan -out <FILE>` to perform and save a plan, then use `terraform apply <FILE>` to apply the saved plan. Use `terraform show <FILE>` to inspect a saved plan before applying it. - **API:** Use the `save-plan` option when creating a run. If you create a new configuration version for a saved plan run, use the `provisional` option so that it will not become the workspace's current configuration version until you decide to apply the run. ## Allow Empty Apply A no-operation (empty) apply enables HCP Terraform to apply a run from a plan that contains no infrastructure changes. During apply, Terraform can upgrade the state version if required. You can use this option to upgrade the state in your HCP Terraform workspace to a new Terraform version. Only some Terraform versions require this, most notably 0.13. To make such upgrades easier, empty apply runs will always auto-apply if their plan contains no changes. ~> **Warning:** HCP Terraform cannot guarantee that a plan in this mode will produce no changes. We recommend checking the plan for drift before proceeding to the apply stage. - **API:** Set the `allow-empty-apply` field to `true`. - **UI:** From the workspace's overview page, click **+ New run**, and then choose **Allow empty apply** as the run type. ## Refresh-Only Mode > **Hands-on:** Try the [Use Refresh-Only Mode to Sync Terraform State](/terraform/tutorials/state/refresh) tutorial. -> **Version note:** Refresh-only support requires a workspace using at least Terraform CLI v0.15.4. [Refresh-only mode](/terraform/cli/commands/plan#planning-modes) instructs Terraform to create a plan that updates the Terraform state to match changes made to remote objects outside of Terraform. This is useful if state drift has occurred and you want to reconcile your state file to match the drifted remote objects. Applying a refresh-only run does not result in further changes to remote objects. - **CLI:** Use `terraform plan -refresh-only` or `terraform apply -refresh-only`. - **API:** Use the `refresh-only` option. - **UI:** From the workspace's overview page, click **+ New run**, and then choose **Refresh state** as the run type. ## Skipping Automatic State Refresh The [`-refresh=false` option](/terraform/cli/commands/plan#refresh-false) is used in normal planning mode to skip the default behavior of refreshing Terraform state before checking for configuration changes. - **CLI:** Use `terraform plan -refresh=false` or `terraform apply -refresh=false`. - **API:** Use the `refresh` option. ## Replacing Selected Resources -> **Version note:** Replace support requires a workspace using at least Terraform CLI v0.15.2. The [replace option](/terraform/cli/commands/plan#replace-address) instructs Terraform to replace the object with the given resource address. - **CLI:** Use `terraform plan -replace=ADDRESS` or `terraform apply -replace=ADDRESS`. - **API:** Use the `replace-addrs` option. - **UI:** Click **+ New run** and select the **Plan and apply (standard)** run type. Then click **Additional planning options** to reveal the **Replace resources** option. Type the address of the resource that you want to replace. You can replace multiple resources. ## Targeted Plan and Apply [Resource Targeting](/terraform/cli/commands/plan#resource-targeting) is intended for exceptional circumstances only and should not be used routinely. - **CLI:** Use `terraform plan -target=ADDRESS` or `terraform apply -target=ADDRESS`. - **API:** Use the `target-addrs` option. The usual caveats for targeting in local operations imply some additional limitations on HCP Terraform features for remote plans created with targeting: - [Sentinel](/terraform/cloud-docs/policy-enforcement) policy checks for targeted plans will see only the selected subset of resource instances planned for changes in [the `tfplan` import](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfplan) and [the `tfplan/v2` import](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfplan-v2), which may cause an unintended failure for any policy that requires a planned change to a particular resource instance selected by its address. - [Cost Estimation](/terraform/cloud-docs/cost-estimation) is disabled for any run created with `-target` set, to prevent producing a misleading underestimate of cost due to resource instances being excluded from the plan. You can disable or constrain use of targeting in a particular workspace using a Sentinel policy based on [the `tfrun.target_addrs` value](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfrun#value-target_addrs). ## Generating Configuration -> **Version note:** Support for `import` blocks and generating configuration requires a workspace using at least Terraform CLI v1.5.0. When using [`import` blocks](/terraform/language/import) to import existing resources, Terraform can [automatically generate configuration](/terraform/language/import/generating-configuration) during the plan for any imported resources that don't have an existing `resource` block. This option is enabled by default for runs started from the UI or from a VCS webhook. - **CLI:** Use `terraform plan -generate-config-out=generated.tf`. - **API:** Use the `allow-config-generation` option. You can find generated configuration displayed in the plan UI. If you're using the CLI workflow, Terraform will write generated configuration to the file you specify when running `terraform plan`. Once Terraform has generated configuration for you, you'll need to review it, incorporate it in your Terraform configuration (including committing it to version control), then run another plan. If you try to directly apply a plan with generated configuration, the run will error.
terraform
page title Run Modes and Options Runs HCP Terraform description Learn the effect of the Destroy and Refresh Only modes as well as options to customize behavior during runs Run Modes and Options HCP Terraform runs support many of the same modes and options available in the Terraform CLI Plan and Apply Standard The default run mode of HCP Terraform is to perform a plan and then apply it If you have enabled auto apply a successful plan applies immediately Otherwise the run waits for user confirmation before applying CLI Use terraform apply without providing a saved plan file API Create a run without specifying any options that select a different mode UI From the workspace s overview page click New run and then choose Plan and apply standard as the run type VCS When a workspace is connected to a VCS repository HCP Terraform automatically starts a standard plan and apply when you add new commits to the selected branch of that repository Destroy Mode Destroy mode terraform cli commands plan planning modes instructs Terraform to create a plan which destroys all objects regardless of configuration changes CLI Use terraform plan destroy or terraform destroy API Use the is destroy option UI Use a workspace s Destruction and Deletion settings page Plan Only Speculative Plan This option creates a speculative plan terraform cloud docs run remote operations speculative plans The speculative plan shows a set of possible changes and checks them against Sentinel policies but Terraform can not apply this plan You can create speculative plans with a different Terraform version than the one currently selected for a workspace This lets you check whether your configuration is compatible with a newer Terraform version without changing the workspace settings Plan only runs ignore the per workspace run queue Plan only runs can proceed even if another run is in progress can not become the workspace s current run and do not block progress on a workspace s other runs API Set the plan only option to true and specify an available terraform version using the terraform version field UI From the workspace s overview page click New run and then choose Plan only as the run type VCS When a workspace is connected to a VCS repository HCP Terraform automatically starts a speculative plan when someone opens a pull request or merge request against the selected branch of that repository The pull merge request view in your VCS links to the speculative plan and you can also find it in the workspace s run list Saved Plans Version note Using saved plans from the CLI with HCP Terraform requires at least Terraform CLI v1 6 0 Saved plan runs are very similar to standard plan and apply runs they perform a plan and then optionally apply it There are three main differences 1 No wait for planning Saved plan runs ignore the per workspace run queue during their plan and checks Like plan only runs saved plans can begin planning even if another run is in progress without blocking progress on other runs 2 No auto apply Saved plan runs are never auto applied even if you enabled auto apply for the workspace Saved plans only apply if you confirm them 3 Automatic discard for stale plans If another run is applied or the state is otherwise modified before a saved plan run is confirmed HCP Terraform automatically discards that saved plan HCP Terraform may also automatically discard saved plans if they are not confirmed within a few weeks Saved plans are ideal for interactive CLI workflows where you can perform many exploratory plans and then choose one to apply or for custom continuous integration workflows where the default run queue behavior isn t suitable CLI Use terraform plan out FILE to perform and save a plan then use terraform apply FILE to apply the saved plan Use terraform show FILE to inspect a saved plan before applying it API Use the save plan option when creating a run If you create a new configuration version for a saved plan run use the provisional option so that it will not become the workspace s current configuration version until you decide to apply the run Allow Empty Apply A no operation empty apply enables HCP Terraform to apply a run from a plan that contains no infrastructure changes During apply Terraform can upgrade the state version if required You can use this option to upgrade the state in your HCP Terraform workspace to a new Terraform version Only some Terraform versions require this most notably 0 13 To make such upgrades easier empty apply runs will always auto apply if their plan contains no changes Warning HCP Terraform cannot guarantee that a plan in this mode will produce no changes We recommend checking the plan for drift before proceeding to the apply stage API Set the allow empty apply field to true UI From the workspace s overview page click New run and then choose Allow empty apply as the run type Refresh Only Mode Hands on Try the Use Refresh Only Mode to Sync Terraform State terraform tutorials state refresh tutorial Version note Refresh only support requires a workspace using at least Terraform CLI v0 15 4 Refresh only mode terraform cli commands plan planning modes instructs Terraform to create a plan that updates the Terraform state to match changes made to remote objects outside of Terraform This is useful if state drift has occurred and you want to reconcile your state file to match the drifted remote objects Applying a refresh only run does not result in further changes to remote objects CLI Use terraform plan refresh only or terraform apply refresh only API Use the refresh only option UI From the workspace s overview page click New run and then choose Refresh state as the run type Skipping Automatic State Refresh The refresh false option terraform cli commands plan refresh false is used in normal planning mode to skip the default behavior of refreshing Terraform state before checking for configuration changes CLI Use terraform plan refresh false or terraform apply refresh false API Use the refresh option Replacing Selected Resources Version note Replace support requires a workspace using at least Terraform CLI v0 15 2 The replace option terraform cli commands plan replace address instructs Terraform to replace the object with the given resource address CLI Use terraform plan replace ADDRESS or terraform apply replace ADDRESS API Use the replace addrs option UI Click New run and select the Plan and apply standard run type Then click Additional planning options to reveal the Replace resources option Type the address of the resource that you want to replace You can replace multiple resources Targeted Plan and Apply Resource Targeting terraform cli commands plan resource targeting is intended for exceptional circumstances only and should not be used routinely CLI Use terraform plan target ADDRESS or terraform apply target ADDRESS API Use the target addrs option The usual caveats for targeting in local operations imply some additional limitations on HCP Terraform features for remote plans created with targeting Sentinel terraform cloud docs policy enforcement policy checks for targeted plans will see only the selected subset of resource instances planned for changes in the tfplan import terraform cloud docs policy enforcement sentinel import tfplan and the tfplan v2 import terraform cloud docs policy enforcement sentinel import tfplan v2 which may cause an unintended failure for any policy that requires a planned change to a particular resource instance selected by its address Cost Estimation terraform cloud docs cost estimation is disabled for any run created with target set to prevent producing a misleading underestimate of cost due to resource instances being excluded from the plan You can disable or constrain use of targeting in a particular workspace using a Sentinel policy based on the tfrun target addrs value terraform cloud docs policy enforcement sentinel import tfrun value target addrs Generating Configuration Version note Support for import blocks and generating configuration requires a workspace using at least Terraform CLI v1 5 0 When using import blocks terraform language import to import existing resources Terraform can automatically generate configuration terraform language import generating configuration during the plan for any imported resources that don t have an existing resource block This option is enabled by default for runs started from the UI or from a VCS webhook CLI Use terraform plan generate config out generated tf API Use the allow config generation option You can find generated configuration displayed in the plan UI If you re using the CLI workflow Terraform will write generated configuration to the file you specify when running terraform plan Once Terraform has generated configuration for you you ll need to review it incorporate it in your Terraform configuration including committing it to version control then run another plan If you try to directly apply a plan with generated configuration the run will error
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 Use the agents and agent pools endpoints List show and delete agents and list show create update and delete agent pools using the HTTP API page title Agent Pools and Agents API Docs HCP Terraform 201 https developer mozilla org en US docs Web HTTP Status 201
--- page_title: Agent Pools and Agents - API Docs - HCP Terraform description: >- Use the `/agents` and `/agent-pools` endpoints. List, show, and delete agents, and list, show, create, update, and delete agent pools using the HTTP API. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # Agent Pools and Agents API An Agent Pool represents a group of Agents, often related to one another by sharing a common network segment or purpose. A workspace may be configured to use one of the organization's agent pools to run remote operations with isolated, private, or on-premises infrastructure. <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/agents.mdx' <!-- END: TFC:only name:pnp-callout --> ## List Agent Pools `GET /organizations/:organization_name/agent-pools` | Parameter | Description | | -------------------- | ----------------------------- | | `:organization_name` | The name of the organization. | This endpoint allows you to list agent pools, their agents, and their tokens for an organization. | Status | Response | Reason | | ------- | --------------------------------------------- | ---------------------- | | [200][] | [JSON API document][] (`type: "agent-pools"`) | Success | | [404][] | [JSON API error object][] | Organization not found | ### Query Parameters This endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. | Parameter | Description | |------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `q` | **Optional.** A search query string. Agent pools are searchable by name. | | `sort` | **Optional.** Allows sorting the returned agents pools. Valid values are `"name"` and `"created-at"`. Prepending a hyphen to the sort parameter will reverse the order (e.g. `"-name"`). | | `page[number]` | **Optional.** If omitted, the endpoint will return the first page. | | `page[size]` | **Optional.** If omitted, the endpoint will return 20 agent pools per page. | | `filter[allowed_workspaces][name]` | **Optional.** Filters agent pools to those associated with the given workspace. The workspace must have permission to use the agent pool. Refer to [Scoping Agent Pools to Specific Workspaces](/terraform/cloud-docs/agents#scope-an-agent-pool-to-specific-workspaces). | | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/organizations/my-organization/agent-pools ``` ### Sample Response ```json { "data": [ { "id": "apool-yoGUFz5zcRMMz53i", "type": "agent-pools", "attributes": { "name": "example-pool", "created-at": "2020-08-05T18:10:26.964Z", "organization-scoped": false, "agent-count": 3 }, "relationships": { "agents": { "links": { "related": "/api/v2/agent-pools/apool-yoGUFz5zcRMMz53i/agents" } }, "authentication-tokens": { "links": { "related": "/api/v2/agent-pools/apool-yoGUFz5zcRMMz53i/authentication-tokens" } }, "workspaces": { "data": [ { "id": "ws-9EEkcEQSA3XgWyGe", "type": "workspaces" } ] }, "allowed-workspaces": { "data": [ { "id": "ws-x9taqV23mxrGcDrn", "type": "workspaces" } ] } }, "links": { "self": "/api/v2/agent-pools/apool-yoGUFz5zcRMMz53i" } } ], "links": { "self": "https://app.terraform.io/api/v2/organizations/my-organization/agent-pools?page%5Bnumber%5D=1&page%5Bsize%5D=20", "first": "https://app.terraform.io/api/v2/organizations/my-organization/agent-pools?page%5Bnumber%5D=1&page%5Bsize%5D=20", "prev": null, "next": null, "last": "https://app.terraform.io/api/v2/organizations/my-organization/agent-pools?page%5Bnumber%5D=1&page%5Bsize%5D=20" }, "meta": { "pagination": { "current-page": 1, "prev-page": null, "next-page": null, "total-pages": 1, "total-count": 1 }, "status-counts": { "total": 1, "matching": 1 } } } ``` ## List Agents `GET /agent-pools/:agent_pool_id/agents` | Parameter | Description | | ---------------- | --------------------------------- | | `:agent_pool_id` | The ID of the Agent Pool to list. | | Status | Response | Reason | | ------- | ---------------------------------------- | ------------------------------------------------------------ | | [200][] | [JSON API document][] (`type: "agents"`) | Success | | [404][] | [JSON API error object][] | Agent Pool not found, or user unauthorized to perform action | ### Query Parameters This endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. | Parameter | Description | | ------------------------- | ---------------------------------------------------------------------------- | | `filter[last-ping-since]` | **Optional.** Accepts a date in ISO8601 format (ex. `2020-08-11T10:41:23Z`). | | `page[number]` | **Optional.** If omitted, the endpoint will return the first page. | | `page[size]` | **Optional.** If omitted, the endpoint will return 20 agents per page. | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/agent-pools/apool-xkuMi7x4LsEnBUdY/agents ``` ### Sample Response ```json { "data": [ { "id": "agent-A726QeosTCpCumAs", "type": "agents", "attributes": { "name": "my-cool-agent", "status": "idle", "ip-address": "123.123.123.123", "last-ping-at": "2020-10-09T18:52:25.246Z" }, "links": { "self": "/api/v2/agents/agent-A726QeosTCpCumAs" } }, { "id": "agent-4cQzjbr1cnM6Pcxr", "type": "agents", "attributes": { "name": "my-other-cool-agent", "status": "exited", "ip-address": "123.123.123.123", "last-ping-at": "2020-08-12T15:25:09.726Z" }, "links": { "self": "/api/v2/agents/agent-4cQzjbr1cnM6Pcxr" } }, { "id": "agent-yEJjXQCucpNxtxd2", "type": "agents", "attributes": { "name": null, "status": "errored", "ip-address": "123.123.123.123", "last-ping-at": "2020-08-11T06:22:20.300Z" }, "links": { "self": "/api/v2/agents/agent-yEJjXQCucpNxtxd2" } } ], "links": { "self": "https://app.terraform.io/api/v2/agent-pools/apool-yoGUFz5zcRMMz53i/agents?page%5Bnumber%5D=1&page%5Bsize%5D=20", "first": "https://app.terraform.io/api/v2/agent-pools/apool-yoGUFz5zcRMMz53i/agents?page%5Bnumber%5D=1&page%5Bsize%5D=20", "prev": null, "next": null, "last": "https://app.terraform.io/api/v2/agent-pools/apool-yoGUFz5zcRMMz53i/agents?page%5Bnumber%5D=1&page%5Bsize%5D=20" }, "meta": { "pagination": { "current-page": 1, "prev-page": null, "next-page": null, "total-pages": 1, "total-count": 3 } } } ``` ## Show an Agent Pool `GET /agent-pools/:id` | Parameter | Description | | --------- | -------------------------------- | | `:id` | The ID of the Agent Pool to show | | Status | Response | Reason | | ------- | --------------------------------------------- | ------------------------------------------------------------ | | [200][] | [JSON API document][] (`type: "agent-pools"`) | Success | | [404][] | [JSON API error object][] | Agent Pool not found, or user unauthorized to perform action | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/agent-pools/apool-MCf6kkxu5FyHbqhd ``` ### Sample Response ```json { "data": { "id": "apool-yoGUFz5zcRMMz53i", "type": "agent-pools", "attributes": { "name": "example-pool", "created-at": "2020-08-05T18:10:26.964Z", "organization-scoped": false }, "relationships": { "agents": { "links": { "related": "/api/v2/agent-pools/apool-yoGUFz5zcRMMz53i/agents" } }, "authentication-tokens": { "links": { "related": "/api/v2/agent-pools/apool-yoGUFz5zcRMMz53i/authentication-tokens" } }, "workspaces": { "data": [ { "id": "ws-9EEkcEQSA3XgWyGe", "type": "workspaces" } ] }, "allowed-workspaces": { "data": [ { "id": "ws-x9taqV23mxrGcDrn", "type": "workspaces" } ] } }, "links": { "self": "/api/v2/agent-pools/apool-yoGUFz5zcRMMz53i" } } } ``` ## Show an Agent `GET /agents/:id` | Parameter | Description | | --------- | --------------------------- | | `:id` | The ID of the agent to show | | Status | Response | Reason | | ------- | ---------------------------------------- | ------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "agents"`) | Success | | [404][] | [JSON API error object][] | Agent not found, or user unauthorized to perform action | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/agents/agent-73PJNzbZB5idR7AQ ``` ### Sample Response ```json { "data": { "id": "agent-Zz9PTEcUgBtYzht8", "type": "agents", "attributes": { "name": "my-agent", "status": "busy", "ip-address": "123.123.123.123", "last-ping-at": "2020-09-08T18:47:35.361Z" }, "links": { "self": "/api/v2/agents/agent-Zz9PTEcUgBtYzht8" } } } ``` This endpoint lists details about an agent along with that agent's status. [Learn more about agents statuses](/terraform/cloud-docs/agents/agent-pools#view-agent-statuses). ## Delete an Agent `DELETE /agents/:id` | Parameter | Description | | --------- | ----------------------------- | | `:id` | The ID of the agent to delete | | Status | Response | Reason | | ------- | ------------------------- | ------------------------------------------------------------------------------------------------------------ | | [204][] | No Content | Success | | [412][] | [JSON API error object][] | Agent is not deletable. Agents must have a status of `unknown`, `errored`, or `exited` before being deleted. | | [404][] | [JSON API error object][] | Agent not found, or user unauthorized to perform action | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --request DELETE \ https://app.terraform.io/api/v2/agents/agent-73PJNzbZB5idR7AQ ``` ## Create an Agent Pool `POST /organizations/:organization_name/agent-pools` | Parameter | Description | | -------------------- | ----------------------------- | | `:organization_name` | The name of the organization. | This endpoint allows you to create an Agent Pool for an organization. Only one Agent Pool may exist for an organization. | Status | Response | Reason | | ------- | --------------------------------------------- | -------------------------------------------------------------- | | [201][] | [JSON API document][] (`type: "agent-pools"`) | Agent Pool successfully created | | [404][] | [JSON API error object][] | Organization not found or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (missing attributes, wrong types, etc.) | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | |---------------------------------------------------|--------|---------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `data.type` | string | | Must be `"agent-pools"`. | | `data.attributes.name` | string | | The name of the agent pool, which can only include letters, numbers, `-`, and `_`. This will be used as an identifier and must be unique in the organization. | | `data.attributes.organization-scoped` | bool | true | The scope of the agent pool. If true, all workspaces in the organization can use the agent pool. | | `data.relationships.allowed-workspaces.data.type` | string | | Must be `"workspaces"`. | | `data.relationships.allowed-workspaces.data.id` | string | | The ID of the workspace that has permission to use the agent pool. Refer to [Scoping Agent Pools to Specific Workspaces](/terraform/cloud-docs/agents#scope-an-agent-pool-to-specific-workspaces). | ### Sample Payload ```json { "data": { "type": "agent-pools", "attributes": { "name": "my-pool", "organization-scoped": false, }, "relationships": { "allowed-workspaces": { "data": [ { "id": "ws-x9taqV23mxrGcDrn", "type": "workspaces" } ] } } } } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/organizations/my-organization/agent-pools ``` ### Sample Response ```json { "data": { "id": "apool-55jZekR57npjHHYQ", "type": "agent-pools", "attributes": { "name": "my-pool", "created-at": "2020-10-13T16:32:45.165Z", "organization-scoped": false, }, "relationships": { "agents": { "links": { "related": "/api/v2/agent-pools/apool-55jZekR57npjHHYQ/agents" } }, "authentication-tokens": { "links": { "related": "/api/v2/agent-pools/apool-55jZekR57npjHHYQ/authentication-tokens" } }, "workspaces": { "data": [] }, "allowed-workspaces": { "data": [ { "id": "ws-x9taqV23mxrGcDrn", "type": "workspaces" } ] } }, "links": { "self": "/api/v2/agent-pools/apool-55jZekR57npjHHYQ" } } } ``` ## Update an Agent Pool `PATCH /agent-pools/:id` | Parameter | Description | | --------- | ---------------------------------- | | `:id` | The ID of the Agent Pool to update | | Status | Response | Reason | | ------- | --------------------------------------------- | -------------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "agent-pools"`) | Success | | [404][] | [JSON API error object][] | Agent Pool not found, or user unauthorized to perform action | | [422][] | JSON error document | Malformed request body (missing attributes, wrong types, etc.) | ### Request Body This PATCH endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | |---------------------------------------------------|--------|------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `data.type` | string | | Must be `"agent-pools"`. | | `data.attributes.name` | string | (previous value) | The name of the agent pool, which can only include letters, numbers, `-`, and `_`. This will be used as an identifier and must be unique in the organization. | | `data.attributes.organization-scoped` | bool | true | The scope of the agent pool. If true, all workspaces in the organization can use the agent pool. | | `data.relationships.allowed-workspaces.data.type` | string | | Must be `"workspaces"`. | | `data.relationships.allowed-workspaces.data.id` | string | | The ID of the workspace that has permission to use the agent pool. Refer to [Scoping Agent Pools to Specific Workspaces](/terraform/cloud-docs/agents#scope-an-agent-pool-to-specific-workspaces). | ### Sample Payload ```json { "data": { "type": "agent-pools", "attributes": { "name": "example-pool", "organization-scoped": false, }, "relationships": { "allowed-workspaces": { "data": [ { "id": "ws-x9taqV23mxrGcDrn", "type": "workspaces" } ] } } } } ``` ### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request PATCH \ --data @payload.json \ https://app.terraform.io/api/v2/agent-pools/apool-MCf6kkxu5FyHbqhd ``` ### Sample Response ```json { "data": { "id": "apool-yoGUFz5zcRMMz53i", "type": "agent-pools", "attributes": { "name": "example-pool", "created-at": "2020-08-05T18:10:26.964Z" }, "relationships": { "agents": { "links": { "related": "/api/v2/agent-pools/apool-yoGUFz5zcRMMz53i/agents" } }, "authentication-tokens": { "links": { "related": "/api/v2/agent-pools/apool-yoGUFz5zcRMMz53i/authentication-tokens" } }, "workspaces": { "data": [ { "id": "ws-9EEkcEQSA3XgWyGe", "type": "workspaces" } ] }, "allowed-workspaces": { "data": [ { "id": "ws-x9taqV23mxrGcDrn", "type": "workspaces" } ] } }, "links": { "self": "/api/v2/agent-pools/apool-yoGUFz5zcRMMz53i" } } } ``` ## Delete an Agent Pool `DELETE /agent-pools/:agent_pool_id` | Parameter | Description | | ---------------- | ------------------------------------- | | `:agent_pool_id` | The ID of the agent pool ID to delete | ### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request DELETE \ https://app.terraform.io/api/v2/agent-pools/apool-MCf6kkxu5FyHbqhd ``` ### Available Related Resources The GET endpoints above can optionally return related resources, if requested with [the `include` query parameter](/terraform/cloud-docs/api-docs#inclusion-of-related-resources). The following resource types are available: | Resource Name | Description | | -------------- | ------------------------------------------- | | `workspaces` | The workspaces attached to this agent pool. |
terraform
page title Agent Pools and Agents API Docs HCP Terraform description Use the agents and agent pools endpoints List show and delete agents and list show create update and delete agent pools using the HTTP API 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects Agent Pools and Agents API An Agent Pool represents a group of Agents often related to one another by sharing a common network segment or purpose A workspace may be configured to use one of the organization s agent pools to run remote operations with isolated private or on premises infrastructure BEGIN TFC only name pnp callout include tfc package callouts agents mdx END TFC only name pnp callout List Agent Pools GET organizations organization name agent pools Parameter Description organization name The name of the organization This endpoint allows you to list agent pools their agents and their tokens for an organization Status Response Reason 200 JSON API document type agent pools Success 404 JSON API error object Organization not found Query Parameters This endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters Remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs Parameter Description q Optional A search query string Agent pools are searchable by name sort Optional Allows sorting the returned agents pools Valid values are name and created at Prepending a hyphen to the sort parameter will reverse the order e g name page number Optional If omitted the endpoint will return the first page page size Optional If omitted the endpoint will return 20 agent pools per page filter allowed workspaces name Optional Filters agent pools to those associated with the given workspace The workspace must have permission to use the agent pool Refer to Scoping Agent Pools to Specific Workspaces terraform cloud docs agents scope an agent pool to specific workspaces Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 organizations my organization agent pools Sample Response json data id apool yoGUFz5zcRMMz53i type agent pools attributes name example pool created at 2020 08 05T18 10 26 964Z organization scoped false agent count 3 relationships agents links related api v2 agent pools apool yoGUFz5zcRMMz53i agents authentication tokens links related api v2 agent pools apool yoGUFz5zcRMMz53i authentication tokens workspaces data id ws 9EEkcEQSA3XgWyGe type workspaces allowed workspaces data id ws x9taqV23mxrGcDrn type workspaces links self api v2 agent pools apool yoGUFz5zcRMMz53i links self https app terraform io api v2 organizations my organization agent pools page 5Bnumber 5D 1 page 5Bsize 5D 20 first https app terraform io api v2 organizations my organization agent pools page 5Bnumber 5D 1 page 5Bsize 5D 20 prev null next null last https app terraform io api v2 organizations my organization agent pools page 5Bnumber 5D 1 page 5Bsize 5D 20 meta pagination current page 1 prev page null next page null total pages 1 total count 1 status counts total 1 matching 1 List Agents GET agent pools agent pool id agents Parameter Description agent pool id The ID of the Agent Pool to list Status Response Reason 200 JSON API document type agents Success 404 JSON API error object Agent Pool not found or user unauthorized to perform action Query Parameters This endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters Remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs Parameter Description filter last ping since Optional Accepts a date in ISO8601 format ex 2020 08 11T10 41 23Z page number Optional If omitted the endpoint will return the first page page size Optional If omitted the endpoint will return 20 agents per page Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 agent pools apool xkuMi7x4LsEnBUdY agents Sample Response json data id agent A726QeosTCpCumAs type agents attributes name my cool agent status idle ip address 123 123 123 123 last ping at 2020 10 09T18 52 25 246Z links self api v2 agents agent A726QeosTCpCumAs id agent 4cQzjbr1cnM6Pcxr type agents attributes name my other cool agent status exited ip address 123 123 123 123 last ping at 2020 08 12T15 25 09 726Z links self api v2 agents agent 4cQzjbr1cnM6Pcxr id agent yEJjXQCucpNxtxd2 type agents attributes name null status errored ip address 123 123 123 123 last ping at 2020 08 11T06 22 20 300Z links self api v2 agents agent yEJjXQCucpNxtxd2 links self https app terraform io api v2 agent pools apool yoGUFz5zcRMMz53i agents page 5Bnumber 5D 1 page 5Bsize 5D 20 first https app terraform io api v2 agent pools apool yoGUFz5zcRMMz53i agents page 5Bnumber 5D 1 page 5Bsize 5D 20 prev null next null last https app terraform io api v2 agent pools apool yoGUFz5zcRMMz53i agents page 5Bnumber 5D 1 page 5Bsize 5D 20 meta pagination current page 1 prev page null next page null total pages 1 total count 3 Show an Agent Pool GET agent pools id Parameter Description id The ID of the Agent Pool to show Status Response Reason 200 JSON API document type agent pools Success 404 JSON API error object Agent Pool not found or user unauthorized to perform action Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 agent pools apool MCf6kkxu5FyHbqhd Sample Response json data id apool yoGUFz5zcRMMz53i type agent pools attributes name example pool created at 2020 08 05T18 10 26 964Z organization scoped false relationships agents links related api v2 agent pools apool yoGUFz5zcRMMz53i agents authentication tokens links related api v2 agent pools apool yoGUFz5zcRMMz53i authentication tokens workspaces data id ws 9EEkcEQSA3XgWyGe type workspaces allowed workspaces data id ws x9taqV23mxrGcDrn type workspaces links self api v2 agent pools apool yoGUFz5zcRMMz53i Show an Agent GET agents id Parameter Description id The ID of the agent to show Status Response Reason 200 JSON API document type agents Success 404 JSON API error object Agent not found or user unauthorized to perform action Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 agents agent 73PJNzbZB5idR7AQ Sample Response json data id agent Zz9PTEcUgBtYzht8 type agents attributes name my agent status busy ip address 123 123 123 123 last ping at 2020 09 08T18 47 35 361Z links self api v2 agents agent Zz9PTEcUgBtYzht8 This endpoint lists details about an agent along with that agent s status Learn more about agents statuses terraform cloud docs agents agent pools view agent statuses Delete an Agent DELETE agents id Parameter Description id The ID of the agent to delete Status Response Reason 204 No Content Success 412 JSON API error object Agent is not deletable Agents must have a status of unknown errored or exited before being deleted 404 JSON API error object Agent not found or user unauthorized to perform action Sample Request shell curl header Authorization Bearer TOKEN request DELETE https app terraform io api v2 agents agent 73PJNzbZB5idR7AQ Create an Agent Pool POST organizations organization name agent pools Parameter Description organization name The name of the organization This endpoint allows you to create an Agent Pool for an organization Only one Agent Pool may exist for an organization Status Response Reason 201 JSON API document type agent pools Agent Pool successfully created 404 JSON API error object Organization not found or user unauthorized to perform action 422 JSON API error object Malformed request body missing attributes wrong types etc Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string Must be agent pools data attributes name string The name of the agent pool which can only include letters numbers and This will be used as an identifier and must be unique in the organization data attributes organization scoped bool true The scope of the agent pool If true all workspaces in the organization can use the agent pool data relationships allowed workspaces data type string Must be workspaces data relationships allowed workspaces data id string The ID of the workspace that has permission to use the agent pool Refer to Scoping Agent Pools to Specific Workspaces terraform cloud docs agents scope an agent pool to specific workspaces Sample Payload json data type agent pools attributes name my pool organization scoped false relationships allowed workspaces data id ws x9taqV23mxrGcDrn type workspaces Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 organizations my organization agent pools Sample Response json data id apool 55jZekR57npjHHYQ type agent pools attributes name my pool created at 2020 10 13T16 32 45 165Z organization scoped false relationships agents links related api v2 agent pools apool 55jZekR57npjHHYQ agents authentication tokens links related api v2 agent pools apool 55jZekR57npjHHYQ authentication tokens workspaces data allowed workspaces data id ws x9taqV23mxrGcDrn type workspaces links self api v2 agent pools apool 55jZekR57npjHHYQ Update an Agent Pool PATCH agent pools id Parameter Description id The ID of the Agent Pool to update Status Response Reason 200 JSON API document type agent pools Success 404 JSON API error object Agent Pool not found or user unauthorized to perform action 422 JSON error document Malformed request body missing attributes wrong types etc Request Body This PATCH endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string Must be agent pools data attributes name string previous value The name of the agent pool which can only include letters numbers and This will be used as an identifier and must be unique in the organization data attributes organization scoped bool true The scope of the agent pool If true all workspaces in the organization can use the agent pool data relationships allowed workspaces data type string Must be workspaces data relationships allowed workspaces data id string The ID of the workspace that has permission to use the agent pool Refer to Scoping Agent Pools to Specific Workspaces terraform cloud docs agents scope an agent pool to specific workspaces Sample Payload json data type agent pools attributes name example pool organization scoped false relationships allowed workspaces data id ws x9taqV23mxrGcDrn type workspaces Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request PATCH data payload json https app terraform io api v2 agent pools apool MCf6kkxu5FyHbqhd Sample Response json data id apool yoGUFz5zcRMMz53i type agent pools attributes name example pool created at 2020 08 05T18 10 26 964Z relationships agents links related api v2 agent pools apool yoGUFz5zcRMMz53i agents authentication tokens links related api v2 agent pools apool yoGUFz5zcRMMz53i authentication tokens workspaces data id ws 9EEkcEQSA3XgWyGe type workspaces allowed workspaces data id ws x9taqV23mxrGcDrn type workspaces links self api v2 agent pools apool yoGUFz5zcRMMz53i Delete an Agent Pool DELETE agent pools agent pool id Parameter Description agent pool id The ID of the agent pool ID to delete Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request DELETE https app terraform io api v2 agent pools apool MCf6kkxu5FyHbqhd Available Related Resources The GET endpoints above can optionally return related resources if requested with the include query parameter terraform cloud docs api docs inclusion of related resources The following resource types are available Resource Name Description workspaces The workspaces attached to this agent pool
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 Use these endpoints to control availability of no code provisioning and designate variable values for a no code module in your organization page title No Code Provisioning API Docs HCP Terraform
--- page_title: No-Code Provisioning - API Docs - HCP Terraform description: >- Use these endpoints to control availability of no-code provisioning and designate variable values for a no-code module in your organization. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: http://jsonapi.org/format/#error-objects # No-code provisioning API The no-code provisioning API allows you to create, configure, and deploy Terraform modules in the no-code provisioning workflows within HCP Terraform. For more information on no-code modules, refer to [Designing No-Code Ready Modules](/terraform/cloud-docs/no-code-provisioning/module-design). ## Enable no-code provisioning for a module `POST /organizations/:organization_name/no-code-modules` | Parameter | Description | | -------------------- | ---------------------------------------------------- | | `:organization_name` | The name of the organization the module belongs to. | To deploy a module using the no-code provisioning workflow, the module must meet the following requirement: 1. The module must exist in your organization's private registry. 1. The module must meet the [design requirements](/terraform/cloud-docs/no-code-provisioning/module-design#requirements) for a no-code module. 1. You must enable no-code provisioning for the module. You can send a `POST` request to the `/no-code-modules` endpoint to enable no-code provisioning for a specific module. You can also call this endpoint to set options for the allowed values of a variable for a no-code module in your organization. -> **Note**: This endpoint can not be accessed with [organization tokens](/terraform/cloud-docs/users-teams-organizations/api-tokens#organization-api-tokens). You must access it with a [user token](/terraform/cloud-docs/users-teams-organizations/users#api-tokens) or [team token](/terraform/cloud-docs/users-teams-organizations/api-tokens#team-api-tokens). | Status | Response | Reason | | ------- | ------------------------------------------------- | --------------------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "no-code-modules"`) | Successfully enabled a module for no-code provisioning. | | [404][] | [JSON API error object][] | Not found, or the user is unauthorized to perform this action. | | [422][] | [JSON API error object][] | Malformed request body (e.g., missing attributes, wrong types, etc.). | | [500][] | [JSON API error object][] | Internal system failure. | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | --- | --- | --- | --- | | `data.type` | string | | Must be `"no-code-modules"`. | | `data.attributes.version-pin` | string | Latest version of the module | The module version to use in no-code provisioning workflows. | | `data.attributes.enabled` | boolean | `false` | Set to `true` to enable no-code provisioning workflows. | | `data.relationships.registry-module.data.id` | string | | The ID of a module in the organization's private registry. | | `data.relationships.registry-module.data.type` | string | | Must be `"registry-module"`. | | `data.relationships.variable-options.data[].type` | string | | Must be `"variable-options"`. | | `data.relationships.variable-options.data[].attributes.variable-name` | string | | The name of a variable within the module. | | `data.relationships.variable-options.data[].attributes.variable-type` | string | | The data type for the variable. Can be [any type supported by Terraform](/terraform/language/expressions/types#types). | | `data.relationships.variable-options.data[].attributes.options` | Any[] | | A list of allowed values for the variable. | ### Sample Payload ```json { "data": { "type": "no-code-modules", "attributes": { "version-pin": "1.0.1", "enabled": true }, "relationships": { "registry-module": { "data": { "id": "mod-2aaFrmRPZs2N9epr", "type": "registry-module" } }, "variable-options": { "data": [ { "type": "variable-options", "attributes": { "variable-name": "amis", "variable-type": "string", "options": [ "ami-1", "ami-2", "ami-3" ] } }, { "type": "variable-options", "attributes": { "variable-name": "region", "variable-type": "string", "options": [ "eu-north-1", "us-east-2", "us-west-1" ] } } ] } } } } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/organizations/my-organization/no-code-modules ``` ### Sample Response ```json { "data": { "id": "nocode-9HE91XDNY3faePn2", "type": "no-code-modules", "attributes": { "enabled": true, "version-pin": "1.0.1" }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" }, "links": { "related": "/api/v2/organizations/my-organization" } }, "registry-module": { "data": { "id": "mod-2aaFrmRPZs2N9epr", "type": "registry-modules" }, "links": { "related": "/api/v2/registry-modules/mod-2aaFrmRPZs2N9epr" } }, "variable-options": { "data": [ { "id": "ncvaropt-fcHDfnZ1EGdRzFNC", "type": "variable-options" }, { "id": "ncvaropt-dZMfdh9KBcwFjyv2", "type": "variable-options" } ] } }, "links": { "self": "/api/v2/no-code-modules/nocode-9HE91XDNY3faePn2" } } } ``` ## Update no-code provisioning settings `PATCH /no-code-modules/:id` | Parameter | Description | | --------- | -------------------------------------------- | | `:id` | The unique identifier of the no-code module. | Send a `PATCH` request to the `/no-code-modules/:id` endpoint to update the settings for the no-code provisioning of a module. You can update the following settings: - Enable or disable no-code provisioning. - Adjust the set of options for allowed variable values. - Change the module version being provisioned. - Change the module being provisioned. The [API call that enables no-code provisioning for a module](#allow-no-code-provisioning-of-a-module-within-an-organization) returns that module's unique identifier. -> **Note:** This endpoint cannot be accessed with [organization tokens](/terraform/cloud-docs/users-teams-organizations/api-tokens#organization-api-tokens). You must access it with a [user token](/terraform/cloud-docs/users-teams-organizations/users#api-tokens) or [team token](/terraform/cloud-docs/users-teams-organizations/api-tokens#team-api-tokens). | Status | Response | Reason | | ------- | ------------------------------------------------- | --------------------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "no-code-modules"`) | Successfully updated a no-code module. | | [404][] | [JSON API error object][] | Not found, or the user is unauthorized to perform this action. | | [422][] | [JSON API error object][] | Malformed request body (e.g., missing attributes, wrong types, etc.). | | [500][] | [JSON API error object][] | Internal system failure. | ### Request Body This PATCH endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | --- | --- | --- | --- | | `data.type` | string | | Must be `"no-code-modules"`. | | `data.attributes.version-pin` | string | Existing value | The module version to use in no-code provisioning workflows. | | `data.attributes.enabled` | boolean | Existing value | Set to `true` to enable no-code provisioning workflows, or `false` to disable them. | | `data.relationships.registry-module.data.id` | string | Existing value | The ID of a module in the organization's Private Registry. | | `data.relationships.registry-module.data.type` | string | Existing value | Must be `"registry-module"`. | | `data.relationships.variable-options.data[].id` | string | | The ID of an existing variable-options set. If provided, a new variable-options set replaces the set with this ID. If not provided, this creates a new variable-option set. | | `data.relationships.variable-options.data[].type` | string | | Must be `"variable-options"`. | | `data.relationships.variable-options.data[].attributes.variable-name` | string | | The name of a variable within the module. | | `data.relationships.variable-options.data[].attributes.variable-type` | string | | The data type for the variable. Can be [any type supported by Terraform](/terraform/language/expressions/types#types). | | `data.relationships.variable-options.data[].attributes.options` | Any[] | | A list of allowed values for the variable. | ### Sample Payload ```json { "data": { "type": "no-code-modules", "attributes": { "enabled": false }, "relationships": { "registry-module": { "data": { "id": "mod-zyai9dwH4VPPaVuC", "type": "registry-module" } }, "variable-options": { "data": [ { "id": "ncvaropt-fcHDfnZ1EGdRzFNC", "type": "variable-options", "attributes": { "variable-name": "Linux AMIs", "variable-type": "array", "options": [ "Xenial Xerus", "Trusty Tahr" ] } }, { "id": "ncvaropt-dZMfdh9KBcwFjyv2", "type": "variable-options", "attributes": { "variable-name": "region", "variable-type": "array", "options": [ "eu-north-1", "us-east-2", "us-west-1" ] } } ] } } } } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request PATCH \ --data @payload.json \ https://app.terraform.io/api/v2/no-code-modules/nocode-9HE91XDNY3faePn2 ``` ### Sample Response ```json { "data": { "id": "nocode-9HE91XDNY3faePn2", "type": "no-code-modules", "attributes": { "enabled": true, "version-pin": "1.0.1" }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" }, "links": { "related": "/api/v2/organizations/my-organization" } }, "registry-module": { "data": { "id": "mod-2aaFrmRPZs2N9epr", "type": "registry-modules" }, "links": { "related": "/api/v2/registry-modules/mod-2aaFrmRPZs2N9epr" } }, "variable-options": { "data": [ { "id": "ncvaropt-fcHDfnZ1EGdRzFNC", "type": "variable-options" }, { "id": "ncvaropt-dZMfdh9KBcwFjyv2", "type": "variable-options" } ] } }, "links": { "self": "/api/v2/no-code-modules/nocode-9HE91XDNY3faePn2" } } } ``` ## Read a no-code module's properties `GET /no-code-modules/:id` | Parameter | Description | | --------- | -------------------------------------------- | | `:id` | The unique identifier of the no-code module. | Use this API to read the details of an existing no-code module. The [API call that enables no-code provisioning for a module](#allow-no-code-provisioning-of-a-module-within-an-organization) returns that module's unique identifier. | Status | Response | Reason | | ------- | ------------------------------------------------- | --------------------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "no-code-modules"`) | Successfully read the no-code module. | | [400][] | [JSON API error object][] | Invalid `include` parameter. | | [404][] | [JSON API error object][] | Not found, or the user is unauthorized to perform this action. | | [422][] | [JSON API error object][] | Malformed request body (e.g., missing attributes, wrong types, etc.). | | [500][] | [JSON API error object][] | Internal system failure. | ### Query Parameters This endpoint uses our [standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). Use HTML URL encoding syntax, such as `%5B` to represent `[` and `%5D` to represent `]`, if your tooling does not automatically encode URLs. Terraform returns related resources when you add the [`include` query parameter](/terraform/cloud-docs/api-docs#inclusion-of-related-resources) to the request. | Parameter | Description | | --------- | ------------------------------------------------- | | `include` | List related resource to include in the response. | The following resource types are available: | Resource Name | Description | | ------------------ | --------------------------------------------------------- | | `variable_options` | Module variables with a configured set of allowed values. | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/no-code-modules/nocode-9HE91XDNY3faePn2?include=variable_options ``` ### Sample Response ```json { "data": { "id": "nocode-9HE91XDNY3faePn2", "type": "no-code-modules", "attributes": { "enabled": true, "version-pin": "1.0.1" }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" }, "links": { "related": "/api/v2/organizations/my-organization" } }, "registry-module": { "data": { "id": "mod-2aaFrmRPZs2N9epr", "type": "registry-modules" }, "links": { "related": "/api/v2/registry-modules/mod-2aaFrmRPZs2N9epr" } }, "variable-options": { "data": [ { "id": "ncvaropt-fcHDfnZ1EGdRzFNC", "type": "variable-options" }, { "id": "ncvaropt-dZMfdh9KBcwFjyv2", "type": "variable-options" } ] } }, "links": { "self": "/api/v2/no-code-modules/nocode-9HE91XDNY3faePn2" } }, "included": [ { "id": "ncvaropt-fcHDfnZ1EGdRzFNC", "type": "variable-options", "attributes": { "variable-name": "Linux AMIs", "variable-type": "array", "options": [ "Xenial Xerus", "Trusty Tahr" ] }, "relationships": { "no-code-allowed-module": { "data": { "id": "nocode-9HE91XDNY3faePn2", "type": "no-code-allowed-modules" } } } }, { "id": "ncvaropt-dZMfdh9KBcwFjyv2", "type": "variable-options", "attributes": { "variable-name": "region", "variable-type": "array", "options": [ "eu-north-1", "us-east-2", "us-west-1" ] }, "relationships": { "no-code-allowed-module": { "data": { "id": "nocode-9HE91XDNY3faePn2", "type": "no-code-allowed-modules" } } } } ] } ``` ## Create a no-code module workspace This endpoint creates a workspace from a no-code module. `POST /no-code-modules/:id/workspaces` | Parameter | Description | | -------------------- | ------------------------------------------ | | `:id` | The ID of the no-code module to provision. | Each HCP Terraform organization has a list of which modules you can use to create workspaces using no-code provisioning. You can use this API to create a workspace by selecting a no-code module to enable a no-code provisioning workflow. -> **Note**: This endpoint can not be accessed with [organization tokens](/terraform/cloud-docs/users-teams-organizations/api-tokens#organization-api-tokens). You must access it with a [user token](/terraform/cloud-docs/users-teams-organizations/users#api-tokens) or [team token](/terraform/cloud-docs/users-teams-organizations/api-tokens#team-api-tokens). | Status | Response | Reason | | ------- | -------------------------------------------- | -------------------------------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "workspaces"`) | Successfully created a workspace from a no-code module for no-code provisioning. | | [404][] | [JSON API error object][] | Not found, or the user is unauthorized to perform this action. | | [422][] | [JSON API error object][] | Malformed request body (e.g., missing attributes, wrong types, etc.). | | [500][] | [JSON API error object][] | Internal system failure. | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | --- | --- | --- | --- | | `data.type` | string | none | Must be `"workspaces"`. | | `data.attributes.agent-pool-id` | string | none | Required when `execution-mode` is set to `agent`. The ID of the agent pool belonging to the workspace's organization. This value must not be specified if `execution-mode` is set to `remote`. | | | `data.attributes.auto_apply` | boolean | `false` | If `true`, Terraform automatically applies changes when a Terraform `plan` is successful. | | `data.attributes.description` | string | `""` | A description for the workspace. | | `data.attributes.execution-mode` | string | none | Which [execution mode](/terraform/cloud-docs/workspaces/settings#execution-mode) to use. Valid values are `remote`, and `agent`. When not provided, defaults to `remote`. | | | `data.attributes.name` | string | none | The name of the workspace. You can only include letters, numbers, `-`, and `_`. Terraform uses this value to identify the workspace and must be unique in the organization. | | `data.attributes.source-name` | string | none | A friendly name for the application or client creating this workspace. If set, this will be displayed on the workspace as "Created via `<SOURCE NAME>`". | | | `data.attributes.source-url` | string | (nothing) | A URL for the application or client creating this workspace. This can be the URL of a related resource in another app, or a link to documentation or other info about the client. | | | `data.relationships.project.data.id` | string | | The ID of the project to create the workspace in. You must have permission to create workspaces in the project, either by organization-level permissions or team admin access to a specific project. | | `data.relationships.project.data.type` | string | | Must be `"project"`. | | `data.relationships.vars.data[].type` | string | | Must be `"vars"`. | | `data.relationships.vars.data[].attributes.key` | string | | The name of the variable. | | `data.relationships.vars.data[].attributes.value` | string | `""` | The value of the variable. | | `data.relationships.vars.data[].attributes.description` | string | | The description of the variable. | | `data.relationships.vars.data[].attributes.category` | string | | Whether this is a Terraform or environment variable. Valid values are `"terraform"` or `"env"`. | | `data.relationships.vars.data[].attributes.hcl` | boolean | `false` | Whether to evaluate the value of the variable as a string of HCL code. Has no effect for environment variables. | | `data.relationships.vars.data[].attributes.sensitive` | boolean | `false` | Whether the value is sensitive. If `true` then the variable is written once and not visible thereafter. | ### Sample Payload ```json { "data": { "type": "workspaces", "attributes": { "name": "no-code-workspace", "description": "A workspace to enable the no-code provisioning workflow." }, "relationships": { "project": { "data": { "id": "prj-yuEN6sJVra5t6XVy", "type": "project" } }, "vars": { "data": [ { "type": "vars", "attributes": { "key": "region", "value": "eu-central-1", "category": "terraform", "hcl": true, "sensitive": false, } }, { "type": "vars", "attributes": { "key": "ami", "value": "ami‑077062", "category": "terraform", "hcl": true, "sensitive": false, } } ] } } } } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/no-code-modules/nocode-WGckovT2RQxupyt1/workspaces ``` ### Sample Response ```json { "data": { "id": "ws-qACTToFUM5BvDKhC", "type": "workspaces", "attributes": { "allow-destroy-plan": true, "auto-apply": false, "auto-destroy-at": null, "auto-destroy-status": null, "created-at": "2023-09-08T10:36:04.391Z", "environment": "default", "locked": false, "name": "no-code-workspace", "queue-all-runs": false, "speculative-enabled": true, "structured-run-output-enabled": true, "terraform-version": "1.5.6", "working-directory": null, "global-remote-state": true, "updated-at": "2023-09-08T10:36:04.427Z", "resource-count": 0, "apply-duration-average": null, "plan-duration-average": null, "policy-check-failures": null, "run-failures": null, "workspace-kpis-runs-count": null, "latest-change-at": "2023-09-08T10:36:04.391Z", "operations": true, "execution-mode": "remote", "vcs-repo": null, "vcs-repo-identifier": null, "permissions": { "can-update": true, "can-destroy": true, "can-queue-run": true, "can-read-variable": true, "can-update-variable": true, "can-read-state-versions": true, "can-read-state-outputs": true, "can-create-state-versions": true, "can-queue-apply": true, "can-lock": true, "can-unlock": true, "can-force-unlock": true, "can-read-settings": true, "can-manage-tags": true, "can-manage-run-tasks": true, "can-force-delete": true, "can-manage-assessments": true, "can-manage-ephemeral-workspaces": true, "can-read-assessment-results": true, "can-queue-destroy": true }, "actions": { "is-destroyable": true }, "description": null, "file-triggers-enabled": true, "trigger-prefixes": [], "trigger-patterns": [], "assessments-enabled": false, "last-assessment-result-at": null, "source": "tfe-module", "source-name": null, "source-url": null, "source-module-id": "private/my-organization/lambda/aws/1.0.9", "no-code-upgrade-available": false, "tag-names": [], "setting-overwrites": { "execution-mode": false, "agent-pool": false } }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" } }, "current-run": { "data": null }, "latest-run": { "data": null }, "outputs": { "data": [] }, "remote-state-consumers": { "links": { "related": "/api/v2/workspaces/ws-qACTToFUM5BvDKhC/relationships/remote-state-consumers" } }, "current-state-version": { "data": null }, "current-configuration-version": { "data": { "id": "cv-vizi2p3mnrt3utgA", "type": "configuration-versions" }, "links": { "related": "/api/v2/configuration-versions/cv-vizi2p3mnrt3utgA" } }, "agent-pool": { "data": null }, "readme": { "data": null }, "project": { "data": { "id": "prj-yuEN6sJVra5t6XVy", "type": "projects" } }, "current-assessment-result": { "data": null }, "no-code-module-version": { "data": { "id": "nocodever-vFcQjZLs3ZHTe4TU", "type": "no-code-module-versions" } }, "vars": { "data": [] } }, "links": { "self": "/api/v2/organizations/my-organization/workspaces/no-code-workspace", "self-html": "/app/my-organization/workspaces/no-code-workspace" } } } ``` ## Initiate a no-code workspace update Upgrading a workspace's no-code provisioning settings is a multi-step process. 1. Use this API to initiate the update. HCP Terraform starts a new plan, which describes the resources to add, update, or remove from the workspace. 1. Poll the [read workspace upgrade plan status API](#read-workspace-upgrade-plan-status) to wait for HCP Terraform to complete the plan. 1. Use the [confirm and apply a workspace upgrade plan API](#confirm-and-apply-a-workspace-upgrade-plan) to complete the workspace upgrade. `POST /no-code-modules/:no_code_module_id/workspaces/:id/upgrade` | Parameter | Description | | -------------------- | -------------------------------| | `:no_code_module_id` | The ID of the no-code module. | | `:id` | The ID of the workspace. | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | --- | --- | --- | --- | `data.type` | string | | Must be `"workspaces"`. | `data.relationships.vars.data[].type` | string | | Must be `"vars"`. | | `data.relationships.vars.data[].attributes.key` | string | | The name of the variable. | | `data.relationships.vars.data[].attributes.value` | string | `""` | The value of the variable. | | `data.relationships.vars.data[].attributes.description` | string | | The description of the variable. | | `data.relationships.vars.data[].attributes.category` | string | | Whether this is a Terraform or environment variable. Valid values are `"terraform"` or `"env"`. | | `data.relationships.vars.data[].attributes.hcl` | boolean | `false` | Whether to evaluate the value of the variable as a string of HCL code. Has no effect for environment variables. | | `data.relationships.vars.data[].attributes.sensitive` | boolean | `false` | Whether the value is sensitive. If `true` then the variable is written once and not visible thereafter. | ### Sample Payload ```json { "data": { "type": "workspaces", "relationships": { "vars": { "data": [ { "type": "vars", "attributes": { "key": "region", "value": "eu-central-1", "category": "terraform", "hcl": true, "sensitive": false, } }, { "type": "vars", "attributes": { "key": "ami", "value": "ami‑077062", "category": "terraform", "hcl": true, "sensitive": false, } } ] } } } } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/no-code-modules/nocode-WGckovT2RQxupyt1/workspaces/ws-qACTToFUM5BvDKhC/upgrade ``` ### Sample Response ```json { "data": { "id": "run-Cyij8ctBHM1g5xdX", "type": "workspace-upgrade", "attributes": { "status": "planned", "plan-url": "https://app.terraform.io/app/my-organization/no-code-workspace/runs/run-Cyij8ctBHM1g5xdX" }, "relationships": { "workspace": { "data": { "id": "ws-VvKtcfueHNkR6GqP", "type": "workspaces" } } } } } ``` ## Read workspace upgrade plan status This endpoint returns the plan details and status for updating a workspace to new no-code provisioning settings. `GET /no-code-modules/:no_code_module_id/workspaces/:workspace_id/upgrade/:id` | Parameter | Description | | -------------------- | -------------------------------| | `:no_code_module_id` | The ID of the no-code module. | | `:workspace_id` | The ID of workspace. | | `:id` | The ID of update. | Returns the details of a no-code workspace update run, including the run's current state, such as `pending`, `fetching`, `planning`, `planned`, or `cost_estimated`. Refer to [Run States and Stages](/terraform/enterprise/run/states) for more information on the states a run can return. | Status | Response | Reason | | ------- | ------------------------------------------------------- | --------------------------------------------------------------------| | [200][] | [JSON API document][] (`type: "workspace-upgrade"`) | Success | | [404][] | [JSON API error object][] | Workspace upgrade not found, or user unauthorized to perform action | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/no-code-modules/nocode-WGckovT2RQxupyt1/workspaces/ws-qACTToFUM5BvDKhC/upgrade/run-Cyij8ctBHM1g5xdX ``` ### Sample Response ```json { "data": { "id": "run-Cyij8ctBHM1g5xdX", "type": "workspace-upgrade", "attributes": { "status": "planned_and_finished", "plan-url": "https://app.terraform.io/app/my-organization/no-code-workspace/runs/run-Cyij8ctBHM1g5xdX" }, "relationships": { "workspace": { "data": { "id": "ws-VvKtcfueHNkR6GqP", "type": "workspaces" } } } } } ``` ## Confirm and apply a workspace upgrade plan Use this endpoint to confirm an update and finalize the update for a workspace to use new no-code provisioning settings. `POST /no-code-modules/:no_code_module_id/workspaces/:workspace_id/upgrade/:id` | Parameter | Description | | -------------------- | -------------------------------| | `:no_code_module_id` | The ID of the no-code module. | | `:workspace_id` | The ID of workspace. | | `:id` | The ID of update. | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ https://app.terraform.io/api/v2/no-code-modules/nocode-WGckovT2RQxupyt1/workspaces/ws-qACTToFUM5BvDKhC/upgrade/run-Cyij8ctBHM1g5xdX ``` ### Sample Response ```json { "Workspace update completed" } ```
terraform
page title No Code Provisioning API Docs HCP Terraform description Use these endpoints to control availability of no code provisioning and designate variable values for a no code module in your organization 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object http jsonapi org format error objects No code provisioning API The no code provisioning API allows you to create configure and deploy Terraform modules in the no code provisioning workflows within HCP Terraform For more information on no code modules refer to Designing No Code Ready Modules terraform cloud docs no code provisioning module design Enable no code provisioning for a module POST organizations organization name no code modules Parameter Description organization name The name of the organization the module belongs to To deploy a module using the no code provisioning workflow the module must meet the following requirement 1 The module must exist in your organization s private registry 1 The module must meet the design requirements terraform cloud docs no code provisioning module design requirements for a no code module 1 You must enable no code provisioning for the module You can send a POST request to the no code modules endpoint to enable no code provisioning for a specific module You can also call this endpoint to set options for the allowed values of a variable for a no code module in your organization Note This endpoint can not be accessed with organization tokens terraform cloud docs users teams organizations api tokens organization api tokens You must access it with a user token terraform cloud docs users teams organizations users api tokens or team token terraform cloud docs users teams organizations api tokens team api tokens Status Response Reason 200 JSON API document type no code modules Successfully enabled a module for no code provisioning 404 JSON API error object Not found or the user is unauthorized to perform this action 422 JSON API error object Malformed request body e g missing attributes wrong types etc 500 JSON API error object Internal system failure Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string Must be no code modules data attributes version pin string Latest version of the module The module version to use in no code provisioning workflows data attributes enabled boolean false Set to true to enable no code provisioning workflows data relationships registry module data id string The ID of a module in the organization s private registry data relationships registry module data type string Must be registry module data relationships variable options data type string Must be variable options data relationships variable options data attributes variable name string The name of a variable within the module data relationships variable options data attributes variable type string The data type for the variable Can be any type supported by Terraform terraform language expressions types types data relationships variable options data attributes options Any A list of allowed values for the variable Sample Payload json data type no code modules attributes version pin 1 0 1 enabled true relationships registry module data id mod 2aaFrmRPZs2N9epr type registry module variable options data type variable options attributes variable name amis variable type string options ami 1 ami 2 ami 3 type variable options attributes variable name region variable type string options eu north 1 us east 2 us west 1 Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 organizations my organization no code modules Sample Response json data id nocode 9HE91XDNY3faePn2 type no code modules attributes enabled true version pin 1 0 1 relationships organization data id my organization type organizations links related api v2 organizations my organization registry module data id mod 2aaFrmRPZs2N9epr type registry modules links related api v2 registry modules mod 2aaFrmRPZs2N9epr variable options data id ncvaropt fcHDfnZ1EGdRzFNC type variable options id ncvaropt dZMfdh9KBcwFjyv2 type variable options links self api v2 no code modules nocode 9HE91XDNY3faePn2 Update no code provisioning settings PATCH no code modules id Parameter Description id The unique identifier of the no code module Send a PATCH request to the no code modules id endpoint to update the settings for the no code provisioning of a module You can update the following settings Enable or disable no code provisioning Adjust the set of options for allowed variable values Change the module version being provisioned Change the module being provisioned The API call that enables no code provisioning for a module allow no code provisioning of a module within an organization returns that module s unique identifier Note This endpoint cannot be accessed with organization tokens terraform cloud docs users teams organizations api tokens organization api tokens You must access it with a user token terraform cloud docs users teams organizations users api tokens or team token terraform cloud docs users teams organizations api tokens team api tokens Status Response Reason 200 JSON API document type no code modules Successfully updated a no code module 404 JSON API error object Not found or the user is unauthorized to perform this action 422 JSON API error object Malformed request body e g missing attributes wrong types etc 500 JSON API error object Internal system failure Request Body This PATCH endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string Must be no code modules data attributes version pin string Existing value The module version to use in no code provisioning workflows data attributes enabled boolean Existing value Set to true to enable no code provisioning workflows or false to disable them data relationships registry module data id string Existing value The ID of a module in the organization s Private Registry data relationships registry module data type string Existing value Must be registry module data relationships variable options data id string The ID of an existing variable options set If provided a new variable options set replaces the set with this ID If not provided this creates a new variable option set data relationships variable options data type string Must be variable options data relationships variable options data attributes variable name string The name of a variable within the module data relationships variable options data attributes variable type string The data type for the variable Can be any type supported by Terraform terraform language expressions types types data relationships variable options data attributes options Any A list of allowed values for the variable Sample Payload json data type no code modules attributes enabled false relationships registry module data id mod zyai9dwH4VPPaVuC type registry module variable options data id ncvaropt fcHDfnZ1EGdRzFNC type variable options attributes variable name Linux AMIs variable type array options Xenial Xerus Trusty Tahr id ncvaropt dZMfdh9KBcwFjyv2 type variable options attributes variable name region variable type array options eu north 1 us east 2 us west 1 Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request PATCH data payload json https app terraform io api v2 no code modules nocode 9HE91XDNY3faePn2 Sample Response json data id nocode 9HE91XDNY3faePn2 type no code modules attributes enabled true version pin 1 0 1 relationships organization data id my organization type organizations links related api v2 organizations my organization registry module data id mod 2aaFrmRPZs2N9epr type registry modules links related api v2 registry modules mod 2aaFrmRPZs2N9epr variable options data id ncvaropt fcHDfnZ1EGdRzFNC type variable options id ncvaropt dZMfdh9KBcwFjyv2 type variable options links self api v2 no code modules nocode 9HE91XDNY3faePn2 Read a no code module s properties GET no code modules id Parameter Description id The unique identifier of the no code module Use this API to read the details of an existing no code module The API call that enables no code provisioning for a module allow no code provisioning of a module within an organization returns that module s unique identifier Status Response Reason 200 JSON API document type no code modules Successfully read the no code module 400 JSON API error object Invalid include parameter 404 JSON API error object Not found or the user is unauthorized to perform this action 422 JSON API error object Malformed request body e g missing attributes wrong types etc 500 JSON API error object Internal system failure Query Parameters This endpoint uses our standard URL query parameters terraform cloud docs api docs query parameters Use HTML URL encoding syntax such as 5B to represent and 5D to represent if your tooling does not automatically encode URLs Terraform returns related resources when you add the include query parameter terraform cloud docs api docs inclusion of related resources to the request Parameter Description include List related resource to include in the response The following resource types are available Resource Name Description variable options Module variables with a configured set of allowed values Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 no code modules nocode 9HE91XDNY3faePn2 include variable options Sample Response json data id nocode 9HE91XDNY3faePn2 type no code modules attributes enabled true version pin 1 0 1 relationships organization data id my organization type organizations links related api v2 organizations my organization registry module data id mod 2aaFrmRPZs2N9epr type registry modules links related api v2 registry modules mod 2aaFrmRPZs2N9epr variable options data id ncvaropt fcHDfnZ1EGdRzFNC type variable options id ncvaropt dZMfdh9KBcwFjyv2 type variable options links self api v2 no code modules nocode 9HE91XDNY3faePn2 included id ncvaropt fcHDfnZ1EGdRzFNC type variable options attributes variable name Linux AMIs variable type array options Xenial Xerus Trusty Tahr relationships no code allowed module data id nocode 9HE91XDNY3faePn2 type no code allowed modules id ncvaropt dZMfdh9KBcwFjyv2 type variable options attributes variable name region variable type array options eu north 1 us east 2 us west 1 relationships no code allowed module data id nocode 9HE91XDNY3faePn2 type no code allowed modules Create a no code module workspace This endpoint creates a workspace from a no code module POST no code modules id workspaces Parameter Description id The ID of the no code module to provision Each HCP Terraform organization has a list of which modules you can use to create workspaces using no code provisioning You can use this API to create a workspace by selecting a no code module to enable a no code provisioning workflow Note This endpoint can not be accessed with organization tokens terraform cloud docs users teams organizations api tokens organization api tokens You must access it with a user token terraform cloud docs users teams organizations users api tokens or team token terraform cloud docs users teams organizations api tokens team api tokens Status Response Reason 200 JSON API document type workspaces Successfully created a workspace from a no code module for no code provisioning 404 JSON API error object Not found or the user is unauthorized to perform this action 422 JSON API error object Malformed request body e g missing attributes wrong types etc 500 JSON API error object Internal system failure Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string none Must be workspaces data attributes agent pool id string none Required when execution mode is set to agent The ID of the agent pool belonging to the workspace s organization This value must not be specified if execution mode is set to remote data attributes auto apply boolean false If true Terraform automatically applies changes when a Terraform plan is successful data attributes description string A description for the workspace data attributes execution mode string none Which execution mode terraform cloud docs workspaces settings execution mode to use Valid values are remote and agent When not provided defaults to remote data attributes name string none The name of the workspace You can only include letters numbers and Terraform uses this value to identify the workspace and must be unique in the organization data attributes source name string none A friendly name for the application or client creating this workspace If set this will be displayed on the workspace as Created via SOURCE NAME data attributes source url string nothing A URL for the application or client creating this workspace This can be the URL of a related resource in another app or a link to documentation or other info about the client data relationships project data id string The ID of the project to create the workspace in You must have permission to create workspaces in the project either by organization level permissions or team admin access to a specific project data relationships project data type string Must be project data relationships vars data type string Must be vars data relationships vars data attributes key string The name of the variable data relationships vars data attributes value string The value of the variable data relationships vars data attributes description string The description of the variable data relationships vars data attributes category string Whether this is a Terraform or environment variable Valid values are terraform or env data relationships vars data attributes hcl boolean false Whether to evaluate the value of the variable as a string of HCL code Has no effect for environment variables data relationships vars data attributes sensitive boolean false Whether the value is sensitive If true then the variable is written once and not visible thereafter Sample Payload json data type workspaces attributes name no code workspace description A workspace to enable the no code provisioning workflow relationships project data id prj yuEN6sJVra5t6XVy type project vars data type vars attributes key region value eu central 1 category terraform hcl true sensitive false type vars attributes key ami value ami 077062 category terraform hcl true sensitive false Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 no code modules nocode WGckovT2RQxupyt1 workspaces Sample Response json data id ws qACTToFUM5BvDKhC type workspaces attributes allow destroy plan true auto apply false auto destroy at null auto destroy status null created at 2023 09 08T10 36 04 391Z environment default locked false name no code workspace queue all runs false speculative enabled true structured run output enabled true terraform version 1 5 6 working directory null global remote state true updated at 2023 09 08T10 36 04 427Z resource count 0 apply duration average null plan duration average null policy check failures null run failures null workspace kpis runs count null latest change at 2023 09 08T10 36 04 391Z operations true execution mode remote vcs repo null vcs repo identifier null permissions can update true can destroy true can queue run true can read variable true can update variable true can read state versions true can read state outputs true can create state versions true can queue apply true can lock true can unlock true can force unlock true can read settings true can manage tags true can manage run tasks true can force delete true can manage assessments true can manage ephemeral workspaces true can read assessment results true can queue destroy true actions is destroyable true description null file triggers enabled true trigger prefixes trigger patterns assessments enabled false last assessment result at null source tfe module source name null source url null source module id private my organization lambda aws 1 0 9 no code upgrade available false tag names setting overwrites execution mode false agent pool false relationships organization data id my organization type organizations current run data null latest run data null outputs data remote state consumers links related api v2 workspaces ws qACTToFUM5BvDKhC relationships remote state consumers current state version data null current configuration version data id cv vizi2p3mnrt3utgA type configuration versions links related api v2 configuration versions cv vizi2p3mnrt3utgA agent pool data null readme data null project data id prj yuEN6sJVra5t6XVy type projects current assessment result data null no code module version data id nocodever vFcQjZLs3ZHTe4TU type no code module versions vars data links self api v2 organizations my organization workspaces no code workspace self html app my organization workspaces no code workspace Initiate a no code workspace update Upgrading a workspace s no code provisioning settings is a multi step process 1 Use this API to initiate the update HCP Terraform starts a new plan which describes the resources to add update or remove from the workspace 1 Poll the read workspace upgrade plan status API read workspace upgrade plan status to wait for HCP Terraform to complete the plan 1 Use the confirm and apply a workspace upgrade plan API confirm and apply a workspace upgrade plan to complete the workspace upgrade POST no code modules no code module id workspaces id upgrade Parameter Description no code module id The ID of the no code module id The ID of the workspace Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string Must be workspaces data relationships vars data type string Must be vars data relationships vars data attributes key string The name of the variable data relationships vars data attributes value string The value of the variable data relationships vars data attributes description string The description of the variable data relationships vars data attributes category string Whether this is a Terraform or environment variable Valid values are terraform or env data relationships vars data attributes hcl boolean false Whether to evaluate the value of the variable as a string of HCL code Has no effect for environment variables data relationships vars data attributes sensitive boolean false Whether the value is sensitive If true then the variable is written once and not visible thereafter Sample Payload json data type workspaces relationships vars data type vars attributes key region value eu central 1 category terraform hcl true sensitive false type vars attributes key ami value ami 077062 category terraform hcl true sensitive false Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 no code modules nocode WGckovT2RQxupyt1 workspaces ws qACTToFUM5BvDKhC upgrade Sample Response json data id run Cyij8ctBHM1g5xdX type workspace upgrade attributes status planned plan url https app terraform io app my organization no code workspace runs run Cyij8ctBHM1g5xdX relationships workspace data id ws VvKtcfueHNkR6GqP type workspaces Read workspace upgrade plan status This endpoint returns the plan details and status for updating a workspace to new no code provisioning settings GET no code modules no code module id workspaces workspace id upgrade id Parameter Description no code module id The ID of the no code module workspace id The ID of workspace id The ID of update Returns the details of a no code workspace update run including the run s current state such as pending fetching planning planned or cost estimated Refer to Run States and Stages terraform enterprise run states for more information on the states a run can return Status Response Reason 200 JSON API document type workspace upgrade Success 404 JSON API error object Workspace upgrade not found or user unauthorized to perform action Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 no code modules nocode WGckovT2RQxupyt1 workspaces ws qACTToFUM5BvDKhC upgrade run Cyij8ctBHM1g5xdX Sample Response json data id run Cyij8ctBHM1g5xdX type workspace upgrade attributes status planned and finished plan url https app terraform io app my organization no code workspace runs run Cyij8ctBHM1g5xdX relationships workspace data id ws VvKtcfueHNkR6GqP type workspaces Confirm and apply a workspace upgrade plan Use this endpoint to confirm an update and finalize the update for a workspace to use new no code provisioning settings POST no code modules no code module id workspaces workspace id upgrade id Parameter Description no code module id The ID of the no code module workspace id The ID of workspace id The ID of update Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST https app terraform io api v2 no code modules nocode WGckovT2RQxupyt1 workspaces ws qACTToFUM5BvDKhC upgrade run Cyij8ctBHM1g5xdX Sample Response json Workspace update completed
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 page title Variables API Docs HCP Terraform 201 https developer mozilla org en US docs Web HTTP Status 201 Use the vars endpoint to manage organization level variables List create update and delete variables using the HTTP API
--- page_title: Variables - API Docs - HCP Terraform description: >- Use the `/vars` endpoint to manage organization-level variables. List, create, update, and delete variables using the HTTP API. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # Variables API ~> **Important**: The Variables API is **deprecated** and will be removed in a future release. All existing integrations with this API should transition to the [Workspace Variables API](/terraform/cloud-docs/api-docs/workspace-variables). This set of APIs covers create, update, list and delete operations on variables. ## Create a Variable `POST /vars` ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | ---------------------------------------- | ------ | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data.type` | string | | Must be `"vars"`. | | `data.attributes.key` | string | | The name of the variable. | | `data.attributes.value` | string | `""` | The value of the variable. | | `data.attributes.description` | string | | The description of the variable. | | `data.attributes.category` | string | | Whether this is a Terraform or environment variable. Valid values are `"terraform"` or `"env"`. | | `data.attributes.hcl` | bool | `false` | Whether to evaluate the value of the variable as a string of HCL code. Has no effect for environment variables. | | `data.attributes.sensitive` | bool | `false` | Whether the value is sensitive. If true then the variable is written once and not visible thereafter. | | `data.relationships.workspace.data.type` | string | | Must be `"workspaces"`. | | `data.relationships.workspace.data.id` | string | | The ID of the workspace that owns the variable. Obtain workspace IDs from the [workspace settings](/terraform/cloud-docs/workspaces/settings) or the [Show Workspace](/terraform/cloud-docs/api-docs/workspaces#show-workspace) endpoint. | **Deprecation warning**: The custom `filter` properties are replaced by JSON API `relationships` and will be removed from future versions of the API! | Key path | Type | Default | Description | | -------------------------- | ------ | ------- | ----------------------------------------------------- | | `filter.workspace.name` | string | | The name of the workspace that owns the variable. | | `filter.organization.name` | string | | The name of the organization that owns the workspace. | ### Sample Payload ```json { "data": { "type":"vars", "attributes": { "key":"some_key", "value":"some_value", "description":"some description", "category":"terraform", "hcl":false, "sensitive":false }, "relationships": { "workspace": { "data": { "id":"ws-4j8p6jX1w33MiDC7", "type":"workspaces" } } } } } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/vars ``` ### Sample Response ```json { "data": { "id":"var-EavQ1LztoRTQHSNT", "type":"vars", "attributes": { "key":"some_key", "value":"some_value", "description":"some description", "sensitive":false, "category":"terraform", "hcl":false }, "relationships": { "configurable": { "data": { "id":"ws-4j8p6jX1w33MiDC7", "type":"workspaces" }, "links": { "related":"/api/v2/organizations/my-organization/workspaces/my-workspace" } } }, "links": { "self":"/api/v2/vars/var-EavQ1LztoRTQHSNT" } } } ``` ## List Variables `GET /vars` ### Query Parameters [These are standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. | Parameter | Description | | ---------------------------- | -------------------------------------------------------------------------- | | `filter[workspace][name]` | **Required** The name of one workspace to list variables for. | | `filter[organization][name]` | **Required** The name of the organization that owns the desired workspace. | These two parameters are optional but linked; if you include one, you must include both. Without a filter, this method lists variables for all workspaces where you have permission to read variables. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) [permissions-citation]: #intentionally-unused---keep-for-maintainers ### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ "https://app.terraform.io/api/v2/vars?filter%5Borganization%5D%5Bname%5D=my-organization&filter%5Bworkspace%5D%5Bname%5D=my-workspace" # ?filter[organization][name]=my-organization&filter[workspace][name]=demo01 ``` ### Sample Response ```json { "data": [ { "id":"var-AD4pibb9nxo1468E", "type":"vars","attributes": { "key":"name", "value":"hello", "description":"some description", "sensitive":false, "category":"terraform", "hcl":false }, "relationships": { "configurable": { "data": { "id":"ws-cZE9LERN3rGPRAmH", "type":"workspaces" }, "links": { "related":"/api/v2/organizations/my-organization/workspaces/my-workspace" } } }, "links": { "self":"/api/v2/vars/var-AD4pibb9nxo1468E" } } ] } ``` ## Update Variables `PATCH /vars/:variable_id` | Parameter | Description | | -------------- | ------------------------------------- | | `:variable_id` | The ID of the variable to be updated. | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | ----------------- | ------ | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data.type` | string | | Must be `"vars"`. | | `data.id` | string | | The ID of the variable to update. | | `data.attributes` | object | | New attributes for the variable. This object can include `key`, `value`, `description`, `category`, `hcl`, and `sensitive` properties, which are described above under [create a variable](#create-a-variable). All of these properties are optional; if omitted, a property will be left unchanged. | ### Sample Payload ```json { "data": { "id":"var-yRmifb4PJj7cLkMG", "attributes": { "key":"name", "value":"mars", "description": "new description", "category":"terraform", "hcl": false, "sensitive": false }, "type":"vars" } } ``` ### Sample Request ```bash $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request PATCH \ --data @payload.json \ https://app.terraform.io/api/v2/vars/var-yRmifb4PJj7cLkMG ``` ### Sample Response ```json { "data": { "id":"var-yRmifb4PJj7cLkMG", "type":"vars", "attributes": { "key":"name", "value":"mars", "description":"new description", "sensitive":false, "category":"terraform", "hcl":false }, "relationships": { "configurable": { "data": { "id":"ws-4j8p6jX1w33MiDC7", "type":"workspaces" }, "links": { "related":"/api/v2/organizations/workspace-v2-06/workspaces/workspace-v2-06" } } }, "links": { "self":"/api/v2/vars/var-yRmifb4PJj7cLkMG" } } } ``` ## Delete Variables `DELETE /vars/:variable_id` | Parameter | Description | | -------------- | ------------------------------------- | | `:variable_id` | The ID of the variable to be deleted. | ### Sample Request ```bash $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request DELETE \ https://app.terraform.io/api/v2/vars/var-yRmifb4PJj7cLkMG ```
terraform
page title Variables API Docs HCP Terraform description Use the vars endpoint to manage organization level variables List create update and delete variables using the HTTP API 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects Variables API Important The Variables API is deprecated and will be removed in a future release All existing integrations with this API should transition to the Workspace Variables API terraform cloud docs api docs workspace variables This set of APIs covers create update list and delete operations on variables Create a Variable POST vars Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string Must be vars data attributes key string The name of the variable data attributes value string The value of the variable data attributes description string The description of the variable data attributes category string Whether this is a Terraform or environment variable Valid values are terraform or env data attributes hcl bool false Whether to evaluate the value of the variable as a string of HCL code Has no effect for environment variables data attributes sensitive bool false Whether the value is sensitive If true then the variable is written once and not visible thereafter data relationships workspace data type string Must be workspaces data relationships workspace data id string The ID of the workspace that owns the variable Obtain workspace IDs from the workspace settings terraform cloud docs workspaces settings or the Show Workspace terraform cloud docs api docs workspaces show workspace endpoint Deprecation warning The custom filter properties are replaced by JSON API relationships and will be removed from future versions of the API Key path Type Default Description filter workspace name string The name of the workspace that owns the variable filter organization name string The name of the organization that owns the workspace Sample Payload json data type vars attributes key some key value some value description some description category terraform hcl false sensitive false relationships workspace data id ws 4j8p6jX1w33MiDC7 type workspaces Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 vars Sample Response json data id var EavQ1LztoRTQHSNT type vars attributes key some key value some value description some description sensitive false category terraform hcl false relationships configurable data id ws 4j8p6jX1w33MiDC7 type workspaces links related api v2 organizations my organization workspaces my workspace links self api v2 vars var EavQ1LztoRTQHSNT List Variables GET vars Query Parameters These are standard URL query parameters terraform cloud docs api docs query parameters Remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs Parameter Description filter workspace name Required The name of one workspace to list variables for filter organization name Required The name of the organization that owns the desired workspace These two parameters are optional but linked if you include one you must include both Without a filter this method lists variables for all workspaces where you have permission to read variables More about permissions terraform cloud docs users teams organizations permissions permissions citation intentionally unused keep for maintainers Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 vars filter 5Borganization 5D 5Bname 5D my organization filter 5Bworkspace 5D 5Bname 5D my workspace filter organization name my organization filter workspace name demo01 Sample Response json data id var AD4pibb9nxo1468E type vars attributes key name value hello description some description sensitive false category terraform hcl false relationships configurable data id ws cZE9LERN3rGPRAmH type workspaces links related api v2 organizations my organization workspaces my workspace links self api v2 vars var AD4pibb9nxo1468E Update Variables PATCH vars variable id Parameter Description variable id The ID of the variable to be updated Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string Must be vars data id string The ID of the variable to update data attributes object New attributes for the variable This object can include key value description category hcl and sensitive properties which are described above under create a variable create a variable All of these properties are optional if omitted a property will be left unchanged Sample Payload json data id var yRmifb4PJj7cLkMG attributes key name value mars description new description category terraform hcl false sensitive false type vars Sample Request bash curl header Authorization Bearer TOKEN header Content Type application vnd api json request PATCH data payload json https app terraform io api v2 vars var yRmifb4PJj7cLkMG Sample Response json data id var yRmifb4PJj7cLkMG type vars attributes key name value mars description new description sensitive false category terraform hcl false relationships configurable data id ws 4j8p6jX1w33MiDC7 type workspaces links related api v2 organizations workspace v2 06 workspaces workspace v2 06 links self api v2 vars var yRmifb4PJj7cLkMG Delete Variables DELETE vars variable id Parameter Description variable id The ID of the variable to be deleted Sample Request bash curl header Authorization Bearer TOKEN header Content Type application vnd api json request DELETE https app terraform io api v2 vars var yRmifb4PJj7cLkMG
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 page title OAuth Clients API Docs HCP Terraform Use the oauth clients endpoint to manage OAuth connections between your organization and a VCS provider List show create update and destroy clients using the HTTP API Attach and detach OAuth clients to projects
--- page_title: OAuth Clients - API Docs - HCP Terraform description: >- Use the `/oauth-clients` endpoint to manage OAuth connections between your organization and a VCS provider. List, show, create, update, and destroy clients using the HTTP API. Attach and detach OAuth clients to projects. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # OAuth Clients API An OAuth client represents the connection between an organization and a VCS provider. By default, you can globally access an OAuth client throughout the organization, or you can have scope access to one or more [projects](/terraform/cloud-docs/projects/manage). ## List OAuth Clients `GET /organizations/:organization_name/oauth-clients` | Parameter | Description | | -------------------- | ----------------------------- | | `:organization_name` | The name of the organization. | This endpoint allows you to list VCS connections between an organization and a VCS provider (GitHub, Bitbucket, or GitLab) for use when creating or setting up workspaces. | Status | Response | Reason | | ------- | ----------------------------------------------- | ---------------------- | | [200][] | [JSON API document][] (`type: "oauth-clients"`) | Success | | [404][] | [JSON API error object][] | Organization not found | ### Query Parameters This endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. If neither pagination query parameters are provided, the endpoint will not be paginated and will return all results. | Parameter | Description | | -------------- | ----------------------------------------------------------------------------- | | `page[number]` | **Optional.** If omitted, the endpoint will return the first page. | | `page[size]` | **Optional.** If omitted, the endpoint will return 20 oauth clients per page. | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/organizations/my-organization/oauth-clients ``` ### Sample Response ```json { "data": [ { "id": "oc-XKFwG6ggfA9n7t1K", "type": "oauth-clients", "attributes": { "created-at": "2018-04-16T20:42:53.771Z", "callback-url": "https://app.terraform.io/auth/35936d44-842c-4ddd-b4d4-7c741383dc3a/callback", "connect-path": "/auth/35936d44-842c-4ddd-b4d4-7c741383dc3a?organization_id=1", "service-provider": "github", "service-provider-display-name": "GitHub", "name": null, "http-url": "https://github.com", "api-url": "https://api.github.com", "key": null, "rsa-public-key": null, "organization-scoped": false }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" }, "links": { "related": "/api/v2/organizations/my-organization" } }, "projects": { "data": [ { "id": "prj-AwfuCJTkdai4xj9w", "type": "projects" } ] }, "oauth-tokens": { "data": [], "links": { "related": "/api/v2/oauth-tokens/ot-KaeqH4cy72VPXFQT" } }, "agent-pool": { "data": { "id": "apool-VsmjEMcYkShrckpK", "type": "agent-pools" }, "links": { "related": "/api/v2/agent-pools/apool-VsmjEMcYkShrckpK" } } } } ] } ``` ## Show an OAuth Client `GET /oauth-clients/:id` | Parameter | Description | | --------- | ---------------------------------- | | `:id` | The ID of the OAuth Client to show | | Status | Response | Reason | | ------- | ----------------------------------------------- | -------------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "oauth-clients"`) | Success | | [404][] | [JSON API error object][] | OAuth Client not found, or user unauthorized to perform action | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/oauth-clients/oc-XKFwG6ggfA9n7t1K ``` ### Sample Response ```json { "data": { "id": "oc-XKFwG6ggfA9n7t1K", "type": "oauth-clients", "attributes": { "created-at": "2018-04-16T20:42:53.771Z", "callback-url": "https://app.terraform.io/auth/35936d44-842c-4ddd-b4d4-7c741383dc3a/callback", "connect-path": "/auth/35936d44-842c-4ddd-b4d4-7c741383dc3a?organization_id=1", "service-provider": "github", "service-provider-display-name": "GitHub", "name": null, "http-url": "https://github.com", "api-url": "https://api.github.com", "key": null, "rsa-public-key": null, "organization-scoped": false }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" }, "links": { "related": "/api/v2/organizations/my-organization" } }, "projects": { "data": [ { "id": "prj-AwfuCJTkdai4xj9w", "type": "projects" } ] }, "oauth-tokens": { "data": [], "links": { "related": "/api/v2/oauth-tokens/ot-KaeqH4cy72VPXFQT" } }, "agent-pool": { "data": { "id": "apool-VsmjEMcYkShrckpK", "type": "agent-pools" }, "links": { "related": "/api/v2/agent-pools/apool-VsmjEMcYkShrckpK" } } } } } ``` ## Create an OAuth Client `POST /organizations/:organization_name/oauth-clients` | Parameter | Description | | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `:organization_name` | The name of the organization that will be connected to the VCS provider. The organization must already exist in the system, and the user must have permission to manage VCS settings. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) | [permissions-citation]: #intentionally-unused---keep-for-maintainers This endpoint allows you to create a VCS connection between an organization and a VCS provider (GitHub or GitLab) for use when creating or setting up workspaces. By using this API endpoint, you can provide a pre-generated OAuth token string instead of going through the process of creating a GitHub or GitLab OAuth Application. To learn how to generate one of these token strings for your VCS provider, you can read the following documentation: * [GitHub and GitHub Enterprise](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token) * [GitLab, GitLab Community Edition, and GitLab Enterprise Edition](https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html#create-a-personal-access-token) * [Azure DevOps Server](https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=azure-devops-2019&tabs=preview-page) | Status | Response | Reason | | ------- | ----------------------------------------------- | -------------------------------------------------------------- | | [201][] | [JSON API document][] (`type: "oauth-clients"`) | OAuth Client successfully created | | [404][] | [JSON API error object][] | Organization not found or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (missing attributes, wrong types, etc.) | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | ------------------------------------ | ------ | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data.type` | string | | Must be `"oauth-clients"`. | | `data.attributes.service-provider` | string | | The VCS provider being connected with. Valid options are `"github"`, `"github_enterprise"`, `"gitlab_hosted"`, `"gitlab_community_edition"`, `"gitlab_enterprise_edition"`, or `"ado_server"`. | | `data.attributes.name` | string | `null` | An optional display name for the OAuth Client. If left `null`, the UI will default to the display name of the VCS provider. | | `data.attributes.key` | string | | The OAuth Client key. It can refer to a Consumer Key, Application Key, or another type of client key for the VCS provider. | | `data.attributes.http-url` | string | | The homepage of your VCS provider (e.g. `"https://github.com"` or `"https://ghe.example.com"` or `"https://gitlab.com"`). | | `data.attributes.api-url` | string | | The base URL as per your VCS provider's API documentation (e.g. `"https://api.github.com"`, `"https://ghe.example.com/api/v3"` or `"https://gitlab.com/api/v4"`). | | `data.attributes.oauth-token-string` | string | | The token string you were given by your VCS provider | | `data.attributes.private-key` | string | | **Required for Azure DevOps Server. Not used for any other providers.** The text of the SSH private key associated with your Azure DevOps Server account. | | `data.attributes.secret` | string | | The OAuth client secret. For Bitbucket Data Center, the secret is the text of the SSH private key associated with your Bitbucket Data Center application link. | | `data.attributes.rsa-public-key` | string | | **Required for Bitbucket Data Center in conjunction with the `secret`. Not used for any other providers.** The text of the SSH public key associated with your Bitbucket Data Center application link. | | `data.attributes.organization-scoped` | boolean | | Whether or not the OAuth client is scoped to all projects and workspaces in the organization. Defaults to `true`. | `data.relationships.projects.data[]` | array\[object] | `[]` | A list of resource identifier objects that defines which projects are associated with the OAuth client. If `data.attributes.organization-scoped` is set to `false`, the OAuth client is only available to this list of projects. Each object in this list must contain a project `id` and use the `"projects"` type. For example, `{ "id": "prj-AwfuCJTkdai4xj9w", "type": "projects" }`. | | `data.relationships.agent-pool.data` | object | `{}` | The Agent Pool associated to the VCS connection. This pool will be responsible for forwarding VCS Provider API calls and cloning VCS repositories. | ### Sample Payload ```json { "data": { "type": "oauth-clients", "attributes": { "service-provider": "github", "http-url": "https://github.com", "api-url": "https://api.github.com", "oauth-token-string": "4306823352f0009d0ed81f1b654ac17a", "organization-scoped": false }, "relationships": { "projects": { "data": [ { "id": "prj-AwfuCJTkdai4xj9w", "type": "projects" } ] }, "agent-pool": { "data": { "id": "apool-VsmjEMcYkShrckzzz", "type": "agent-pools" } } } } } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/organizations/my-organization/oauth-clients ``` ### Sample Response ```json { "data": { "id": "oc-XKFwG6ggfA9n7t1K", "type": "oauth-clients", "attributes": { "created-at": "2018-04-16T20:42:53.771Z", "callback-url": "https://app.terraform.io/auth/35936d44-842c-4ddd-b4d4-7c741383dc3a/callback", "connect-path": "/auth/35936d44-842c-4ddd-b4d4-7c741383dc3a?organization_id=1", "service-provider": "github", "service-provider-display-name": "GitHub", "name": null, "http-url": "https://github.com", "api-url": "https://api.github.com", "key": null, "rsa-public-key": null, "organization-scoped": false }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" }, "links": { "related": "/api/v2/organizations/my-organization" } }, "projects": { "data": [ { "id": "prj-AwfuCJTkdai4xj9w", "type": "projects" } ] }, "oauth-tokens": { "data": [], "links": { "related": "/api/v2/oauth-tokens/ot-KaeqH4cy72VPXFQT" } }, "agent-pool": { "data": { "id": "apool-VsmjEMcYkShrckzzz", "type": "agent-pools" } } } } } ``` ## Update an OAuth Client `PATCH /oauth-clients/:id` | Parameter | Description | | --------- | ------------------------------------- | | `:id` | The ID of the OAuth Client to update. | Use caution when changing attributes with this endpoint; editing an OAuth client that workspaces are currently using can have unexpected effects. | Status | Response | Reason | | ------- | ----------------------------------------------- | -------------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "oauth-clients"`) | The request was successful | | [404][] | [JSON API error object][] | OAuth Client not found or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (missing attributes, wrong types, etc.) | ### Request Body This PATCH endpoint requires a JSON object with the following properties as a request payload. | Key path | Type | Default | Description | | -------------------------------- | ------ | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data.type` | string | | Must be `"oauth-clients"`. | | `data.attributes.name` | string | (previous value) | An optional display name for the OAuth Client. If set to `null`, the UI will default to the display name of the VCS provider. | | `data.attributes.key` | string | (previous value) | The OAuth Client key. It can refer to a Consumer Key, Application Key, or another type of client key for the VCS provider. | | `data.attributes.secret` | string | (previous value) | The OAuth client secret. For Bitbucket Data Center, this secret is the text of the SSH private key associated with your Bitbucket Data Center application link. | | `data.attributes.rsa-public-key` | string | (previous value) | **Required for Bitbucket Data Center in conjunction with the `secret`. Not used for any other providers.** The text of the SSH public key associated with your Bitbucket Data Center application link. | | `data.attributes.organization-scoped` | boolean | (previous value) | Whether or not the OAuth client is available to all projects and workspaces in the organization. | | `data.relationships.projects` | array\[object] | (previous value) | A list of resource identifier objects that defines which projects are associated with the OAuth client. If `data.attributes.organization-scoped` is set to `false`, the OAuth client is only available to this list of projects. Each object in this list must contain a project `id` and use the `"projects"` type. For example, `{ "id": "prj-AwfuCJTkdai4xj9w", "type": "projects" }`. Sending an empty array clears all project assignments. | | `data.relationships.agent-pool.data` | object | `{}` | The Agent Pool associated to the VCS connection. This pool will be responsible for forwarding VCS Provider API calls and cloning VCS repositories. | ### Sample Payload ```json { "data": { "id": "oc-XKFwG6ggfA9n7t1K", "type": "oauth-clients", "attributes": { "key": "key", "secret": "secret", "organization-scoped": false }, "relationships": { "projects": { "data": [ { "id": "prj-AwfuCJTkdai4xj9w", "type": "projects" } ] }, "agent-pool": { "data": { "id": "apool-VsmjEMcYkShrckzzz", "type": "agent-pools" } } } } } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request PATCH \ --data @payload.json \ https://app.terraform.io/api/v2/oauth-clients/oc-XKFwG6ggfA9n7t1K ``` ### Sample Response ```json { "data": { "id": "oc-XKFwG6ggfA9n7t1K", "type": "oauth-clients", "attributes": { "created-at": "2018-04-16T20:42:53.771Z", "callback-url": "https://app.terraform.io/auth/35936d44-842c-4ddd-b4d4-7c741383dc3a/callback", "connect-path": "/auth/35936d44-842c-4ddd-b4d4-7c741383dc3a?organization_id=1", "service-provider": "github", "service-provider-display-name": "GitHub", "name": null, "http-url": "https://github.com", "api-url": "https://api.github.com", "key": null, "rsa-public-key": null, "organization-scoped": false }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" }, "links": { "related": "/api/v2/organizations/my-organization" } }, "projects": { "data": [ { "id": "prj-AwfuCJTkdai4xj9w", "type": "projects" } ] }, "oauth-tokens": { "data": [], "links": { "related": "/api/v2/oauth-tokens/ot-KaeqH4cy72VPXFQT" } }, "agent-pool": { "data": { "id": "apool-VsmjEMcYkShrckzzz", "type": "agent-pools" } } } } } ``` ## Destroy an OAuth Client `DELETE /oauth-clients/:id` | Parameter | Description | | --------- | ------------------------------------- | | `:id` | The ID of the OAuth Client to destroy | This endpoint allows you to remove an existing connection between an organization and a VCS provider (GitHub, Bitbucket, or GitLab). **Note:** Removing the OAuth Client will unlink workspaces that use this connection from their repositories, and these workspaces will need to be manually linked to another repository. | Status | Response | Reason | | ------- | ------------------------- | ------------------------------------------------------------------------------ | | [204][] | Empty response | The OAuth Client was successfully destroyed | | [404][] | [JSON API error object][] | Organization or OAuth Client not found, or user unauthorized to perform action | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request DELETE \ https://app.terraform.io/api/v2/oauth-clients/oc-XKFwG6ggfA9n7t1K ``` ## Attach to a project `POST /oauth-clients/:id/relationships/projects` | Parameter | Description | | --------- | -------------------------------------------------------------------------------------------------- | | `:id` | The ID of the OAuth client to attach to a project. Use the [List OAuth Clients](#list-oauth-clients) endpoint to reference your OAuth client IDs. | | Status | Response | Reason | | ------- | ------------------------- | -------------------------------------------------------------------------- | | [204][] | Nothing | The request was successful | | [404][] | [JSON API error object][] | OAuth Client not found or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (one or more projects not found, wrong types, etc.) | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | -------- | -------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data[]` | array\[object] | `[]` | A list of resource identifier objects that defines which projects to attach the OAuth client to. These objects must contain `id` and `type` properties, and the `type` property must be `projects` (e.g. `{ "id": "prj-AwfuCJTkdai4xj9w", "type": "projects" }`). | ### Sample Payload ```json { "data": [ { "id": "prj-AwfuCJTkdai4xj9w", "type": "projects" }, { "id": "prj-2HRvNs49EWPjDqT1", "type": "projects" } ] } ``` ### Sample Request ```shell curl \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/oauth-clients/oc-XKFwG6ggfA9n7t1K/relationships/projects ``` ## Detach an OAuth Client from projects `DELETE /oauth-clients/:id/relationships/projects` | Parameter | Description | | --------- | -------------------------------------------------------------------------------------------------- | | `:id` | The ID of the oauth client you want to detach from the specified projects. Use the "List OAuth Clients" endpoint to find IDs. | | Status | Response | Reason | | ------- | ------------------------- | -------------------------------------------------------------------------- | | [204][] | Nothing | The request was successful | | [404][] | [JSON API error object][] | OAuth Client not found or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (one or more projects not found, wrong types, etc.) | ### Request Body This DELETE endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | -------- | -------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data[]` | array\[object] | `[]` | A list of resource identifier objects that defines which projects are associated with the OAuth client. If `data.attributes.organization-scoped` is set to `false`, the OAuth client is only available to this list of projects. Each object in this list must contain a project `id` and use the `"projects"` type. For example, `{ "id": "prj-AwfuCJTkdai4xj9w", "type": "projects" }`. | ### Sample Payload ```json { "data": [ { "id": "prj-AwfuCJTkdai4xj9w", "type": "projects" }, { "id": "prj-2HRvNs49EWPjDqT1", "type": "projects" } ] } ``` ### Sample Request ```shell curl \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/vnd.api+json" \ --request DELETE \ --data @payload.json \ https://app.terraform.io/api/v2/oauth-clients/oc-XKFwG6ggfA9n7t1K/relationships/projects ``` ### Available Related Resources The GET endpoints above can optionally return related resources, if requested with [the `include` query parameter](/terraform/cloud-docs/api-docs#inclusion-of-related-resources). The following resource types are available: | Resource Name | Description | | -------------- | ---------------------------------------- | | `oauth_tokens` | The OAuth tokens managed by this client | | `projects` | The projects scoped to this client |
terraform
page title OAuth Clients API Docs HCP Terraform description Use the oauth clients endpoint to manage OAuth connections between your organization and a VCS provider List show create update and destroy clients using the HTTP API Attach and detach OAuth clients to projects 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects OAuth Clients API An OAuth client represents the connection between an organization and a VCS provider By default you can globally access an OAuth client throughout the organization or you can have scope access to one or more projects terraform cloud docs projects manage List OAuth Clients GET organizations organization name oauth clients Parameter Description organization name The name of the organization This endpoint allows you to list VCS connections between an organization and a VCS provider GitHub Bitbucket or GitLab for use when creating or setting up workspaces Status Response Reason 200 JSON API document type oauth clients Success 404 JSON API error object Organization not found Query Parameters This endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters Remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs If neither pagination query parameters are provided the endpoint will not be paginated and will return all results Parameter Description page number Optional If omitted the endpoint will return the first page page size Optional If omitted the endpoint will return 20 oauth clients per page Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 organizations my organization oauth clients Sample Response json data id oc XKFwG6ggfA9n7t1K type oauth clients attributes created at 2018 04 16T20 42 53 771Z callback url https app terraform io auth 35936d44 842c 4ddd b4d4 7c741383dc3a callback connect path auth 35936d44 842c 4ddd b4d4 7c741383dc3a organization id 1 service provider github service provider display name GitHub name null http url https github com api url https api github com key null rsa public key null organization scoped false relationships organization data id my organization type organizations links related api v2 organizations my organization projects data id prj AwfuCJTkdai4xj9w type projects oauth tokens data links related api v2 oauth tokens ot KaeqH4cy72VPXFQT agent pool data id apool VsmjEMcYkShrckpK type agent pools links related api v2 agent pools apool VsmjEMcYkShrckpK Show an OAuth Client GET oauth clients id Parameter Description id The ID of the OAuth Client to show Status Response Reason 200 JSON API document type oauth clients Success 404 JSON API error object OAuth Client not found or user unauthorized to perform action Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 oauth clients oc XKFwG6ggfA9n7t1K Sample Response json data id oc XKFwG6ggfA9n7t1K type oauth clients attributes created at 2018 04 16T20 42 53 771Z callback url https app terraform io auth 35936d44 842c 4ddd b4d4 7c741383dc3a callback connect path auth 35936d44 842c 4ddd b4d4 7c741383dc3a organization id 1 service provider github service provider display name GitHub name null http url https github com api url https api github com key null rsa public key null organization scoped false relationships organization data id my organization type organizations links related api v2 organizations my organization projects data id prj AwfuCJTkdai4xj9w type projects oauth tokens data links related api v2 oauth tokens ot KaeqH4cy72VPXFQT agent pool data id apool VsmjEMcYkShrckpK type agent pools links related api v2 agent pools apool VsmjEMcYkShrckpK Create an OAuth Client POST organizations organization name oauth clients Parameter Description organization name The name of the organization that will be connected to the VCS provider The organization must already exist in the system and the user must have permission to manage VCS settings More about permissions terraform cloud docs users teams organizations permissions permissions citation intentionally unused keep for maintainers This endpoint allows you to create a VCS connection between an organization and a VCS provider GitHub or GitLab for use when creating or setting up workspaces By using this API endpoint you can provide a pre generated OAuth token string instead of going through the process of creating a GitHub or GitLab OAuth Application To learn how to generate one of these token strings for your VCS provider you can read the following documentation GitHub and GitHub Enterprise https docs github com en authentication keeping your account and data secure creating a personal access token GitLab GitLab Community Edition and GitLab Enterprise Edition https docs gitlab com ee user profile personal access tokens html create a personal access token Azure DevOps Server https docs microsoft com en us azure devops organizations accounts use personal access tokens to authenticate view azure devops 2019 tabs preview page Status Response Reason 201 JSON API document type oauth clients OAuth Client successfully created 404 JSON API error object Organization not found or user unauthorized to perform action 422 JSON API error object Malformed request body missing attributes wrong types etc Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string Must be oauth clients data attributes service provider string The VCS provider being connected with Valid options are github github enterprise gitlab hosted gitlab community edition gitlab enterprise edition or ado server data attributes name string null An optional display name for the OAuth Client If left null the UI will default to the display name of the VCS provider data attributes key string The OAuth Client key It can refer to a Consumer Key Application Key or another type of client key for the VCS provider data attributes http url string The homepage of your VCS provider e g https github com or https ghe example com or https gitlab com data attributes api url string The base URL as per your VCS provider s API documentation e g https api github com https ghe example com api v3 or https gitlab com api v4 data attributes oauth token string string The token string you were given by your VCS provider data attributes private key string Required for Azure DevOps Server Not used for any other providers The text of the SSH private key associated with your Azure DevOps Server account data attributes secret string The OAuth client secret For Bitbucket Data Center the secret is the text of the SSH private key associated with your Bitbucket Data Center application link data attributes rsa public key string Required for Bitbucket Data Center in conjunction with the secret Not used for any other providers The text of the SSH public key associated with your Bitbucket Data Center application link data attributes organization scoped boolean Whether or not the OAuth client is scoped to all projects and workspaces in the organization Defaults to true data relationships projects data array object A list of resource identifier objects that defines which projects are associated with the OAuth client If data attributes organization scoped is set to false the OAuth client is only available to this list of projects Each object in this list must contain a project id and use the projects type For example id prj AwfuCJTkdai4xj9w type projects data relationships agent pool data object The Agent Pool associated to the VCS connection This pool will be responsible for forwarding VCS Provider API calls and cloning VCS repositories Sample Payload json data type oauth clients attributes service provider github http url https github com api url https api github com oauth token string 4306823352f0009d0ed81f1b654ac17a organization scoped false relationships projects data id prj AwfuCJTkdai4xj9w type projects agent pool data id apool VsmjEMcYkShrckzzz type agent pools Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 organizations my organization oauth clients Sample Response json data id oc XKFwG6ggfA9n7t1K type oauth clients attributes created at 2018 04 16T20 42 53 771Z callback url https app terraform io auth 35936d44 842c 4ddd b4d4 7c741383dc3a callback connect path auth 35936d44 842c 4ddd b4d4 7c741383dc3a organization id 1 service provider github service provider display name GitHub name null http url https github com api url https api github com key null rsa public key null organization scoped false relationships organization data id my organization type organizations links related api v2 organizations my organization projects data id prj AwfuCJTkdai4xj9w type projects oauth tokens data links related api v2 oauth tokens ot KaeqH4cy72VPXFQT agent pool data id apool VsmjEMcYkShrckzzz type agent pools Update an OAuth Client PATCH oauth clients id Parameter Description id The ID of the OAuth Client to update Use caution when changing attributes with this endpoint editing an OAuth client that workspaces are currently using can have unexpected effects Status Response Reason 200 JSON API document type oauth clients The request was successful 404 JSON API error object OAuth Client not found or user unauthorized to perform action 422 JSON API error object Malformed request body missing attributes wrong types etc Request Body This PATCH endpoint requires a JSON object with the following properties as a request payload Key path Type Default Description data type string Must be oauth clients data attributes name string previous value An optional display name for the OAuth Client If set to null the UI will default to the display name of the VCS provider data attributes key string previous value The OAuth Client key It can refer to a Consumer Key Application Key or another type of client key for the VCS provider data attributes secret string previous value The OAuth client secret For Bitbucket Data Center this secret is the text of the SSH private key associated with your Bitbucket Data Center application link data attributes rsa public key string previous value Required for Bitbucket Data Center in conjunction with the secret Not used for any other providers The text of the SSH public key associated with your Bitbucket Data Center application link data attributes organization scoped boolean previous value Whether or not the OAuth client is available to all projects and workspaces in the organization data relationships projects array object previous value A list of resource identifier objects that defines which projects are associated with the OAuth client If data attributes organization scoped is set to false the OAuth client is only available to this list of projects Each object in this list must contain a project id and use the projects type For example id prj AwfuCJTkdai4xj9w type projects Sending an empty array clears all project assignments data relationships agent pool data object The Agent Pool associated to the VCS connection This pool will be responsible for forwarding VCS Provider API calls and cloning VCS repositories Sample Payload json data id oc XKFwG6ggfA9n7t1K type oauth clients attributes key key secret secret organization scoped false relationships projects data id prj AwfuCJTkdai4xj9w type projects agent pool data id apool VsmjEMcYkShrckzzz type agent pools Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request PATCH data payload json https app terraform io api v2 oauth clients oc XKFwG6ggfA9n7t1K Sample Response json data id oc XKFwG6ggfA9n7t1K type oauth clients attributes created at 2018 04 16T20 42 53 771Z callback url https app terraform io auth 35936d44 842c 4ddd b4d4 7c741383dc3a callback connect path auth 35936d44 842c 4ddd b4d4 7c741383dc3a organization id 1 service provider github service provider display name GitHub name null http url https github com api url https api github com key null rsa public key null organization scoped false relationships organization data id my organization type organizations links related api v2 organizations my organization projects data id prj AwfuCJTkdai4xj9w type projects oauth tokens data links related api v2 oauth tokens ot KaeqH4cy72VPXFQT agent pool data id apool VsmjEMcYkShrckzzz type agent pools Destroy an OAuth Client DELETE oauth clients id Parameter Description id The ID of the OAuth Client to destroy This endpoint allows you to remove an existing connection between an organization and a VCS provider GitHub Bitbucket or GitLab Note Removing the OAuth Client will unlink workspaces that use this connection from their repositories and these workspaces will need to be manually linked to another repository Status Response Reason 204 Empty response The OAuth Client was successfully destroyed 404 JSON API error object Organization or OAuth Client not found or user unauthorized to perform action Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request DELETE https app terraform io api v2 oauth clients oc XKFwG6ggfA9n7t1K Attach to a project POST oauth clients id relationships projects Parameter Description id The ID of the OAuth client to attach to a project Use the List OAuth Clients list oauth clients endpoint to reference your OAuth client IDs Status Response Reason 204 Nothing The request was successful 404 JSON API error object OAuth Client not found or user unauthorized to perform action 422 JSON API error object Malformed request body one or more projects not found wrong types etc Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data array object A list of resource identifier objects that defines which projects to attach the OAuth client to These objects must contain id and type properties and the type property must be projects e g id prj AwfuCJTkdai4xj9w type projects Sample Payload json data id prj AwfuCJTkdai4xj9w type projects id prj 2HRvNs49EWPjDqT1 type projects Sample Request shell curl H Authorization Bearer TOKEN H Content Type application vnd api json request POST data payload json https app terraform io api v2 oauth clients oc XKFwG6ggfA9n7t1K relationships projects Detach an OAuth Client from projects DELETE oauth clients id relationships projects Parameter Description id The ID of the oauth client you want to detach from the specified projects Use the List OAuth Clients endpoint to find IDs Status Response Reason 204 Nothing The request was successful 404 JSON API error object OAuth Client not found or user unauthorized to perform action 422 JSON API error object Malformed request body one or more projects not found wrong types etc Request Body This DELETE endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data array object A list of resource identifier objects that defines which projects are associated with the OAuth client If data attributes organization scoped is set to false the OAuth client is only available to this list of projects Each object in this list must contain a project id and use the projects type For example id prj AwfuCJTkdai4xj9w type projects Sample Payload json data id prj AwfuCJTkdai4xj9w type projects id prj 2HRvNs49EWPjDqT1 type projects Sample Request shell curl H Authorization Bearer TOKEN H Content Type application vnd api json request DELETE data payload json https app terraform io api v2 oauth clients oc XKFwG6ggfA9n7t1K relationships projects Available Related Resources The GET endpoints above can optionally return related resources if requested with the include query parameter terraform cloud docs api docs inclusion of related resources The following resource types are available Resource Name Description oauth tokens The OAuth tokens managed by this client projects The projects scoped to this client
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 page title OAuth Tokens API Docs HCP Terraform 201 https developer mozilla org en US docs Web HTTP Status 201 Use the oauth tokens endpoint to manage the OAuth tokens used to connect a workspace to a VCS provider List show update and destroy tokens using the HTTP API
--- page_title: OAuth Tokens - API Docs - HCP Terraform description: >- Use the `/oauth-tokens` endpoint to manage the OAuth tokens used to connect a workspace to a VCS provider. List, show, update, and destroy tokens using the HTTP API. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # OAuth Tokens The `oauth-token` object represents a VCS configuration which includes the OAuth connection and the associated OAuth token. This object is used when creating a workspace to identify which VCS connection to use. ## List OAuth Tokens List all the OAuth Tokens for a given OAuth Client `GET /oauth-clients/:oauth_client_id/oauth-tokens` | Parameter | Description | | ------------------ | -------------------------- | | `:oauth_client_id` | The ID of the OAuth Client | | Status | Response | Reason | | ------- | ---------------------------------------------- | -------------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "oauth-tokens"`) | Success | | [404][] | [JSON API error object][] | OAuth Client not found, or user unauthorized to perform action | ### Query Parameters This endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. If neither pagination query parameters are provided, the endpoint will not be paginated and will return all results. | Parameter | Description | | -------------- | ---------------------------------------------------------------------------- | | `page[number]` | **Optional.** If omitted, the endpoint will return the first page. | | `page[size]` | **Optional.** If omitted, the endpoint will return 20 oauth tokens per page. | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ https://app.terraform.io/api/v2/oauth-clients/oc-GhHqb5rkeK19mLB8/oauth-tokens ``` ### Sample Response ```json { "data": [ { "id": "ot-hmAyP66qk2AMVdbJ", "type": "oauth-tokens", "attributes": { "created-at":"2017-11-02T06:37:49.284Z", "service-provider-user":"skierkowski", "has-ssh-key": false }, "relationships": { "oauth-client": { "data": { "id": "oc-GhHqb5rkeK19mLB8", "type": "oauth-clients" }, "links": { "related": "/api/v2/oauth-clients/oc-GhHqb5rkeK19mLB8" } } }, "links": { "self": "/api/v2/oauth-tokens/ot-hmAyP66qk2AMVdbJ" } } ] } ``` ## Show an OAuth Token `GET /oauth-tokens/:id` | Parameter | Description | | --------- | --------------------------------- | | `:id` | The ID of the OAuth token to show | | Status | Response | Reason | | ------- | ---------------------------------------------- | ------------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "oauth-tokens"`) | Success | | [404][] | [JSON API error object][] | OAuth Token not found, or user unauthorized to perform action | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/oauth-tokens/ot-29t7xkUKiNC2XasL ``` ### Sample Response ```json { "data": { "id": "ot-29t7xkUKiNC2XasL", "type": "oauth-tokens", "attributes": { "created-at": "2018-08-29T14:07:22.144Z", "service-provider-user": "EM26Jj0ikRsIFFh3fE5C", "has-ssh-key": false }, "relationships": { "oauth-client": { "data": { "id": "oc-WMipGbuW8q7xCRmJ", "type": "oauth-clients" }, "links": { "related": "/api/v2/oauth-clients/oc-WMipGbuW8q7xCRmJ" } } }, "links": { "self": "/api/v2/oauth-tokens/ot-29t7xkUKiNC2XasL" } } } ``` ## Update an OAuth Token `PATCH /oauth-tokens/:id` | Parameter | Description | | --------- | ----------------------------------- | | `:id` | The ID of the OAuth token to update | | Status | Response | Reason | | ------- | ---------------------------------------------- | -------------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "oauth-tokens"`) | OAuth Token successfully updated | | [404][] | [JSON API error object][] | OAuth Token not found or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (missing attributes, wrong types, etc.) | ### Request Body This PATCH endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | ------------------------- | ------ | ------- | ------------------------- | | `data.type` | string | | Must be `"oauth-tokens"`. | | `data.attributes.ssh-key` | string | | **Optional.** The SSH key | ### Sample Payload ```json { "data": { "id": "ot-29t7xkUKiNC2XasL", "type": "oauth-tokens", "attributes": { "ssh-key": "..." } } } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request PATCH \ --data @payload.json \ https://app.terraform.io/api/v2/oauth-tokens/ot-29t7xkUKiNC2XasL ``` ### Sample Response ```json { "data": { "id": "ot-29t7xkUKiNC2XasL", "type": "oauth-tokens", "attributes": { "created-at": "2018-08-29T14:07:22.144Z", "service-provider-user": "EM26Jj0ikRsIFFh3fE5C", "has-ssh-key": false }, "relationships": { "oauth-client": { "data": { "id": "oc-WMipGbuW8q7xCRmJ", "type": "oauth-clients" }, "links": { "related": "/api/v2/oauth-clients/oc-WMipGbuW8q7xCRmJ" } } }, "links": { "self": "/api/v2/oauth-tokens/ot-29t7xkUKiNC2XasL" } } } ``` ## Destroy an OAuth Token `DELETE /oauth-tokens/:id` | Parameter | Description | | --------- | ------------------------------------ | | `:id` | The ID of the OAuth Token to destroy | | Status | Response | Reason | | ------- | ------------------------- | ------------------------------------------------------------- | | [204][] | Empty response | The OAuth Token was successfully destroyed | | [404][] | [JSON API error object][] | OAuth Token not found, or user unauthorized to perform action | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request DELETE \ https://app.terraform.io/api/v2/oauth-tokens/ot-29t7xkUKiNC2XasL ```
terraform
page title OAuth Tokens API Docs HCP Terraform description Use the oauth tokens endpoint to manage the OAuth tokens used to connect a workspace to a VCS provider List show update and destroy tokens using the HTTP API 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects OAuth Tokens The oauth token object represents a VCS configuration which includes the OAuth connection and the associated OAuth token This object is used when creating a workspace to identify which VCS connection to use List OAuth Tokens List all the OAuth Tokens for a given OAuth Client GET oauth clients oauth client id oauth tokens Parameter Description oauth client id The ID of the OAuth Client Status Response Reason 200 JSON API document type oauth tokens Success 404 JSON API error object OAuth Client not found or user unauthorized to perform action Query Parameters This endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters Remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs If neither pagination query parameters are provided the endpoint will not be paginated and will return all results Parameter Description page number Optional If omitted the endpoint will return the first page page size Optional If omitted the endpoint will return 20 oauth tokens per page Sample Request shell curl header Authorization Bearer TOKEN https app terraform io api v2 oauth clients oc GhHqb5rkeK19mLB8 oauth tokens Sample Response json data id ot hmAyP66qk2AMVdbJ type oauth tokens attributes created at 2017 11 02T06 37 49 284Z service provider user skierkowski has ssh key false relationships oauth client data id oc GhHqb5rkeK19mLB8 type oauth clients links related api v2 oauth clients oc GhHqb5rkeK19mLB8 links self api v2 oauth tokens ot hmAyP66qk2AMVdbJ Show an OAuth Token GET oauth tokens id Parameter Description id The ID of the OAuth token to show Status Response Reason 200 JSON API document type oauth tokens Success 404 JSON API error object OAuth Token not found or user unauthorized to perform action Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 oauth tokens ot 29t7xkUKiNC2XasL Sample Response json data id ot 29t7xkUKiNC2XasL type oauth tokens attributes created at 2018 08 29T14 07 22 144Z service provider user EM26Jj0ikRsIFFh3fE5C has ssh key false relationships oauth client data id oc WMipGbuW8q7xCRmJ type oauth clients links related api v2 oauth clients oc WMipGbuW8q7xCRmJ links self api v2 oauth tokens ot 29t7xkUKiNC2XasL Update an OAuth Token PATCH oauth tokens id Parameter Description id The ID of the OAuth token to update Status Response Reason 200 JSON API document type oauth tokens OAuth Token successfully updated 404 JSON API error object OAuth Token not found or user unauthorized to perform action 422 JSON API error object Malformed request body missing attributes wrong types etc Request Body This PATCH endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string Must be oauth tokens data attributes ssh key string Optional The SSH key Sample Payload json data id ot 29t7xkUKiNC2XasL type oauth tokens attributes ssh key Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request PATCH data payload json https app terraform io api v2 oauth tokens ot 29t7xkUKiNC2XasL Sample Response json data id ot 29t7xkUKiNC2XasL type oauth tokens attributes created at 2018 08 29T14 07 22 144Z service provider user EM26Jj0ikRsIFFh3fE5C has ssh key false relationships oauth client data id oc WMipGbuW8q7xCRmJ type oauth clients links related api v2 oauth clients oc WMipGbuW8q7xCRmJ links self api v2 oauth tokens ot 29t7xkUKiNC2XasL Destroy an OAuth Token DELETE oauth tokens id Parameter Description id The ID of the OAuth Token to destroy Status Response Reason 204 Empty response The OAuth Token was successfully destroyed 404 JSON API error object OAuth Token not found or user unauthorized to perform action Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request DELETE https app terraform io api v2 oauth tokens ot 29t7xkUKiNC2XasL
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 Use the authentication tokens endpoint to manage agent tokens List show create and destroy tokens using the HTTP API 201 https developer mozilla org en US docs Web HTTP Status 201 page title Agent Tokens API Docs HCP Terraform
--- page_title: Agent Tokens - API Docs - HCP Terraform description: >- Use the `/authentication-tokens` endpoint to manage agent tokens. List, show, create, and destroy tokens using the HTTP API. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # Agent Tokens API <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/agents.mdx' <!-- END: TFC:only name:pnp-callout --> ## List Agent Tokens `GET /agent-pools/:agent_pool_id/authentication-tokens` | Parameter | Description | | ---------------- | ------------------------- | | `:agent_pool_id` | The ID of the Agent Pool. | The objects returned by this endpoint only contain metadata, and do not include the secret text of any authentication tokens. A token is only shown upon creation, and cannot be recovered later. | Status | Response | Reason | | ------- | ------------------------------------------------------- | ------------------------------------------------------------ | | [200][] | [JSON API document][] (`type: "authentication-tokens"`) | Success | | [404][] | [JSON API error object][] | Agent Pool not found, or user unauthorized to perform action | ### Query Parameters This endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. | Parameter | Description | | -------------- | ---------------------------------------------------------------------- | | `page[number]` | **Optional.** If omitted, the endpoint will return the first page. | | `page[size]` | **Optional.** If omitted, the endpoint will return 20 tokens per page. | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/agent-pools/apool-MCf6kkxu5FyHbqhd/authentication-tokens ``` ### Sample Response ```json { "data": [ { "id": "at-bonpPzYqv2bGD7vr", "type": "authentication-tokens", "attributes": { "created-at": "2020-08-07T19:38:20.868Z", "last-used-at": "2020-08-07T19:40:55.139Z", "description": "asdfsdf", "token": null }, "relationships": { "created-by": { "data": { "id": "user-Nxv6svuhVrTW7eb1", "type": "users" } } } } ], "links": { "self": "https://app.terraform.io/api/v2/agent-pools/apool-MCf6kkxu5FyHbqhd/authentication-tokens?page%5Bnumber%5D=1&page%5Bsize%5D=20", "first": "https://app.terraform.io/api/v2/agent-pools/apool-MCf6kkxu5FyHbqhd/authentication-tokens?page%5Bnumber%5D=1&page%5Bsize%5D=20", "prev": null, "next": null, "last": "https://app.terraform.io/api/v2/agent-pools/apool-MCf6kkxu5FyHbqhd/authentication-tokens?page%5Bnumber%5D=1&page%5Bsize%5D=20" }, "meta": { "pagination": { "current-page": 1, "prev-page": null, "next-page": null, "total-pages": 1, "total-count": 1 } } } ``` ## Show an Agent Token `GET /authentication-tokens/:id` | Parameter | Description | | --------- | --------------------------------- | | `:id` | The ID of the Agent Token to show | | Status | Response | Reason | | ------- | ------------------------------------------------------- | ------------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "authentication-tokens"`) | Success | | [404][] | [JSON API error object][] | Agent Token not found, or user unauthorized to perform action | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/authentication-tokens/at-bonpPzYqv2bGD7vr ``` ### Sample Response ```json { "data": { "id": "at-bonpPzYqv2bGD7vr", "type": "authentication-tokens", "attributes": { "created-at": "2020-08-07T19:38:20.868Z", "last-used-at": "2020-08-07T19:40:55.139Z", "description": "test token", "token": null }, "relationships": { "created-by": { "data": { "id": "user-Nxv6svuhVrTW7eb1", "type": "users" } } } } } ``` ## Create an Agent Token `POST /agent-pools/:agent_pool_id/authentication-tokens` | Parameter | Description | | ---------------- | ------------------------ | | `:agent_pool_id` | The ID of the Agent Pool | This endpoint returns the secret text of the created authentication token. A token is only shown upon creation, and cannot be recovered later. | Status | Response | Reason | | ------- | ------------------------------------------------------- | -------------------------------------------------------------- | | [201][] | [JSON API document][] (`type: "authentication-tokens"`) | The request was successful | | [404][] | [JSON API error object][] | Agent Pool not found or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (missing attributes, wrong types, etc.) | | [500][] | [JSON API error object][] | Failure during Agent Token creation | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | ----------------------------- | ------ | ------- | ------------------------------------ | | `data.type` | string | | Must be `"authentication-tokens"`. | | `data.attributes.description` | string | | The description for the Agent Token. | ### Sample Payload ```json { "data": { "type": "authentication-tokens", "attributes": { "description":"api" } } } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/agent-pools/apool-xkuMi7x4LsEnBUdY/authentication-tokens ``` ### Sample Response ```json { "data": { "id": "at-2rG2oYU9JEvfaqji", "type": "authentication-tokens", "attributes": { "created-at": "2020-08-10T22:29:21.907Z", "last-used-at": null, "description": "api", "token": "eHub7TsW7fz7LQ.atlasv1.cHGFcvf2VxVfUH4PZ7UNdaGB6SjyKWs5phdZ371zkI2KniZs2qKgrAcazhlsiy02awk" }, "relationships": { "created-by": { "data": { "id": "user-Nxv6svuhVrTW7eb1", "type": "users" } } } } } ``` ## Destroy an Agent Token `DELETE /api/v2/authentication-tokens/:id` | Parameter | Description | | --------- | ------------------------------------- | | `:id` | The ID of the Agent Token to destroy. | | Status | Response | Reason | | ------- | ------------------------- | ------------------------------------------------------------- | | [204][] | Empty response | The Agent Token was successfully destroyed | | [404][] | [JSON API error object][] | Agent Token not found, or user unauthorized to perform action | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request DELETE \ https://app.terraform.io/api/v2/authentication-tokens/at-6yEmxNAhaoQLH1Da ```
terraform
page title Agent Tokens API Docs HCP Terraform description Use the authentication tokens endpoint to manage agent tokens List show create and destroy tokens using the HTTP API 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects Agent Tokens API BEGIN TFC only name pnp callout include tfc package callouts agents mdx END TFC only name pnp callout List Agent Tokens GET agent pools agent pool id authentication tokens Parameter Description agent pool id The ID of the Agent Pool The objects returned by this endpoint only contain metadata and do not include the secret text of any authentication tokens A token is only shown upon creation and cannot be recovered later Status Response Reason 200 JSON API document type authentication tokens Success 404 JSON API error object Agent Pool not found or user unauthorized to perform action Query Parameters This endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters Remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs Parameter Description page number Optional If omitted the endpoint will return the first page page size Optional If omitted the endpoint will return 20 tokens per page Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 agent pools apool MCf6kkxu5FyHbqhd authentication tokens Sample Response json data id at bonpPzYqv2bGD7vr type authentication tokens attributes created at 2020 08 07T19 38 20 868Z last used at 2020 08 07T19 40 55 139Z description asdfsdf token null relationships created by data id user Nxv6svuhVrTW7eb1 type users links self https app terraform io api v2 agent pools apool MCf6kkxu5FyHbqhd authentication tokens page 5Bnumber 5D 1 page 5Bsize 5D 20 first https app terraform io api v2 agent pools apool MCf6kkxu5FyHbqhd authentication tokens page 5Bnumber 5D 1 page 5Bsize 5D 20 prev null next null last https app terraform io api v2 agent pools apool MCf6kkxu5FyHbqhd authentication tokens page 5Bnumber 5D 1 page 5Bsize 5D 20 meta pagination current page 1 prev page null next page null total pages 1 total count 1 Show an Agent Token GET authentication tokens id Parameter Description id The ID of the Agent Token to show Status Response Reason 200 JSON API document type authentication tokens Success 404 JSON API error object Agent Token not found or user unauthorized to perform action Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 authentication tokens at bonpPzYqv2bGD7vr Sample Response json data id at bonpPzYqv2bGD7vr type authentication tokens attributes created at 2020 08 07T19 38 20 868Z last used at 2020 08 07T19 40 55 139Z description test token token null relationships created by data id user Nxv6svuhVrTW7eb1 type users Create an Agent Token POST agent pools agent pool id authentication tokens Parameter Description agent pool id The ID of the Agent Pool This endpoint returns the secret text of the created authentication token A token is only shown upon creation and cannot be recovered later Status Response Reason 201 JSON API document type authentication tokens The request was successful 404 JSON API error object Agent Pool not found or user unauthorized to perform action 422 JSON API error object Malformed request body missing attributes wrong types etc 500 JSON API error object Failure during Agent Token creation Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string Must be authentication tokens data attributes description string The description for the Agent Token Sample Payload json data type authentication tokens attributes description api Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 agent pools apool xkuMi7x4LsEnBUdY authentication tokens Sample Response json data id at 2rG2oYU9JEvfaqji type authentication tokens attributes created at 2020 08 10T22 29 21 907Z last used at null description api token eHub7TsW7fz7LQ atlasv1 cHGFcvf2VxVfUH4PZ7UNdaGB6SjyKWs5phdZ371zkI2KniZs2qKgrAcazhlsiy02awk relationships created by data id user Nxv6svuhVrTW7eb1 type users Destroy an Agent Token DELETE api v2 authentication tokens id Parameter Description id The ID of the Agent Token to destroy Status Response Reason 204 Empty response The Agent Token was successfully destroyed 404 JSON API error object Agent Token not found or user unauthorized to perform action Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request DELETE https app terraform io api v2 authentication tokens at 6yEmxNAhaoQLH1Da
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 page title Account API Docs HCP Terraform Use the account endpoint to manage the current user Get user details update account info and change the user password with the HTTP API
--- page_title: Account - API Docs - HCP Terraform description: >- Use the `/account` endpoint to manage the current user. Get user details, update account info, and change the user password with the HTTP API. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # Account API Account represents the current user interacting with Terraform. It returns the same type of object as the [Users](/terraform/cloud-docs/api-docs/users) API, but also includes an email address, which is hidden when viewing info about other users. For internal reasons, HCP Terraform associates team and organization tokens with a synthetic user account called _service user_. HCP Terraform returns the associated service user for account requests authenticated by a team or organization token. Use the `authenticated-resource` relationship to access the underlying team or organization associated with a token. For user tokens, you can use the user, itself. ## Get your account details `GET /account/details` | Status | Response | Reason | | ------- | --------------------------------------- | -------------------------- | | [200][] | [JSON API document][] (`type: "users"`) | The request was successful | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/account/details ``` ### Sample Response ```json { "data": { "id": "user-V3R563qtJNcExAkN", "type": "users", "attributes": { "username": "admin", "is-service-account": false, "auth-method": "tfc", "avatar-url": "https://www.gravatar.com/avatar/9babb00091b97b9ce9538c45807fd35f?s=100&d=mm", "v2-only": false, "is-site-admin": true, "is-sso-login": false, "email": "[email protected]", "unconfirmed-email": null, "permissions": { "can-create-organizations": true, "can-change-email": true, "can-change-username": true } }, "relationships": { "authentication-tokens": { "links": { "related": "/api/v2/users/user-V3R563qtJNcExAkN/authentication-tokens" } }, "authenticated-resource": { "data": { "id": "user-V3R563qtJNcExAkN", "type": "users" }, "links": { "related": "/api/v2/users/user-V3R563qtJNcExAkN" } } }, "links": { "self": "/api/v2/users/user-V3R563qtJNcExAkN" } } } ``` ## Update your account info Your username and email address can be updated with this endpoint. `PATCH /account/update` | Status | Response | Reason | | ------- | --------------------------------------- | -------------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "users"`) | Your info was successfully updated | | [401][] | [JSON API error object][] | Unauthorized | | [422][] | [JSON API error object][] | Malformed request body (missing attributes, wrong types, etc.) | ### Request Body This PATCH endpoint requires a JSON object with the following properties as a request payload. | Key path | Type | Default | Description | | -------------------------- | ------ | ------- | --------------------------------------------------------------- | | `data.type` | string | | Must be `"users"` | | `data.attributes.username` | string | | New username | | `data.attributes.email` | string | | New email address (must be confirmed afterwards to take effect) | ### Sample Payload ```json { "data": { "type": "users", "attributes": { "email": "[email protected]", "username": "admin" } } } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request PATCH \ --data @payload.json \ https://app.terraform.io/api/v2/account/update ``` ### Sample Response ```json { "data": { "id": "user-V3R563qtJNcExAkN", "type": "users", "attributes": { "username": "admin", "is-service-account": false, "auth-method": "hcp_username_password", "avatar-url": "https://www.gravatar.com/avatar/9babb00091b97b9ce9538c45807fd35f?s=100&d=mm", "v2-only": false, "is-site-admin": true, "is-sso-login": false, "email": "[email protected]", "unconfirmed-email": null, "permissions": { "can-create-organizations": true, "can-change-email": true, "can-change-username": true } }, "relationships": { "authentication-tokens": { "links": { "related": "/api/v2/users/user-V3R563qtJNcExAkN/authentication-tokens" } } }, "links": { "self": "/api/v2/users/user-V3R563qtJNcExAkN" } } } ``` ## Change your password `PATCH /account/password` | Status | Response | Reason | | ------- | --------------------------------------- | -------------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "users"`) | Your password was successfully changed | | [401][] | [JSON API error object][] | Unauthorized | | [422][] | [JSON API error object][] | Malformed request body (missing attributes, wrong types, etc.) | ### Request Body This PATCH endpoint requires a JSON object with the following properties as a request payload. | Key path | Type | Default | Description | | --------------------------------------- | ------ | ------- | --------------------------- | | `data.type` | string | | Must be `"users"` | | `data.attributes.current_password` | string | | Current password | | `data.attributes.password` | string | | New password (must be at least 10 characters in length) | | `data.attributes.password_confirmation` | string | | New password (confirmation) | ### Sample Payload ```json { "data": { "type": "users", "attributes": { "current_password": "current password e.g. 2:C)e'G4{D\n06:[d1~y", "password": "new password e.g. 34rk492+jgLL0@xhfyisj", "password_confirmation": "new password e.g. 34rk492+jLL0@xhfyisj" } } } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request PATCH \ --data @payload.json \ https://app.terraform.io/api/v2/account/password ``` ### Sample Response ```json { "data": { "id": "user-V3R563qtJNcExAkN", "type": "users", "attributes": { "username": "admin", "is-service-account": false, "auth-method": "hcp_github", "avatar-url": "https://www.gravatar.com/avatar/9babb00091b97b9ce9538c45807fd35f?s=100&d=mm", "v2-only": false, "is-site-admin": true, "is-sso-login": false, "email": "[email protected]", "unconfirmed-email": null, "permissions": { "can-create-organizations": true, "can-change-email": true, "can-change-username": true } }, "relationships": { "authentication-tokens": { "links": { "related": "/api/v2/users/user-V3R563qtJNcExAkN/authentication-tokens" } } }, "links": { "self": "/api/v2/users/user-V3R563qtJNcExAkN" } } } ```
terraform
page title Account API Docs HCP Terraform description Use the account endpoint to manage the current user Get user details update account info and change the user password with the HTTP API 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects Account API Account represents the current user interacting with Terraform It returns the same type of object as the Users terraform cloud docs api docs users API but also includes an email address which is hidden when viewing info about other users For internal reasons HCP Terraform associates team and organization tokens with a synthetic user account called service user HCP Terraform returns the associated service user for account requests authenticated by a team or organization token Use the authenticated resource relationship to access the underlying team or organization associated with a token For user tokens you can use the user itself Get your account details GET account details Status Response Reason 200 JSON API document type users The request was successful Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 account details Sample Response json data id user V3R563qtJNcExAkN type users attributes username admin is service account false auth method tfc avatar url https www gravatar com avatar 9babb00091b97b9ce9538c45807fd35f s 100 d mm v2 only false is site admin true is sso login false email admin hashicorp com unconfirmed email null permissions can create organizations true can change email true can change username true relationships authentication tokens links related api v2 users user V3R563qtJNcExAkN authentication tokens authenticated resource data id user V3R563qtJNcExAkN type users links related api v2 users user V3R563qtJNcExAkN links self api v2 users user V3R563qtJNcExAkN Update your account info Your username and email address can be updated with this endpoint PATCH account update Status Response Reason 200 JSON API document type users Your info was successfully updated 401 JSON API error object Unauthorized 422 JSON API error object Malformed request body missing attributes wrong types etc Request Body This PATCH endpoint requires a JSON object with the following properties as a request payload Key path Type Default Description data type string Must be users data attributes username string New username data attributes email string New email address must be confirmed afterwards to take effect Sample Payload json data type users attributes email admin example com username admin Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request PATCH data payload json https app terraform io api v2 account update Sample Response json data id user V3R563qtJNcExAkN type users attributes username admin is service account false auth method hcp username password avatar url https www gravatar com avatar 9babb00091b97b9ce9538c45807fd35f s 100 d mm v2 only false is site admin true is sso login false email admin hashicorp com unconfirmed email null permissions can create organizations true can change email true can change username true relationships authentication tokens links related api v2 users user V3R563qtJNcExAkN authentication tokens links self api v2 users user V3R563qtJNcExAkN Change your password PATCH account password Status Response Reason 200 JSON API document type users Your password was successfully changed 401 JSON API error object Unauthorized 422 JSON API error object Malformed request body missing attributes wrong types etc Request Body This PATCH endpoint requires a JSON object with the following properties as a request payload Key path Type Default Description data type string Must be users data attributes current password string Current password data attributes password string New password must be at least 10 characters in length data attributes password confirmation string New password confirmation Sample Payload json data type users attributes current password current password e g 2 C e G4 D n06 d1 y password new password e g 34rk492 jgLL0 xhfyisj password confirmation new password e g 34rk492 jLL0 xhfyisj Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request PATCH data payload json https app terraform io api v2 account password Sample Response json data id user V3R563qtJNcExAkN type users attributes username admin is service account false auth method hcp github avatar url https www gravatar com avatar 9babb00091b97b9ce9538c45807fd35f s 100 d mm v2 only false is site admin true is sso login false email admin hashicorp com unconfirmed email null permissions can create organizations true can change email true can change username true relationships authentication tokens links related api v2 users user V3R563qtJNcExAkN authentication tokens links self api v2 users user V3R563qtJNcExAkN
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 Use the github app installations endpoint to view Terraform Cloud GitHub App installations List installations and get details on a specific installation using the HTTP API page title GitHub App Installations API Docs HCP Terraform 201 https developer mozilla org en US docs Web HTTP Status 201
--- page_title: GitHub App Installations - API Docs - HCP Terraform description: >- Use the `/github-app/installations` endpoint to view Terraform Cloud GitHub App installations. List installations and get details on a specific installation using the HTTP API. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # GitHub App Installations API You can create a GitHub App installation using the HCP Terraform UI. Learn how to [create a GitHub App installation](/terraform/cloud-docs/vcs/github-app). ~> **Note:** To use this resource in Terraform Enterprise installations, you must configure the GitHub App in the site admin area. ~> **Note:** You can only use this API if you have already authorized the Terraform Cloud GitHub App. Manage your [GitHub App token](/terraform/cloud-docs/users-teams-organizations/users#github-app-oauth-token) from **Account Settings** > **Tokens**. ## List Installations This endpoint lists GitHub App installations available to the current User. `GET /github-app/installations` ### Query Parameters Queries only return GitHub App Installations that the current user has access to within GitHub. | Parameter | Description | |-----------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------| | `filter[name]` | **Optional.** If present, returns a list of available GitHub App installations that match the GitHub organization or login. | | `filter[installation_id]` | **Optional.** If present, returns a list of available GitHub App installations that match the installation ID within GitHub. (**Not HCP Terraform**) | ### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/github-app/installations ``` ### Sample Response ```json { "data": [ { "id": "ghain-BYrbNeGQ8nAzKouu", "type": "github-app-installations", "attributes": { "name": "octouser", "installation-id": 54810170, "icon-url": "https://avatars.githubusercontent.com/u/29916665?v=4", "installation-type": "User", "installation-url": "https://github.com/settings/installations/54810170" } } ] } ``` ## Show Installation `GET /github-app/installation/:gh_app_installation_id` | Parameter | Description | |---------------------------|--------------------------------| | `:gh_app_installation_id` | The Github App Installation ID | ### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/github-app/installation/ghain-R4xmKTaxnhLFioUq ``` ### Sample Response ```json { "data": { "id": "ghain-R4xmKTaxnhLFioUq", "type": "github-app-installations", "attributes": { "name": "octouser", "installation-id": 54810170, "icon-url": "https://avatars.githubusercontent.com/u/29916665?v=4", "installation-type": "User", "installation-url": "https://github.com/settings/installations/54810170" } } } ```
terraform
page title GitHub App Installations API Docs HCP Terraform description Use the github app installations endpoint to view Terraform Cloud GitHub App installations List installations and get details on a specific installation using the HTTP API 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects GitHub App Installations API You can create a GitHub App installation using the HCP Terraform UI Learn how to create a GitHub App installation terraform cloud docs vcs github app Note To use this resource in Terraform Enterprise installations you must configure the GitHub App in the site admin area Note You can only use this API if you have already authorized the Terraform Cloud GitHub App Manage your GitHub App token terraform cloud docs users teams organizations users github app oauth token from Account Settings Tokens List Installations This endpoint lists GitHub App installations available to the current User GET github app installations Query Parameters Queries only return GitHub App Installations that the current user has access to within GitHub Parameter Description filter name Optional If present returns a list of available GitHub App installations that match the GitHub organization or login filter installation id Optional If present returns a list of available GitHub App installations that match the installation ID within GitHub Not HCP Terraform Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 github app installations Sample Response json data id ghain BYrbNeGQ8nAzKouu type github app installations attributes name octouser installation id 54810170 icon url https avatars githubusercontent com u 29916665 v 4 installation type User installation url https github com settings installations 54810170 Show Installation GET github app installation gh app installation id Parameter Description gh app installation id The Github App Installation ID Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 github app installation ghain R4xmKTaxnhLFioUq Sample Response json data id ghain R4xmKTaxnhLFioUq type github app installations attributes name octouser installation id 54810170 icon url https avatars githubusercontent com u 29916665 v 4 installation type User installation url https github com settings installations 54810170
terraform VCS Events API Note The VCS Events API is still in beta as support is being added for additional VCS providers Currently only GitLab com connections established after December 2020 are supported page title VCS Events API Docs HCP Terraform Use the vcs events endpoint to query VCS related events List changes within your organization using the HTTP API
--- page_title: VCS Events - API Docs - HCP Terraform description: >- Use the `/vcs-events` endpoint to query VCS-related events. List changes within your organization using the HTTP API. --- # VCS Events API -> **Note**: The VCS Events API is still in beta as support is being added for additional VCS providers. Currently only GitLab.com connections established after December 2020 are supported. VCS (version control system) events describe changes within your organization for VCS-related actions. Events are only stored for 10 days. If information about the [OAuth Client](/terraform/cloud-docs/api-docs/oauth-clients) or [OAuth Token](/terraform/cloud-docs/api-docs/oauth-tokens) are available at the time of the event, it will be logged with the event. ## List VCS events This endpoint lists VCS events for an organization `GET /organizations/:organization_name/vcs-events` | Parameter | Description | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `:organization_name` | The name of the organization to list VCS events from. The organization must already exist in the system and the user must have permissions to manage VCS settings. | -> **Note:** Viewing VCS events is restricted to the owners team, teams with the "Manage VCS Settings", and the [organization API token](/terraform/cloud-docs/users-teams-organizations/api-tokens#organization-api-tokens). ([More about permissions](/terraform/cloud-docs/users-teams-organizations/permissions).) ### Query Parameters This endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. | Parameter | Description | | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `page[number]` | **Optional.** If omitted, the endpoint will return the first page. | | `page[size]` | **Optional.** If omitted, the endpoint will return 20 workspaces per page. | | `filter[from]` | **Optional.** Must be RFC3339 formatted and in UTC. If omitted, the endpoint will default to 10 days ago. | | `filter[to]` | **Optional.** Must be RFC3339 formatted and in UTC. If omitted, the endpoint will default to now. | | `filter[oauth_client_external_ids]` | **Optional.** Format as a comma-separated string. If omitted, the endpoint will return all events. | | `filter[levels]` | **Optional.** `info` and `error` are the only accepted values. If omitted, the endpoint will return both info and error events. | | `include` | **Optional.** Allows including related resource data. This endpoint only supports `oauth_client` as a value. Only the `name`, `service-provider`, and `id` will be returned on the OAuth Client object in the `included` block. | ### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/organizations/my-organization/vcs-events?filter%5Bfrom%5D=2021-02-02T14%3A09%3A00Z&filter%5Bto%5D=2021-02-12T14%3A09%3A59Z&filter%5Boauth_client_external_ids%5D=oc-hhTM7WNUUgbXJpkW&filter%5Blevels%5D=info&include=oauth_client ``` ### Sample Response ```json { "data": [ { "id": "ve-DJpbEwZc98ZedHZG", "type": "vcs-events", "attributes": { "created-at": "2021-02-09 20:07:49.686182 +0000 UTC", "level": "info", "message": "Loaded 11 repositories", "organization-id": "org-SBVreZxVessAmCZG" }, "relationships": { "oauth-client": { "data": { "id": "oc-LePsVhHXhCM6jWf3", "type": "oauth-clients" }, "links": { "related": "/api/v2/oauth-clients/oc-LePsVhHXhCM6jWf3" } }, "oauth-token": { "data": { "id": "ot-Ma2cs8tzjv3LYZHw", "type": "oauth-tokens" }, "links": { "related": "/api/v2/oauth-tokens/ot-Ma2cs8tzjv3LYZHw" } } } } ], "included": [ { "id": "oc-LePsVhHXhCM6jWf3", "type": "oauth-clients", "attributes": { "name": "working", "service-provider": "gitlab_hosted" }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" }, "links": { "related": "/api/v2/organizations/my-organization" } }, "oauth-tokens": { "data": [ { "id": "ot-Ma2cs8tzjv3LYZHw", "type": "oauth-tokens" } ] } } } ], "links": { "self": "https://app.terraform.io/api/v2/organizations/my-organization/vcs-events?filter%5Bfrom%5D=2021-02-02T14%3A09%3A00Z\u0026filter%5Blevels%5D=info\u0026filter%5Boauth_client_external_ids%5D=oc-LePsVhHXhCM6jWf3\u0026filter%5Bto%5D=2021-02-12T14%3A09%3A59Z\u0026include=oauth_client\u0026organization_name=my-organization\u0026page%5Bnumber%5D=1\u0026page%5Bsize%5D=20", "first": "https://app.terraform.io/api/v2/organizations/my-organization/vcs-events?filter%5Bfrom%5D=2021-02-02T14%3A09%3A00Z\u0026filter%5Blevels%5D=info\u0026filter%5Boauth_client_external_ids%5D=oc-LePsVhHXhCM6jWf3\u0026filter%5Bto%5D=2021-02-12T14%3A09%3A59Z\u0026include=oauth_client\u0026organization_name=my-organization\u0026page%5Bnumber%5D=1\u0026page%5Bsize%5D=20", "prev": null, "next": null, "last": "https://app.terraform.io/api/v2/organizations/my-organization/vcs-events?filter%5Bfrom%5D=2021-02-02T14%3A09%3A00Z\u0026filter%5Blevels%5D=info\u0026filter%5Boauth_client_external_ids%5D=oc-LePsVhHXhCM6jWf3\u0026filter%5Bto%5D=2021-02-12T14%3A09%3A59Z\u0026include=oauth_client\u0026organization_name=my-organization\u0026page%5Bnumber%5D=1\u0026page%5Bsize%5D=20" }, "meta": { "pagination": { "current-page": 1, "prev-page": null, "next-page": null, "total-pages": 1, "total-count": 8 } } } ```
terraform
page title VCS Events API Docs HCP Terraform description Use the vcs events endpoint to query VCS related events List changes within your organization using the HTTP API VCS Events API Note The VCS Events API is still in beta as support is being added for additional VCS providers Currently only GitLab com connections established after December 2020 are supported VCS version control system events describe changes within your organization for VCS related actions Events are only stored for 10 days If information about the OAuth Client terraform cloud docs api docs oauth clients or OAuth Token terraform cloud docs api docs oauth tokens are available at the time of the event it will be logged with the event List VCS events This endpoint lists VCS events for an organization GET organizations organization name vcs events Parameter Description organization name The name of the organization to list VCS events from The organization must already exist in the system and the user must have permissions to manage VCS settings Note Viewing VCS events is restricted to the owners team teams with the Manage VCS Settings and the organization API token terraform cloud docs users teams organizations api tokens organization api tokens More about permissions terraform cloud docs users teams organizations permissions Query Parameters This endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters Remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs Parameter Description page number Optional If omitted the endpoint will return the first page page size Optional If omitted the endpoint will return 20 workspaces per page filter from Optional Must be RFC3339 formatted and in UTC If omitted the endpoint will default to 10 days ago filter to Optional Must be RFC3339 formatted and in UTC If omitted the endpoint will default to now filter oauth client external ids Optional Format as a comma separated string If omitted the endpoint will return all events filter levels Optional info and error are the only accepted values If omitted the endpoint will return both info and error events include Optional Allows including related resource data This endpoint only supports oauth client as a value Only the name service provider and id will be returned on the OAuth Client object in the included block Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 organizations my organization vcs events filter 5Bfrom 5D 2021 02 02T14 3A09 3A00Z filter 5Bto 5D 2021 02 12T14 3A09 3A59Z filter 5Boauth client external ids 5D oc hhTM7WNUUgbXJpkW filter 5Blevels 5D info include oauth client Sample Response json data id ve DJpbEwZc98ZedHZG type vcs events attributes created at 2021 02 09 20 07 49 686182 0000 UTC level info message Loaded 11 repositories organization id org SBVreZxVessAmCZG relationships oauth client data id oc LePsVhHXhCM6jWf3 type oauth clients links related api v2 oauth clients oc LePsVhHXhCM6jWf3 oauth token data id ot Ma2cs8tzjv3LYZHw type oauth tokens links related api v2 oauth tokens ot Ma2cs8tzjv3LYZHw included id oc LePsVhHXhCM6jWf3 type oauth clients attributes name working service provider gitlab hosted relationships organization data id my organization type organizations links related api v2 organizations my organization oauth tokens data id ot Ma2cs8tzjv3LYZHw type oauth tokens links self https app terraform io api v2 organizations my organization vcs events filter 5Bfrom 5D 2021 02 02T14 3A09 3A00Z u0026filter 5Blevels 5D info u0026filter 5Boauth client external ids 5D oc LePsVhHXhCM6jWf3 u0026filter 5Bto 5D 2021 02 12T14 3A09 3A59Z u0026include oauth client u0026organization name my organization u0026page 5Bnumber 5D 1 u0026page 5Bsize 5D 20 first https app terraform io api v2 organizations my organization vcs events filter 5Bfrom 5D 2021 02 02T14 3A09 3A00Z u0026filter 5Blevels 5D info u0026filter 5Boauth client external ids 5D oc LePsVhHXhCM6jWf3 u0026filter 5Bto 5D 2021 02 12T14 3A09 3A59Z u0026include oauth client u0026organization name my organization u0026page 5Bnumber 5D 1 u0026page 5Bsize 5D 20 prev null next null last https app terraform io api v2 organizations my organization vcs events filter 5Bfrom 5D 2021 02 02T14 3A09 3A00Z u0026filter 5Blevels 5D info u0026filter 5Boauth client external ids 5D oc LePsVhHXhCM6jWf3 u0026filter 5Bto 5D 2021 02 12T14 3A09 3A59Z u0026include oauth client u0026organization name my organization u0026page 5Bnumber 5D 1 u0026page 5Bsize 5D 20 meta pagination current page 1 prev page null next page null total pages 1 total count 8
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 Use the comments endpoint to manage with a Terraform run s comments List show and create comments using the HTTP API 201 https developer mozilla org en US docs Web HTTP Status 201 page title Comments API Docs HCP Terraform
--- page_title: Comments - API Docs - HCP Terraform description: >- Use the `/comments` endpoint to manage with a Terraform run's comments. List, show, and create comments using the HTTP API. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [307]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/307 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # Comments API Comments allow users to leave feedback or record decisions about a run. ## List Comments for a Run `GET /runs/:id/comments` | Parameter | Description | | --------- | ------------------ | | `id` | The ID of the run. | ### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/runs/run-KTuq99JSzgmDSvYj/comments ``` ### Sample Response ```json { "data": [ { "id": "wsc-JdFX3u8o114F4CWf", "type": "comments", "attributes": { "body": "A comment body" }, "relationships": { "run-event": { "data": { "id": "re-fo1YXZ8W5bp5GBKM", "type": "run-events" }, "links": { "related": "/api/v2/run-events/re-fo1YXZ8W5bp5GBKM" } } }, "links": { "self": "/api/v2/comments/wsc-JdFX3u8o114F4CWf" } }, { "id": "wsc-QdhSPFTNoCTpfafp", "type": "comments", "attributes": { "body": "Another comment body" }, "relationships": { "run-event": { "data": { "id": "re-fo1YXZ8W5bp5GBKM", "type": "run-events" }, "links": { "related": "/api/v2/run-events/re-fo1YXZ8W5bp5GBKM" } } }, "links": { "self": "/api/v2/comments/wsc-QdhSPFTNoCTpfafp" } } ] } ``` ## Show a Comment `GET /comments/:id` | Parameter | Description | | --------- | ---------------------- | | `id` | The ID of the comment. | ### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/comments/wsc-gTFq83JSzjmAvYj ``` ### Sample Response ```json { "data": { "id": "wsc-gTFq83JSzjmAvYj", "type": "comments", "attributes": { "body": "Another comment" }, "relationships": { "run-event": { "data": { "id": "re-8RB5ZaFrDanG2hGY", "type": "run-events" }, "links": { "related": "/api/v2/run-events/re-8RB5ZaFrDanG2hGY" } } }, "links": { "self": "/api/v2/comments/wsc-gTFq83JSzjmAvYj" } } } ``` ## Create Comment `POST /runs/:id/comments` | Parameter | Description | | --------- | ------------------ | | `id` | The ID of the run. | ### Request Body This POST endpoint requires a JSON object with the following properties as the request payload. | Key Path | Type | Default | Description | ------------------------ | ------ | ------- | ---------------- | `data.type` | string | | Must be `"comments"`. | `data.attributes.body` | string | | The body of the comment. ### Sample Payload ```json { "data": { "attributes": { "body": "A comment about the run", }, "type": "comments" } } ``` ### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/runs/run-KTuq99JSzgmDSvYj/comments ``` ### Sample Response ```json { "data": { "id": "wsc-oRiShushpgLU4JD2", "type": "comments", "attributes": { "body": "A comment about the run" }, "relationships": { "run-event": { "data": { "id": "re-E3xsBX11F1fbm2zV", "type": "run-events" }, "links": { "related": "/api/v2/run-events/re-E3xsBX11F1fbm2zV" } } }, "links": { "self": "/api/v2/comments/wsc-oRiShushpgLU4JD2" } } } ```
terraform
page title Comments API Docs HCP Terraform description Use the comments endpoint to manage with a Terraform run s comments List show and create comments using the HTTP API 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 307 https developer mozilla org en US docs Web HTTP Status 307 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects Comments API Comments allow users to leave feedback or record decisions about a run List Comments for a Run GET runs id comments Parameter Description id The ID of the run Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 runs run KTuq99JSzgmDSvYj comments Sample Response json data id wsc JdFX3u8o114F4CWf type comments attributes body A comment body relationships run event data id re fo1YXZ8W5bp5GBKM type run events links related api v2 run events re fo1YXZ8W5bp5GBKM links self api v2 comments wsc JdFX3u8o114F4CWf id wsc QdhSPFTNoCTpfafp type comments attributes body Another comment body relationships run event data id re fo1YXZ8W5bp5GBKM type run events links related api v2 run events re fo1YXZ8W5bp5GBKM links self api v2 comments wsc QdhSPFTNoCTpfafp Show a Comment GET comments id Parameter Description id The ID of the comment Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 comments wsc gTFq83JSzjmAvYj Sample Response json data id wsc gTFq83JSzjmAvYj type comments attributes body Another comment relationships run event data id re 8RB5ZaFrDanG2hGY type run events links related api v2 run events re 8RB5ZaFrDanG2hGY links self api v2 comments wsc gTFq83JSzjmAvYj Create Comment POST runs id comments Parameter Description id The ID of the run Request Body This POST endpoint requires a JSON object with the following properties as the request payload Key Path Type Default Description data type string Must be comments data attributes body string The body of the comment Sample Payload json data attributes body A comment about the run type comments Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 runs run KTuq99JSzgmDSvYj comments Sample Response json data id wsc oRiShushpgLU4JD2 type comments attributes body A comment about the run relationships run event data id re E3xsBX11F1fbm2zV type run events links related api v2 run events re E3xsBX11F1fbm2zV links self api v2 comments wsc oRiShushpgLU4JD2
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 page title Notification Configurations API Docs HCP Terraform Use the notification configurations endpoint to manage notification configurations List show create update verify and delete notification configurations for a workspace using the HTTP API
--- page_title: Notification Configurations - API Docs - HCP Terraform description: >- Use the `notification-configurations` endpoint to manage notification configurations. List, show, create, update, verify, and delete notification configurations for a workspace using the HTTP API. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # Notification configuration API HCP Terraform can send notifications for run state transitions and workspace events. You can specify a destination URL, request type, and what events will trigger the notification. Each workspace can have up to 20 notification configurations, and they apply to all runs for that workspace. Interacting with notification configurations requires admin access to the relevant workspace. ([More about permissions](/terraform/cloud-docs/users-teams-organizations/permissions).) -> **Note:** [Speculative plans](/terraform/cloud-docs/run/modes-and-options#plan-only-speculative-plan) and workspaces configured with `Local` [execution mode](/terraform/cloud-docs/workspaces/settings#execution-mode) do not support notifications. [permissions-citation]: #intentionally-unused---keep-for-maintainers ## Notification triggers Notifications are sent in response to triggers related to workspace events, and can be defined at workspace and team levels. You can specify workspace events in the `triggers` array attribute. ### Workspace notification triggers The following triggers are available for workspace notifications. | Display Name | Value | Description | | ------------------ | ----------------------- | -------------------------------------------------------------------------------------------------------- | | Created | `"run:created"` | A run is created and enters the [Pending stage](/terraform/cloud-docs/run/states#the-pending-stage) | | Planning | `"run:planning"` | A run acquires the lock and starts to execute. | | Needs Attention | `"run:needs_attention"` | A plan has changes and Terraform requires user input to continue. This input may include approving the plan or a [policy override](/terraform/cloud-docs/run/states#the-policy-check-stage). | | Applying | `"run:applying"` | A run enters the [Apply stage](/terraform/cloud-docs/run/states#the-apply-stage), where Terraform makes the infrastructure changes described in the plan. | | Completed | `"run:completed"` | A run completes successfully. | | Errored | `"run:errored"` | A run terminates early due to error or cancellation. | | Drifted | `"assessment:drifted"` | HCP Terraform detected configuration drift. This option is only available if you enabled drift detection for the workspace. | | Checks Failed | `"assessment:check_failure"` | One or more continuous validation checks did not pass. This option is only available if you enabled drift detection for the workspace. | | Health Assessment Failed | `"assessment:failed"` | A health assessment failed. This option is only available if you enable health assessments for the workspace. | | Auto Destroy Reminder | `"workspace:auto_destro_reminder"` | An automated workspace destroy run is imminent. | | Auto Destroy Results | `"workspace:auto_destroy_run_results"` | HCP Terraform attempted an automated workspace destroy run. | ### Team notification triggers The following triggers are available for [team notifications](#team-notification-configuration). | Display Name | Value | Description | | ------------------ | ----------------------- | -------------------------------------------------------------------------------------------------------- | | Change Request | `"team:change_request"` | HCP Terraform sent a change request to a workspace that the specified team has explicit access to. | ## Notification payload The notification is an HTTP POST request with a detailed payload. The content depends on the type of notification. For Slack and Microsoft Teams notifications, the payload conforms to the respective webhook API and results in a notification message with informational attachments. Refer to [Slack Notification Payloads](/terraform/cloud-docs/workspaces/settings/notifications#slack) and [Microsoft Teams Notification Payloads](/terraform/cloud-docs/workspaces/settings/notifications#microsoft-teams) for examples. For generic notifications, the payload varies based on whether the notification contains information about run events or workspace events. ### Run notification payload Run events include detailed information about a specific run, including the time it began and the associated workspace and organization. Generic notifications for run events contain the following information: | Name | Type | Description | | -------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `payload_version` | number | Always "1". | | `notification_configuration_id` | string | The ID of the configuration associated with this notification. | | `run_url` | string | URL used to access the run UI page. | | `run_id` | string | ID of the run which triggered this notification. | | `run_message` | string | The reason the run was queued. | | `run_created_at` | string | Timestamp of the run's creation. | | `run_created_by` | string | Username of the user who created the run. | | `workspace_id` | string | ID of the run's workspace. | | `workspace_name` | string | Human-readable name of the run's workspace. | | `organization_name` | string | Human-readable name of the run's organization. | | `notifications` | array | List of events which caused this notification to be sent, with each event represented by an object. At present, this is always one event, but in the future HCP Terraform may roll up several notifications for a run into a single request. | | `notifications[].message` | string | Human-readable reason for the notification. | | `notifications[].trigger` | string | Value of the trigger which caused the notification to be sent. | | `notifications[].run_status` | string | Status of the run at the time of notification. | | `notifications[].run_updated_at` | string | Timestamp of the run's update. | | `notifications[].run_updated_by` | string | Username of the user who caused the run to update. | #### Sample payload ```json { "payload_version": 1, "notification_configuration_id": "nc-AeUQ2zfKZzW9TiGZ", "run_url": "https://app.terraform.io/app/acme-org/my-workspace/runs/run-FwnENkvDnrpyFC7M", "run_id": "run-FwnENkvDnrpyFC7M", "run_message": "Add five new queue workers", "run_created_at": "2019-01-25T18:34:00.000Z", "run_created_by": "sample-user", "workspace_id": "ws-XdeUVMWShTesDMME", "workspace_name": "my-workspace", "organization_name": "acme-org", "notifications": [ { "message": "Run Canceled", "trigger": "run:errored", "run_status": "canceled", "run_updated_at": "2019-01-25T18:37:04.000Z", "run_updated_by": "sample-user" } ] } ``` ### Change request notification payload Change request events contain the following fields in their payloads. | Name | Type | Description | | -------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `payload_version` | number | Always "1". | | `notification_configuration_id` | string | The ID of the configuration associated with this notification. | | `change_request_url` | string | URL used to access the change request UI page. | | `change_request_subject` | string | title of the change request which triggered this notification. | | `change_request_message` | string | The contents of the change request. | | `change_request_created_at` | string | Timestamp of the change request's creation. | | `change_request_created_by` | string | Username of the user who created the change_request. | | `workspace_id` | string | ID of the run's workspace. | | `workspace_name` | string | Human-readable name of the run's workspace. | | `organization_name` | string | Human-readable name of the run's organization. | ##### `Send a test` payload This is a sample payload you can send to test if notifications are working. The payload does not have a `run` or `workspace` context, resulting in null values. You can trigger a test notification from the workspace notification settings page. You can read more about verifying a [notification configuration](/terraform/enterprise/workspaces/settings/notifications#enabling-and-verifying-a-configuration). ```json { "payload_version": 1, "notification_configuration_id": "nc-jWvVsmp5VxsaCeXm", "run_url": null, "run_id": null, "run_message": null, "run_created_at": null, "run_created_by": null, "workspace_id": null, "workspace_name": null, "organization_name": null, "notifications": [ { "message": "Verification of test", "trigger": "verification", "run_status": null, "run_updated_at": null, "run_updated_by": null, } ] } ``` ### Workspace notification payload Workspace events include detailed information about workspace-level validation events like [health assessments](/terraform/cloud-docs/workspaces/health) if you enable them for the workspace. Much of the information provides details about the associated [assessment result](/terraform/cloud-docs/api-docs/assessment-results), which HCP Terraform uses to track instances of continuous validation. HCP Terraform returns different types of attributes returned in the payload details, depending on the type of `trigger_scope`. There are two main values for `trigger_scope`: `assessment` and `workspace`, examples of which you can see below. #### Health assessments Health assessment notifications for workspace events contain the following information: <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/health-assessments.mdx' <!-- END: TFC:only name:pnp-callout --> | Name | Type | Description | | -------------------------------------------- | ------ | ------------------------------------------------------------------------------------ | | `payload_version` | number | Always "2". | | `notification_configuration_id` | string | The ID of the configuration associated with this notification. | | `notification_configuration_url` | string | URL to get the notification configuration from the HCP Terraform API. | | `trigger_scope` | string | Always "assessment" for workspace assessment notifications. | | `trigger` | string | Value of the trigger that caused the notification to be sent. | | `message` | string | Human-readable reason for the notification. | | `details` | object | Object containing details specific to the notification. | | `details.new_assessment_result` | object | The most recent assessment result. This result triggered the notification. | | `details.new_assessment_result.id` | string | ID of the assessment result. | | `details.new_assessment_result.url` | string | URL to get the assessment result from the HCP Terraform API. | | `details.new_assessment_result.succeeded` | bool | Whether assessment succeeded. | | `details.new_assessment_result.all_checks_succeeded` | bool | Whether all conditions passed. | | `details.new_assessment_result.checks_passed` | number | The number of resources, data sources, and outputs passing their conditions. | | `details.new_assessment_result.checks_failed` | number | The number of resources, data sources, and outputs with one or more failing conditions. | | `details.new_assessment_result.checks_errored` | number | The number of resources, data sources, and outputs that had a condition error. | | `details.new_assessment_result.checks_unknown` | number | The number of resources, data sources, and outputs that had conditions left unevaluated. | | `details.new_assessment_result.drifted` | bool | Whether assessment detected drift. | | `details.new_assessment_result.resources_drifted` | number| The number of resources whose configuration does not match from the workspace's state file. | | `details.new_assessment_result.resources_undrifted` | number| The number of real resources whose configuration matches the workspace's state file. | | `details.new_assessment_result.created_at` | string | Timestamp for when HCP Terraform created the assessment result. | | `details.prior_assessment_result` | object | The assessment result immediately prior to the one that triggered the notification. | | `details.prior_assessment_result.id` | string | ID of the assessment result. | | `details.prior_assessment_result.url` | string | URL to get the assessment result from the HCP Terraform API. | | `details.prior_assessment_result.succeeded` | bool | Whether assessment succeeded. | | `details.prior_assessment_result.all_checks_succeeded` | bool | Whether all conditions passed. | | `details.prior_assessment_result.checks_passed` | number | The number of resources, data sources, and outputs passing their conditions. | | `details.prior_assessment_result.checks_failed` | number | The number of resources, data sources, and outputs with one or more failing conditions. | | `details.prior_assessment_result.checks_errored` | number | The number of resources, data sources, and outputs that had a condition error. | | `details.prior_assessment_result.checks_unknown` | number | The number of resources, data sources, and outputs that had conditions left unevaluated. | | `details.prior_assessment_result.drifted` | bool | Whether assessment detected drift. | | `details.prior_assessment_result.resources_drifted` | number| The number of resources whose configuration does not match the workspace's state file. | | `details.prior_assessment_result.resources_undrifted` | number| The number of resources whose configuration matches the workspace's state file. | | `details.prior_assessment_result.created_at` | string | Timestamp of the assessment result. | | `details.workspace_id` | string | ID of the workspace that generated the notification. | | `details.workspace_name` | string | Human-readable name of the workspace. | | `details.organization_name` | string | Human-readable name of the organization. | ##### Sample payload Health assessment payloads have information about resource drift and continuous validation checks. ```json { "payload_version": "2", "notification_configuration_id": "nc-SZ3V3cLFxK6sqLKn", "notification_configuration_url": "https://app.terraform.io/api/v2/notification-configurations/nc-SZ3V3cLFxK6sqLKn", "trigger_scope": "assessment", "trigger": "assessment:drifted", "message": "Drift Detected", "details": { "new_assessment_result": { "id": "asmtres-vRVQxpqq64EA9V5a", "url": "https://app.terraform.io/api/v2/assessment-results/asmtres-vRVQxpqq64EA9V5a", "succeeded": true, "drifted": true, "all_checks_succeeded": true, "resources_drifted": 4, "resources_undrifted": 55, "checks_passed": 33, "checks_failed": 0, "checks_errored": 0, "checks_unknown": 0, "created_at": "2022-06-09T05:23:10Z" }, "prior_assessment_result": { "id": "asmtres-A6zEbpGArqP74fdL", "url": "https://app.terraform.io/api/v2/assessment-results/asmtres-A6zEbpGArqP74fdL", "succeeded": true, "drifted": true, "all_checks_succeeded": true, "resources_drifted": 4, "resources_undrifted": 55, "checks_passed": 33, "checks_failed": 0, "checks_errored": 0, "checks_unknown": 0, "created_at": "2022-06-09T05:22:51Z" }, "workspace_id": "ws-XdeUVMWShTesDMME", "workspace_name": "my-workspace", "organization_name": "acme-org" } } ``` #### Automatic destroy runs <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/ephemeral-workspaces.mdx' <!-- END: TFC:only name:pnp-callout --> Automatic destroy run notifications for workspace events contain the following information: | Name | Type | Description | | -------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------------------| | `payload_version` | string | Always 2. | | `notification_configuration_id` | string | The ID of the notification's configuration. | | `notification_configuration_url` | string | The URL to get the notification's configuration from the HCP Terraform API. | | `trigger_scope` | string | Always "workspace" for ephemeral workspace notifications | | `trigger` | string | Value of the trigger that caused HCP Terraform to send the notification. | | `message` | string | Human-readable reason for the notification. | | `details` | object | Object containing details specific to the notification. | | `details.auto_destroy_at` | string | Timestamp when HCP Terraform will schedule the next destroy run. Only applies to reminder notifications. | | `details.run_created_at` | string | Timestamp of when HCP Terraform successfully created a destroy run. Only applies to results notifications. | | `details.run_status` | string | Status of the scheduled destroy run. Only applies to results notifications. | | `details.run_external_id` | string | The ID of the scheduled destroy run. Only applies to results notifications. | | `details.run_create_error_message` | string | Message detailing why the run was unable to be queued. Only applies to results notifications. | | `details.trigger_type` | string | The type of notification, and the value is either "reminder" or "results". | | `details.workspace_name` | string | Human-readable name of the workspace. | | `details.organization_name` | string | Human-readable name of the organization. | ##### Sample payload The shape of data in auto destroy notification payloads may differ depending on the success of the run HCP Terraform created. Refer to the specific examples below. ###### Reminder Reminders that HCP Terraform will trigger a destroy run at some point in the future. ```json { "payload_version": "2", "notification_configuration_id": "nc-SZ3V3cLFxK6sqLKn", "notification_configuration_url": "https://app.terraform.io/api/v2/notification-configurations/nc-SZ3V3cLFxK6sqLKn", "trigger_scope": "workspace", "trigger": "workspace:auto_destroy_reminder", "message": "Auto Destroy Reminder", "details": { "auto_destroy_at": "2025-01-01T00:00:00Z", "run_created_at": null, "run_status": null, "run_external_id": null, "run_create_error_message": null, "trigger_type": "reminder", "workspace_name": "learned-english-dog", "organization_name": "acme-org" } } ``` ###### Results The final result of the scheduled auto destroy run includes additional metadata about the run. ```json { "payload_version": "2", "notification_configuration_id": "nc-SZ3V3cLFxK6sqLKn", "notification_configuration_url": "https://app.terraform.io/api/v2/notification-configurations/nc-SZ3V3cLFxK6sqLKn", "trigger_scope": "workspace", "trigger": "workspace:auto_destroy_results", "message": "Auto Destroy Results", "details": { "auto_destroy_at": null, "run_created_at": "2022-06-09T05:22:51Z", "run_status": "applied", "run_external_id": "run-vRVQxpqq64EA9V5a", "run_create_error_message": null, "trigger_type": "results", "workspace_name": "learned-english-dog", "organization_name": "acme-org" } } ``` ###### Failed run creation Run-specific values are empty when HCP Terraform was unable to create an auto destroy run. ```json { "payload_version": "2", "notification_configuration_id": "nc-SZ3V3cLFxK6sqLKn", "notification_configuration_url": "https://app.terraform.io/api/v2/notification-configurations/nc-SZ3V3cLFxK6sqLKn", "trigger_scope": "workspace", "trigger": "workspace:auto_destroy_results", "message": "Auto Destroy Results", "details": { "auto_destroy_at": null, "run_created_at": null, "run_status": null, "run_external_id": null, "run_create_error_message": "Configuration version is missing", "trigger_type": "results", "workspace_name": "learned-english-dog", "organization_name": "acme-org" } } ``` ## Notification authenticity If a `token` is configured, HCP Terraform provides an HMAC signature on all `"generic"` notification requests, using the `token` as the key. This is sent in the `X-TFE-Notification-Signature` header. The digest algorithm used is SHA-512. Notification target servers should verify the source of the HTTP request by computing the HMAC of the request body using the same shared secret, and dropping any requests with invalid signatures. Sample Ruby code for verifying the HMAC: ```ruby token = SecureRandom.hex hmac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new("sha512"), token, @request.body) fail "Invalid HMAC" if hmac != @request.headers["X-TFE-Notification-Signature"] ``` ## Notification verification and delivery responses When saving a configuration with `enabled` set to `true`, or when using the [verify API][], HCP Terraform sends a verification request to the configured URL. The response to this request is stored and available in the `delivery-responses` array of the `notification-configuration` resource. Configurations cannot be enabled if the verification request fails. Success is defined as an HTTP response with status code of `2xx`. Configurations with `destination_type` `email` can only be verified manually, they do not require an HTTP response. The most recent response is stored in the `delivery-responses` array. Each delivery response has several fields: | Name | Type | Description | | ------------ | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `body` | string | Response body (may be truncated). | | `code` | string | HTTP status code, e.g. `400`. | | `headers` | object | All HTTP headers received, represented as an object with keys for each header name (lowercased) and an array of string values (most arrays will be size one). | | `sent-at` | date | The UTC timestamp when the notification was sent. | | `successful` | bool | Whether HCP Terraform considers this response to be successful. | | `url` | string | The URL to which the request was sent. | [verify API]: #verify-a-notification-configuration ## Create a notification configuration `POST /workspaces/:workspace_id/notification-configurations` | Parameter | Description | | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `:workspace_id` | The ID of the workspace to list configurations for. Obtain this from the [workspace settings](/terraform/cloud-docs/workspaces/settings) or the [Show Workspace](/terraform/cloud-docs/api-docs/workspaces#show-workspace) endpoint. | | Status | Response | Reason | | ------- | ------------------------------------------------------------- | -------------------------------------------------------------- | | [201][] | [JSON API document][] (`type: "notification-configurations"`) | Successfully created a notification configuration | | [400][] | [JSON API error object][] | Unable to complete verification request to destination URL | | [404][] | [JSON API error object][] | Workspace not found, or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (missing attributes, wrong types, etc.) | ### Request body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. If `enabled` is set to `true`, a verification request will be sent before saving the configuration. If this request receives no response or the response is not successful (HTTP 2xx), the configuration will not save. | Key path | Type | Default | Description | | ---------------------------------- | -------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data.type` | string | | Must be `"notification-configuration"`. | | `data.attributes.destination-type` | string | | Type of notification payload to send. Valid values are `"generic"`, `"email"`, `"slack"` or `"microsoft-teams"`. | | `data.attributes.enabled` | bool | `false` | Disabled configurations will not send any notifications. | | `data.attributes.name` | string | | Human-readable name for the configuration. | | `data.attributes.token` | string or null | `null` | Optional write-only secure token, which can be used at the receiving server to verify request authenticity. See [Notification Authenticity][notification-authenticity] for more details. | | `data.attributes.triggers` | array | `[]` | Array of triggers for which this configuration will send notifications. See [Notification Triggers][notification-triggers] for more details and a list of allowed values. | | `data.attributes.url` | string | | HTTP or HTTPS URL to which notification requests will be made, only for configurations with `"destination_type:"` `"slack"`, `"microsoft-teams"` or `"generic"` | | `data.relationships.users` | array | | Array of users part of the organization, only for configurations with `"destination_type:"` `"email"` | [notification-authenticity]: #notification-authenticity [notification-triggers]: #notification-triggers ### Sample payload for generic notification configurations ```json { "data": { "type": "notification-configuration", "attributes": { "destination-type": "generic", "enabled": true, "name": "Webhook server test", "url": "https://httpstat.us/200", "triggers": [ "run:applying", "run:completed", "run:created", "run:errored", "run:needs_attention", "run:planning" ] } } } ``` ### Sample payload for email notification configurations ```json { "data": { "type": "notification-configurations", "attributes": { "destination-type": "email", "enabled": true, "name": "Notify organization users about run", "triggers": [ "run:applying", "run:completed", "run:created", "run:errored", "run:needs_attention", "run:planning" ] }, "relationships": { "users": { "data": [ { "id": "organization-user-id", "type": "users" } ] } } } } ``` ### Sample request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/workspaces/ws-XdeUVMWShTesDMME/notification-configurations ``` ### Sample response ```json { "data": { "id": "nc-AeUQ2zfKZzW9TiGZ", "type": "notification-configurations", "attributes": { "enabled": true, "name": "Webhook server test", "url": "https://httpstat.us/200", "destination-type": "generic", "token": null, "triggers": [ "run:applying", "run:completed", "run:created", "run:errored", "run:needs_attention", "run:planning" ], "delivery-responses": [ { "url": "https://httpstat.us/200", "body": "\"200 OK\"", "code": "200", "headers": { "cache-control": [ "private" ], "content-length": [ "129" ], "content-type": [ "application/json; charset=utf-8" ], "content-encoding": [ "gzip" ], "vary": [ "Accept-Encoding" ], "server": [ "Microsoft-IIS/10.0" ], "x-aspnetmvc-version": [ "5.1" ], "access-control-allow-origin": [ "*" ], "x-aspnet-version": [ "4.0.30319" ], "x-powered-by": [ "ASP.NET" ], "set-cookie": [ "ARRAffinity=77c477e3e649643e5771873e1a13179fb00983bc73c71e196bf25967fd453df9;Path=/;HttpOnly;Domain=httpstat.us" ], "date": [ "Tue, 08 Jan 2019 21:34:37 GMT" ] }, "sent-at": "2019-01-08 21:34:37 UTC", "successful": "true" } ], "created-at": "2019-01-08T21:32:14.125Z", "updated-at": "2019-01-08T21:34:37.274Z" }, "relationships": { "subscribable": { "data": { "id": "ws-XdeUVMWShTesDMME", "type": "workspaces" } } }, "links": { "self": "/api/v2/notification-configurations/nc-AeUQ2zfKZzW9TiGZ" } } } ``` ## List notification configurations Use the following endpoint to list all notification configurations for a workspace. `GET /workspaces/:workspace_id/notification-configurations` | Parameter | Description | | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `:workspace_id` | The ID of the workspace to list configurations from. Obtain this from the [workspace settings](/terraform/cloud-docs/workspaces/settings) or the [Show Workspace](/terraform/cloud-docs/api-docs/workspaces#show-workspace) endpoint. If neither pagination query parameters are provided, the endpoint will not be paginated and will return all results. | ### Query parameters This endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. | Parameter | Description | | -------------- | ------------------------------------------------------------------------------------------- | | `page[number]` | **Optional.** If omitted, the endpoint will return the first page. | | `page[size]` | **Optional.** If omitted, the endpoint will return 20 notification configurations per page. | ### Sample request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/workspaces/ws-XdeUVMWShTesDMME/notification-configurations ``` ### Sample response ```json { "data": [ { "id": "nc-W6VGEi8A7Cfoaf4K", "type": "notification-configurations", "attributes": { "enabled": false, "name": "Slack: #devops", "url": "https://hooks.slack.com/services/T00000000/BC012345/0PWCpQmYyD4bTTRYZ53q4w", "destination-type": "slack", "token": null, "triggers": [ "run:errored", "run:needs_attention" ], "delivery-responses": [], "created-at": "2019-01-08T21:34:28.367Z", "updated-at": "2019-01-08T21:34:28.367Z" }, "relationships": { "subscribable": { "data": { "id": "ws-XdeUVMWShTesDMME", "type": "workspaces" } } }, "links": { "self": "/api/v2/notification-configurations/nc-W6VGEi8A7Cfoaf4K" } }, { "id": "nc-AeUQ2zfKZzW9TiGZ", "type": "notification-configurations", "attributes": { "enabled": true, "name": "Webhook server test", "url": "https://httpstat.us/200", "destination-type": "generic", "token": null, "triggers": [ "run:applying", "run:completed", "run:created", "run:errored", "run:needs_attention", "run:planning" ], "delivery-responses": [ { "url": "https://httpstat.us/200", "body": "\"200 OK\"", "code": "200", "headers": { "cache-control": [ "private" ], "content-length": [ "129" ], "content-type": [ "application/json; charset=utf-8" ], "content-encoding": [ "gzip" ], "vary": [ "Accept-Encoding" ], "server": [ "Microsoft-IIS/10.0" ], "x-aspnetmvc-version": [ "5.1" ], "access-control-allow-origin": [ "*" ], "x-aspnet-version": [ "4.0.30319" ], "x-powered-by": [ "ASP.NET" ], "set-cookie": [ "ARRAffinity=77c477e3e649643e5771873e1a13179fb00983bc73c71e196bf25967fd453df9;Path=/;HttpOnly;Domain=httpstat.us" ], "date": [ "Tue, 08 Jan 2019 21:34:37 GMT" ] }, "sent-at": "2019-01-08 21:34:37 UTC", "successful": "true" } ], "created-at": "2019-01-08T21:32:14.125Z", "updated-at": "2019-01-08T21:34:37.274Z" }, "relationships": { "subscribable": { "data": { "id": "ws-XdeUVMWShTesDMME", "type": "workspaces" } } }, "links": { "self": "/api/v2/notification-configurations/nc-AeUQ2zfKZzW9TiGZ" } } ] } ``` ## Show a notification configuration `GET /notification-configurations/:notification-configuration-id` | Parameter | Description | | -------------------------------- | ------------------------------------------------- | | `:notification-configuration-id` | The id of the notification configuration to show. | ### Sample request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/notification-configurations/nc-AeUQ2zfKZzW9TiGZ ``` ### Sample response The `type` and `id` attributes in `relationships.subscribable` may also reference a `"teams"` and team ID, respectively. ```json { "data": { "id": "nc-AeUQ2zfKZzW9TiGZ", "type": "notification-configurations", "attributes": { "enabled": true, "name": "Webhook server test", "url": "https://httpstat.us/200", "destination-type": "generic", "token": null, "triggers": [ "run:applying", "run:completed", "run:created", "run:errored", "run:needs_attention", "run:planning" ], "delivery-responses": [ { "url": "https://httpstat.us/200", "body": "\"200 OK\"", "code": "200", "headers": { "cache-control": [ "private" ], "content-length": [ "129" ], "content-type": [ "application/json; charset=utf-8" ], "content-encoding": [ "gzip" ], "vary": [ "Accept-Encoding" ], "server": [ "Microsoft-IIS/10.0" ], "x-aspnetmvc-version": [ "5.1" ], "access-control-allow-origin": [ "*" ], "x-aspnet-version": [ "4.0.30319" ], "x-powered-by": [ "ASP.NET" ], "set-cookie": [ "ARRAffinity=77c477e3e649643e5771873e1a13179fb00983bc73c71e196bf25967fd453df9;Path=/;HttpOnly;Domain=httpstat.us" ], "date": [ "Tue, 08 Jan 2019 21:34:37 GMT" ] }, "sent-at": "2019-01-08 21:34:37 UTC", "successful": "true" } ], "created-at": "2019-01-08T21:32:14.125Z", "updated-at": "2019-01-08T21:34:37.274Z" }, "relationships": { "subscribable": { "data": { "id": "ws-XdeUVMWShTesDMME", "type": "workspaces" } } }, "links": { "self": "/api/v2/notification-configurations/nc-AeUQ2zfKZzW9TiGZ" } } } ``` ## Update a notification configuration `PATCH /notification-configurations/:notification-configuration-id` | Parameter | Description | | -------------------------------- | --------------------------------------------------- | | `:notification-configuration-id` | The id of the notification configuration to update. | If the `enabled` attribute is true, updating the configuration will cause HCP Terraform to send a verification request. If a response is received, it will be stored and returned in the `delivery-responses` attribute. More details in the [Notification Verification and Delivery Responses][] section above. [Notification Verification and Delivery Responses]: #notification-verification-and-delivery-responses | Status | Response | Reason | | ------- | ------------------------------------------------------------- | ---------------------------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "notification-configurations"`) | Successfully updated the notification configuration | | [400][] | [JSON API error object][] | Unable to complete verification request to destination URL | | [404][] | [JSON API error object][] | Notification configuration not found, or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (missing attributes, wrong types, etc.) | ### Request body This PATCH endpoint requires a JSON object with the following properties as a request payload. If `enabled` is set to `true`, a verification request will be sent before saving the configuration. If this request fails to send, or the response is not successful (HTTP 2xx), the configuration will not save. | Key path | Type | Default | Description | | -------------------------- | ------ | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data.type` | string | (previous value) | Must be `"notification-configuration"`. | | `data.attributes.enabled` | bool | (previous value) | Disabled configurations will not send any notifications. | | `data.attributes.name` | string | (previous value) | User-readable name for the configuration. | | `data.attributes.token` | string | (previous value) | Optional write-only secure token, which can be used at the receiving server to verify request authenticity. See [Notification Authenticity][notification-authenticity] for more details. | | `data.attributes.triggers` | array | (previous value) | Array of triggers for sending notifications. See [Notification Triggers][notification-triggers] for more details. | | `data.attributes.url` | string | (previous value) | HTTP or HTTPS URL to which notification requests will be made, only for configurations with `"destination_type:"` `"slack"`, `"microsoft-teams"` or `"generic"` | | `data.relationships.users` | array | | Array of users part of the organization, only for configurations with `"destination_type:"` `"email"` | [notification-authenticity]: #notification-authenticity [notification-triggers]: #notification-triggers ### Sample payload ```json { "data": { "id": "nc-W6VGEi8A7Cfoaf4K", "type": "notification-configurations", "attributes": { "enabled": false, "name": "Slack: #devops", "url": "https://hooks.slack.com/services/T00000001/BC012345/0PWCpQmYyD4bTTRYZ53q4w", "destination-type": "slack", "token": null, "triggers": [ "run:created", "run:errored", "run:needs_attention" ], } } } ``` ### Sample request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request PATCH \ --data @payload.json \ https://app.terraform.io/api/v2/notification-configurations/nc-W6VGEi8A7Cfoaf4K ``` ### Sample response ```json { "data": { "id": "nc-W6VGEi8A7Cfoaf4K", "type": "notification-configurations", "attributes": { "enabled": false, "name": "Slack: #devops", "url": "https://hooks.slack.com/services/T00000001/BC012345/0PWCpQmYyD4bTTRYZ53q4w", "destination-type": "slack", "token": null, "triggers": [ "run:created", "run:errored", "run:needs_attention" ], "delivery-responses": [], "created-at": "2019-01-08T21:34:28.367Z", "updated-at": "2019-01-08T21:49:02.103Z" }, "relationships": { "subscribable": { "data": { "id": "ws-XdeUVMWShTesDMME", "type": "workspaces" } } }, "links": { "self": "/api/v2/notification-configurations/nc-W6VGEi8A7Cfoaf4K" } }, } ``` ## Verify a notification configuration `POST /notification-configurations/:notification-configuration-id/actions/verify` | Parameter | Description | | -------------------------------- | --------------------------------------------------- | | `:notification-configuration-id` | The id of the notification configuration to verify. | This will cause HCP Terraform to send a verification request for the specified configuration. If a response is received, it will be stored and returned in the `delivery-responses` attribute. More details in the [Notification Verification and Delivery Responses][] section above. | Status | Response | Reason | | ------- | ------------------------------------------------------------- | ---------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "notification-configurations"`) | Successfully verified the notification configuration | | [400][] | [JSON API error object][] | Unable to complete verification request to destination URL | ### Sample request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ https://app.terraform.io/api/v2/notification-configurations/nc-AeUQ2zfKZzW9TiGZ/actions/verify ``` ### Sample response ```json { "data": { "id": "nc-AeUQ2zfKZzW9TiGZ", "type": "notification-configurations", "attributes": { "enabled": true, "name": "Webhook server test", "url": "https://httpstat.us/200", "destination-type": "generic", "token": null, "triggers": [ "run:applying", "run:completed", "run:created", "run:errored", "run:needs_attention", "run:planning" ], "delivery-responses": [ { "url": "https://httpstat.us/200", "body": "\"200 OK\"", "code": "200", "headers": { "cache-control": [ "private" ], "content-length": [ "129" ], "content-type": [ "application/json; charset=utf-8" ], "content-encoding": [ "gzip" ], "vary": [ "Accept-Encoding" ], "server": [ "Microsoft-IIS/10.0" ], "x-aspnetmvc-version": [ "5.1" ], "access-control-allow-origin": [ "*" ], "x-aspnet-version": [ "4.0.30319" ], "x-powered-by": [ "ASP.NET" ], "set-cookie": [ "ARRAffinity=77c477e3e649643e5771873e1a13179fb00983bc73c71e196bf25967fd453df9;Path=/;HttpOnly;Domain=httpstat.us" ], "date": [ "Tue, 08 Jan 2019 21:34:37 GMT" ] }, "sent-at": "2019-01-08 21:34:37 UTC", "successful": "true" } ], "created-at": "2019-01-08T21:32:14.125Z", "updated-at": "2019-01-08T21:34:37.274Z" }, "relationships": { "subscribable": { "data": { "id": "ws-XdeUVMWShTesDMME", "type": "workspaces" } } }, "links": { "self": "/api/v2/notification-configurations/nc-AeUQ2zfKZzW9TiGZ" } } } ``` ## Delete a notification configuration This endpoint deletes a notification configuration. `DELETE /notification-configurations/:notification-configuration-id` | Parameter | Description | | -------------------------------- | --------------------------------------------------- | | `:notification-configuration-id` | The id of the notification configuration to delete. | | Status | Response | Reason | | ------- | ------------------------- | ---------------------------------------------------------------------------- | | [204][] | None | Successfully deleted the notification configuration | | [404][] | [JSON API error object][] | Notification configuration not found, or user unauthorized to perform action | ### Sample request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request DELETE \ https://app.terraform.io/api/v2/notification-configurations/nc-AeUQ2zfKZzW9TiGZ ``` ## Team notification configuration -> **Note**: Team notifications are in public beta. All APIs and workflows are subject to change. Team notifications allow you to configure relevant alerts that notify teams you specify whenever a certain event occurs. <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/notifications.mdx' <!-- END: TFC:only name:pnp-callout --> ### Create a team notification configuration By default, every team has a default email notification configuration with no users assigned. If a notification configuration has no users assigned, HCP Terraform sends email notifications to all team members. Use this endpoint to create a notification configuration to notify a team. `POST /teams/:team_id/notification-configurations` | Parameter | Description | | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `:team_id` | The ID of the team to create a configuration for. | | Status | Response | Reason | | ------- | ------------------------------------------------------------- | -------------------------------------------------------------- | | [201][] | [JSON API document][] (`type: "notification-configurations"`) | Successfully created a notification configuration | | [400][] | [JSON API error object][] | Unable to complete verification request to destination URL | | [404][] | [JSON API error object][] | Team not found, or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (missing attributes, wrong types, etc.) | #### Request body This `POST` endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. If `enabled` is set to `true`, HCP Terraform sends a verification request before saving the configuration. If this request does not receive a response or the response is not successful (HTTP 2xx), the configuration will not be saved. | Key path | Type | Default | Description | | ---------------------------------- | -------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data.type` | string | | Must be `"notification-configuration"`. | | `data.attributes.destination-type` | string | | Type of notification payload to send. Valid values are `"generic"`, `"email"`, `"slack"` or `"microsoft-teams"`. | | `data.attributes.enabled` | bool | `false` | Disabled configurations will not send any notifications. | | `data.attributes.name` | string | | Human-readable name for the configuration. | | `data.attributes.token` | string or null | `null` | Optional write-only secure token, which can be used at the receiving server to verify request authenticity. See [Notification Authenticity][notification-authenticity] for more details. | | `data.attributes.triggers` | array | `[]` | Array of triggers for which this configuration will send notifications. See [Notification Triggers][notification-triggers] for more details and a list of allowed values. | | `data.attributes.url` | string | | HTTP or HTTPS URL to which notification requests will be made, only for configurations with `"destination_type:"` `"slack"`, `"microsoft-teams"` or `"generic"` | | `data.attributes.email_all_members`| bool | | Email all team members, only for configurations with `"destination_type:" "email"`. | | `data.relationships.users` | array | | Array of users part of the organization, only for configurations with `"destination_type:"` `"email"` | [notification-authenticity]: #notification-authenticity [notification-triggers]: #notification-triggers #### Sample payload for generic notification configurations ```json { "data": { "type": "notification-configuration", "attributes": { "destination-type": "generic", "enabled": true, "name": "Webhook server test", "url": "https://httpstat.us/200", "triggers": [ "change_request:created" ] } } } ``` #### Sample payload for email notification configurations ```json { "data": { "type": "notification-configurations", "attributes": { "destination-type": "email", "enabled": true, "name": "Email teams about change requests", "triggers": [ "change_request:created" ] }, "relationships": { "users": { "data": [ { "id": "organization-user-id", "type": "users" } ] } } } } ``` #### Sample request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/teams/team-6p5jTwJQXwqZBncC/notification-configurations ``` #### Sample response ```json { "data": { "id": "nc-AeUQ2zfKZzW9TiGZ", "type": "notification-configurations", "attributes": { "enabled": true, "name": "Webhook server test", "url": "https://httpstat.us/200", "destination-type": "generic", "token": null, "triggers": [ "change_request:created" ], "delivery-responses": [ { "url": "https://httpstat.us/200", "body": "\"200 OK\"", "code": "200", "headers": { "cache-control": [ "private" ], "content-length": [ "129" ], "content-type": [ "application/json; charset=utf-8" ], "content-encoding": [ "gzip" ], "vary": [ "Accept-Encoding" ], "server": [ "Microsoft-IIS/10.0" ], "x-aspnetmvc-version": [ "5.1" ], "access-control-allow-origin": [ "*" ], "x-aspnet-version": [ "4.0.30319" ], "x-powered-by": [ "ASP.NET" ], "set-cookie": [ "ARRAffinity=77c477e3e649643e5771873e1a13179fb00983bc73c71e196bf25967fd453df9;Path=/;HttpOnly;Domain=httpstat.us" ], "date": [ "Tue, 08 Jan 2024 21:34:37 GMT" ] }, "sent-at": "2024-01-08 21:34:37 UTC", "successful": "true" } ], "created-at": "2024-01-08T21:32:14.125Z", "updated-at": "2024-01-08T21:34:37.274Z" }, "relationships": { "subscribable": { "data": { "id": "team-6p5jTwJQXwqZBncC", "type": "teams" } } }, "links": { "self": "/api/v2/notification-configurations/nc-AeUQ2zfKZzW9TiGZ" } } } ``` ### List team notification configurations Use this endpoint to list notification configurations for a team. `GET /teams/:team_id/notification-configurations` | Parameter | Description | | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `:team_id` | The ID of the teams to list configurations from. | ### Query Parameters This endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. | Parameter | Description | | -------------- | ------------------------------------------------------------------------------------------- | | `page[number]` | **Optional.** If omitted, the endpoint will return the first page. | | `page[size]` | **Optional.** If omitted, the endpoint will return 20 notification configurations per page. | #### Sample request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/teams/team-6p5jTwJQXwqZBncC/notification-configurations ``` #### Sample response ```json { "data": [ { "id": "nc-W6VGEi8A7Cfoaf4K", "type": "notification-configurations", "attributes": { "enabled": false, "name": "Slack: #devops", "url": "https://hooks.slack.com/services/T00000000/BC012345/0PWCpQmYyD4bTTRYZ53q4w", "destination-type": "slack", "token": null, "triggers": [ "change_request:created" ], "delivery-responses": [], "created-at": "2019-01-08T21:34:28.367Z", "updated-at": "2019-01-08T21:34:28.367Z" }, "relationships": { "subscribable": { "data": { "id": "team-TdeUVMWShTesDMME", "type": "teams" } } }, "links": { "self": "/api/v2/notification-configurations/nc-W6VGEi8A7Cfoaf4K" } }, { "id": "nc-AeUQ2zfKZzW9TiGZ", "type": "notification-configurations", "attributes": { "enabled": true, "name": "Webhook server test", "url": "https://httpstat.us/200", "destination-type": "generic", "token": null, "triggers": [ "change_request:created" ], "delivery-responses": [ { "url": "https://httpstat.us/200", "body": "\"200 OK\"", "code": "200", "headers": { "cache-control": [ "private" ], "content-length": [ "129" ], "content-type": [ "application/json; charset=utf-8" ], "content-encoding": [ "gzip" ], "vary": [ "Accept-Encoding" ], "server": [ "Microsoft-IIS/10.0" ], "x-aspnetmvc-version": [ "5.1" ], "access-control-allow-origin": [ "*" ], "x-aspnet-version": [ "4.0.30319" ], "x-powered-by": [ "ASP.NET" ], "set-cookie": [ "ARRAffinity=77c477e3e649643e5771873e1a13179fb00983bc73c71e196bf25967fd453df9;Path=/;HttpOnly;Domain=httpstat.us" ], "date": [ "Tue, 08 Jan 2019 21:34:37 GMT" ] }, "sent-at": "2019-01-08 21:34:37 UTC", "successful": "true" } ], "created-at": "2019-01-08T21:32:14.125Z", "updated-at": "2019-01-08T21:34:37.274Z" }, "relationships": { "subscribable": { "data": { "id": "team-XdeUVMWShTesDMME", "type": "teams" } } }, "links": { "self": "/api/v2/notification-configurations/nc-AeUQ2zfKZzW9TiGZ" } } ] } ```
terraform
page title Notification Configurations API Docs HCP Terraform description Use the notification configurations endpoint to manage notification configurations List show create update verify and delete notification configurations for a workspace using the HTTP API 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects Notification configuration API HCP Terraform can send notifications for run state transitions and workspace events You can specify a destination URL request type and what events will trigger the notification Each workspace can have up to 20 notification configurations and they apply to all runs for that workspace Interacting with notification configurations requires admin access to the relevant workspace More about permissions terraform cloud docs users teams organizations permissions Note Speculative plans terraform cloud docs run modes and options plan only speculative plan and workspaces configured with Local execution mode terraform cloud docs workspaces settings execution mode do not support notifications permissions citation intentionally unused keep for maintainers Notification triggers Notifications are sent in response to triggers related to workspace events and can be defined at workspace and team levels You can specify workspace events in the triggers array attribute Workspace notification triggers The following triggers are available for workspace notifications Display Name Value Description Created run created A run is created and enters the Pending stage terraform cloud docs run states the pending stage Planning run planning A run acquires the lock and starts to execute Needs Attention run needs attention A plan has changes and Terraform requires user input to continue This input may include approving the plan or a policy override terraform cloud docs run states the policy check stage Applying run applying A run enters the Apply stage terraform cloud docs run states the apply stage where Terraform makes the infrastructure changes described in the plan Completed run completed A run completes successfully Errored run errored A run terminates early due to error or cancellation Drifted assessment drifted HCP Terraform detected configuration drift This option is only available if you enabled drift detection for the workspace Checks Failed assessment check failure One or more continuous validation checks did not pass This option is only available if you enabled drift detection for the workspace Health Assessment Failed assessment failed A health assessment failed This option is only available if you enable health assessments for the workspace Auto Destroy Reminder workspace auto destro reminder An automated workspace destroy run is imminent Auto Destroy Results workspace auto destroy run results HCP Terraform attempted an automated workspace destroy run Team notification triggers The following triggers are available for team notifications team notification configuration Display Name Value Description Change Request team change request HCP Terraform sent a change request to a workspace that the specified team has explicit access to Notification payload The notification is an HTTP POST request with a detailed payload The content depends on the type of notification For Slack and Microsoft Teams notifications the payload conforms to the respective webhook API and results in a notification message with informational attachments Refer to Slack Notification Payloads terraform cloud docs workspaces settings notifications slack and Microsoft Teams Notification Payloads terraform cloud docs workspaces settings notifications microsoft teams for examples For generic notifications the payload varies based on whether the notification contains information about run events or workspace events Run notification payload Run events include detailed information about a specific run including the time it began and the associated workspace and organization Generic notifications for run events contain the following information Name Type Description payload version number Always 1 notification configuration id string The ID of the configuration associated with this notification run url string URL used to access the run UI page run id string ID of the run which triggered this notification run message string The reason the run was queued run created at string Timestamp of the run s creation run created by string Username of the user who created the run workspace id string ID of the run s workspace workspace name string Human readable name of the run s workspace organization name string Human readable name of the run s organization notifications array List of events which caused this notification to be sent with each event represented by an object At present this is always one event but in the future HCP Terraform may roll up several notifications for a run into a single request notifications message string Human readable reason for the notification notifications trigger string Value of the trigger which caused the notification to be sent notifications run status string Status of the run at the time of notification notifications run updated at string Timestamp of the run s update notifications run updated by string Username of the user who caused the run to update Sample payload json payload version 1 notification configuration id nc AeUQ2zfKZzW9TiGZ run url https app terraform io app acme org my workspace runs run FwnENkvDnrpyFC7M run id run FwnENkvDnrpyFC7M run message Add five new queue workers run created at 2019 01 25T18 34 00 000Z run created by sample user workspace id ws XdeUVMWShTesDMME workspace name my workspace organization name acme org notifications message Run Canceled trigger run errored run status canceled run updated at 2019 01 25T18 37 04 000Z run updated by sample user Change request notification payload Change request events contain the following fields in their payloads Name Type Description payload version number Always 1 notification configuration id string The ID of the configuration associated with this notification change request url string URL used to access the change request UI page change request subject string title of the change request which triggered this notification change request message string The contents of the change request change request created at string Timestamp of the change request s creation change request created by string Username of the user who created the change request workspace id string ID of the run s workspace workspace name string Human readable name of the run s workspace organization name string Human readable name of the run s organization Send a test payload This is a sample payload you can send to test if notifications are working The payload does not have a run or workspace context resulting in null values You can trigger a test notification from the workspace notification settings page You can read more about verifying a notification configuration terraform enterprise workspaces settings notifications enabling and verifying a configuration json payload version 1 notification configuration id nc jWvVsmp5VxsaCeXm run url null run id null run message null run created at null run created by null workspace id null workspace name null organization name null notifications message Verification of test trigger verification run status null run updated at null run updated by null Workspace notification payload Workspace events include detailed information about workspace level validation events like health assessments terraform cloud docs workspaces health if you enable them for the workspace Much of the information provides details about the associated assessment result terraform cloud docs api docs assessment results which HCP Terraform uses to track instances of continuous validation HCP Terraform returns different types of attributes returned in the payload details depending on the type of trigger scope There are two main values for trigger scope assessment and workspace examples of which you can see below Health assessments Health assessment notifications for workspace events contain the following information BEGIN TFC only name pnp callout include tfc package callouts health assessments mdx END TFC only name pnp callout Name Type Description payload version number Always 2 notification configuration id string The ID of the configuration associated with this notification notification configuration url string URL to get the notification configuration from the HCP Terraform API trigger scope string Always assessment for workspace assessment notifications trigger string Value of the trigger that caused the notification to be sent message string Human readable reason for the notification details object Object containing details specific to the notification details new assessment result object The most recent assessment result This result triggered the notification details new assessment result id string ID of the assessment result details new assessment result url string URL to get the assessment result from the HCP Terraform API details new assessment result succeeded bool Whether assessment succeeded details new assessment result all checks succeeded bool Whether all conditions passed details new assessment result checks passed number The number of resources data sources and outputs passing their conditions details new assessment result checks failed number The number of resources data sources and outputs with one or more failing conditions details new assessment result checks errored number The number of resources data sources and outputs that had a condition error details new assessment result checks unknown number The number of resources data sources and outputs that had conditions left unevaluated details new assessment result drifted bool Whether assessment detected drift details new assessment result resources drifted number The number of resources whose configuration does not match from the workspace s state file details new assessment result resources undrifted number The number of real resources whose configuration matches the workspace s state file details new assessment result created at string Timestamp for when HCP Terraform created the assessment result details prior assessment result object The assessment result immediately prior to the one that triggered the notification details prior assessment result id string ID of the assessment result details prior assessment result url string URL to get the assessment result from the HCP Terraform API details prior assessment result succeeded bool Whether assessment succeeded details prior assessment result all checks succeeded bool Whether all conditions passed details prior assessment result checks passed number The number of resources data sources and outputs passing their conditions details prior assessment result checks failed number The number of resources data sources and outputs with one or more failing conditions details prior assessment result checks errored number The number of resources data sources and outputs that had a condition error details prior assessment result checks unknown number The number of resources data sources and outputs that had conditions left unevaluated details prior assessment result drifted bool Whether assessment detected drift details prior assessment result resources drifted number The number of resources whose configuration does not match the workspace s state file details prior assessment result resources undrifted number The number of resources whose configuration matches the workspace s state file details prior assessment result created at string Timestamp of the assessment result details workspace id string ID of the workspace that generated the notification details workspace name string Human readable name of the workspace details organization name string Human readable name of the organization Sample payload Health assessment payloads have information about resource drift and continuous validation checks json payload version 2 notification configuration id nc SZ3V3cLFxK6sqLKn notification configuration url https app terraform io api v2 notification configurations nc SZ3V3cLFxK6sqLKn trigger scope assessment trigger assessment drifted message Drift Detected details new assessment result id asmtres vRVQxpqq64EA9V5a url https app terraform io api v2 assessment results asmtres vRVQxpqq64EA9V5a succeeded true drifted true all checks succeeded true resources drifted 4 resources undrifted 55 checks passed 33 checks failed 0 checks errored 0 checks unknown 0 created at 2022 06 09T05 23 10Z prior assessment result id asmtres A6zEbpGArqP74fdL url https app terraform io api v2 assessment results asmtres A6zEbpGArqP74fdL succeeded true drifted true all checks succeeded true resources drifted 4 resources undrifted 55 checks passed 33 checks failed 0 checks errored 0 checks unknown 0 created at 2022 06 09T05 22 51Z workspace id ws XdeUVMWShTesDMME workspace name my workspace organization name acme org Automatic destroy runs BEGIN TFC only name pnp callout include tfc package callouts ephemeral workspaces mdx END TFC only name pnp callout Automatic destroy run notifications for workspace events contain the following information Name Type Description payload version string Always 2 notification configuration id string The ID of the notification s configuration notification configuration url string The URL to get the notification s configuration from the HCP Terraform API trigger scope string Always workspace for ephemeral workspace notifications trigger string Value of the trigger that caused HCP Terraform to send the notification message string Human readable reason for the notification details object Object containing details specific to the notification details auto destroy at string Timestamp when HCP Terraform will schedule the next destroy run Only applies to reminder notifications details run created at string Timestamp of when HCP Terraform successfully created a destroy run Only applies to results notifications details run status string Status of the scheduled destroy run Only applies to results notifications details run external id string The ID of the scheduled destroy run Only applies to results notifications details run create error message string Message detailing why the run was unable to be queued Only applies to results notifications details trigger type string The type of notification and the value is either reminder or results details workspace name string Human readable name of the workspace details organization name string Human readable name of the organization Sample payload The shape of data in auto destroy notification payloads may differ depending on the success of the run HCP Terraform created Refer to the specific examples below Reminder Reminders that HCP Terraform will trigger a destroy run at some point in the future json payload version 2 notification configuration id nc SZ3V3cLFxK6sqLKn notification configuration url https app terraform io api v2 notification configurations nc SZ3V3cLFxK6sqLKn trigger scope workspace trigger workspace auto destroy reminder message Auto Destroy Reminder details auto destroy at 2025 01 01T00 00 00Z run created at null run status null run external id null run create error message null trigger type reminder workspace name learned english dog organization name acme org Results The final result of the scheduled auto destroy run includes additional metadata about the run json payload version 2 notification configuration id nc SZ3V3cLFxK6sqLKn notification configuration url https app terraform io api v2 notification configurations nc SZ3V3cLFxK6sqLKn trigger scope workspace trigger workspace auto destroy results message Auto Destroy Results details auto destroy at null run created at 2022 06 09T05 22 51Z run status applied run external id run vRVQxpqq64EA9V5a run create error message null trigger type results workspace name learned english dog organization name acme org Failed run creation Run specific values are empty when HCP Terraform was unable to create an auto destroy run json payload version 2 notification configuration id nc SZ3V3cLFxK6sqLKn notification configuration url https app terraform io api v2 notification configurations nc SZ3V3cLFxK6sqLKn trigger scope workspace trigger workspace auto destroy results message Auto Destroy Results details auto destroy at null run created at null run status null run external id null run create error message Configuration version is missing trigger type results workspace name learned english dog organization name acme org Notification authenticity If a token is configured HCP Terraform provides an HMAC signature on all generic notification requests using the token as the key This is sent in the X TFE Notification Signature header The digest algorithm used is SHA 512 Notification target servers should verify the source of the HTTP request by computing the HMAC of the request body using the same shared secret and dropping any requests with invalid signatures Sample Ruby code for verifying the HMAC ruby token SecureRandom hex hmac OpenSSL HMAC hexdigest OpenSSL Digest new sha512 token request body fail Invalid HMAC if hmac request headers X TFE Notification Signature Notification verification and delivery responses When saving a configuration with enabled set to true or when using the verify API HCP Terraform sends a verification request to the configured URL The response to this request is stored and available in the delivery responses array of the notification configuration resource Configurations cannot be enabled if the verification request fails Success is defined as an HTTP response with status code of 2xx Configurations with destination type email can only be verified manually they do not require an HTTP response The most recent response is stored in the delivery responses array Each delivery response has several fields Name Type Description body string Response body may be truncated code string HTTP status code e g 400 headers object All HTTP headers received represented as an object with keys for each header name lowercased and an array of string values most arrays will be size one sent at date The UTC timestamp when the notification was sent successful bool Whether HCP Terraform considers this response to be successful url string The URL to which the request was sent verify API verify a notification configuration Create a notification configuration POST workspaces workspace id notification configurations Parameter Description workspace id The ID of the workspace to list configurations for Obtain this from the workspace settings terraform cloud docs workspaces settings or the Show Workspace terraform cloud docs api docs workspaces show workspace endpoint Status Response Reason 201 JSON API document type notification configurations Successfully created a notification configuration 400 JSON API error object Unable to complete verification request to destination URL 404 JSON API error object Workspace not found or user unauthorized to perform action 422 JSON API error object Malformed request body missing attributes wrong types etc Request body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required If enabled is set to true a verification request will be sent before saving the configuration If this request receives no response or the response is not successful HTTP 2xx the configuration will not save Key path Type Default Description data type string Must be notification configuration data attributes destination type string Type of notification payload to send Valid values are generic email slack or microsoft teams data attributes enabled bool false Disabled configurations will not send any notifications data attributes name string Human readable name for the configuration data attributes token string or null null Optional write only secure token which can be used at the receiving server to verify request authenticity See Notification Authenticity notification authenticity for more details data attributes triggers array Array of triggers for which this configuration will send notifications See Notification Triggers notification triggers for more details and a list of allowed values data attributes url string HTTP or HTTPS URL to which notification requests will be made only for configurations with destination type slack microsoft teams or generic data relationships users array Array of users part of the organization only for configurations with destination type email notification authenticity notification authenticity notification triggers notification triggers Sample payload for generic notification configurations json data type notification configuration attributes destination type generic enabled true name Webhook server test url https httpstat us 200 triggers run applying run completed run created run errored run needs attention run planning Sample payload for email notification configurations json data type notification configurations attributes destination type email enabled true name Notify organization users about run triggers run applying run completed run created run errored run needs attention run planning relationships users data id organization user id type users Sample request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 workspaces ws XdeUVMWShTesDMME notification configurations Sample response json data id nc AeUQ2zfKZzW9TiGZ type notification configurations attributes enabled true name Webhook server test url https httpstat us 200 destination type generic token null triggers run applying run completed run created run errored run needs attention run planning delivery responses url https httpstat us 200 body 200 OK code 200 headers cache control private content length 129 content type application json charset utf 8 content encoding gzip vary Accept Encoding server Microsoft IIS 10 0 x aspnetmvc version 5 1 access control allow origin x aspnet version 4 0 30319 x powered by ASP NET set cookie ARRAffinity 77c477e3e649643e5771873e1a13179fb00983bc73c71e196bf25967fd453df9 Path HttpOnly Domain httpstat us date Tue 08 Jan 2019 21 34 37 GMT sent at 2019 01 08 21 34 37 UTC successful true created at 2019 01 08T21 32 14 125Z updated at 2019 01 08T21 34 37 274Z relationships subscribable data id ws XdeUVMWShTesDMME type workspaces links self api v2 notification configurations nc AeUQ2zfKZzW9TiGZ List notification configurations Use the following endpoint to list all notification configurations for a workspace GET workspaces workspace id notification configurations Parameter Description workspace id The ID of the workspace to list configurations from Obtain this from the workspace settings terraform cloud docs workspaces settings or the Show Workspace terraform cloud docs api docs workspaces show workspace endpoint If neither pagination query parameters are provided the endpoint will not be paginated and will return all results Query parameters This endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters Remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs Parameter Description page number Optional If omitted the endpoint will return the first page page size Optional If omitted the endpoint will return 20 notification configurations per page Sample request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 workspaces ws XdeUVMWShTesDMME notification configurations Sample response json data id nc W6VGEi8A7Cfoaf4K type notification configurations attributes enabled false name Slack devops url https hooks slack com services T00000000 BC012345 0PWCpQmYyD4bTTRYZ53q4w destination type slack token null triggers run errored run needs attention delivery responses created at 2019 01 08T21 34 28 367Z updated at 2019 01 08T21 34 28 367Z relationships subscribable data id ws XdeUVMWShTesDMME type workspaces links self api v2 notification configurations nc W6VGEi8A7Cfoaf4K id nc AeUQ2zfKZzW9TiGZ type notification configurations attributes enabled true name Webhook server test url https httpstat us 200 destination type generic token null triggers run applying run completed run created run errored run needs attention run planning delivery responses url https httpstat us 200 body 200 OK code 200 headers cache control private content length 129 content type application json charset utf 8 content encoding gzip vary Accept Encoding server Microsoft IIS 10 0 x aspnetmvc version 5 1 access control allow origin x aspnet version 4 0 30319 x powered by ASP NET set cookie ARRAffinity 77c477e3e649643e5771873e1a13179fb00983bc73c71e196bf25967fd453df9 Path HttpOnly Domain httpstat us date Tue 08 Jan 2019 21 34 37 GMT sent at 2019 01 08 21 34 37 UTC successful true created at 2019 01 08T21 32 14 125Z updated at 2019 01 08T21 34 37 274Z relationships subscribable data id ws XdeUVMWShTesDMME type workspaces links self api v2 notification configurations nc AeUQ2zfKZzW9TiGZ Show a notification configuration GET notification configurations notification configuration id Parameter Description notification configuration id The id of the notification configuration to show Sample request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 notification configurations nc AeUQ2zfKZzW9TiGZ Sample response The type and id attributes in relationships subscribable may also reference a teams and team ID respectively json data id nc AeUQ2zfKZzW9TiGZ type notification configurations attributes enabled true name Webhook server test url https httpstat us 200 destination type generic token null triggers run applying run completed run created run errored run needs attention run planning delivery responses url https httpstat us 200 body 200 OK code 200 headers cache control private content length 129 content type application json charset utf 8 content encoding gzip vary Accept Encoding server Microsoft IIS 10 0 x aspnetmvc version 5 1 access control allow origin x aspnet version 4 0 30319 x powered by ASP NET set cookie ARRAffinity 77c477e3e649643e5771873e1a13179fb00983bc73c71e196bf25967fd453df9 Path HttpOnly Domain httpstat us date Tue 08 Jan 2019 21 34 37 GMT sent at 2019 01 08 21 34 37 UTC successful true created at 2019 01 08T21 32 14 125Z updated at 2019 01 08T21 34 37 274Z relationships subscribable data id ws XdeUVMWShTesDMME type workspaces links self api v2 notification configurations nc AeUQ2zfKZzW9TiGZ Update a notification configuration PATCH notification configurations notification configuration id Parameter Description notification configuration id The id of the notification configuration to update If the enabled attribute is true updating the configuration will cause HCP Terraform to send a verification request If a response is received it will be stored and returned in the delivery responses attribute More details in the Notification Verification and Delivery Responses section above Notification Verification and Delivery Responses notification verification and delivery responses Status Response Reason 200 JSON API document type notification configurations Successfully updated the notification configuration 400 JSON API error object Unable to complete verification request to destination URL 404 JSON API error object Notification configuration not found or user unauthorized to perform action 422 JSON API error object Malformed request body missing attributes wrong types etc Request body This PATCH endpoint requires a JSON object with the following properties as a request payload If enabled is set to true a verification request will be sent before saving the configuration If this request fails to send or the response is not successful HTTP 2xx the configuration will not save Key path Type Default Description data type string previous value Must be notification configuration data attributes enabled bool previous value Disabled configurations will not send any notifications data attributes name string previous value User readable name for the configuration data attributes token string previous value Optional write only secure token which can be used at the receiving server to verify request authenticity See Notification Authenticity notification authenticity for more details data attributes triggers array previous value Array of triggers for sending notifications See Notification Triggers notification triggers for more details data attributes url string previous value HTTP or HTTPS URL to which notification requests will be made only for configurations with destination type slack microsoft teams or generic data relationships users array Array of users part of the organization only for configurations with destination type email notification authenticity notification authenticity notification triggers notification triggers Sample payload json data id nc W6VGEi8A7Cfoaf4K type notification configurations attributes enabled false name Slack devops url https hooks slack com services T00000001 BC012345 0PWCpQmYyD4bTTRYZ53q4w destination type slack token null triggers run created run errored run needs attention Sample request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request PATCH data payload json https app terraform io api v2 notification configurations nc W6VGEi8A7Cfoaf4K Sample response json data id nc W6VGEi8A7Cfoaf4K type notification configurations attributes enabled false name Slack devops url https hooks slack com services T00000001 BC012345 0PWCpQmYyD4bTTRYZ53q4w destination type slack token null triggers run created run errored run needs attention delivery responses created at 2019 01 08T21 34 28 367Z updated at 2019 01 08T21 49 02 103Z relationships subscribable data id ws XdeUVMWShTesDMME type workspaces links self api v2 notification configurations nc W6VGEi8A7Cfoaf4K Verify a notification configuration POST notification configurations notification configuration id actions verify Parameter Description notification configuration id The id of the notification configuration to verify This will cause HCP Terraform to send a verification request for the specified configuration If a response is received it will be stored and returned in the delivery responses attribute More details in the Notification Verification and Delivery Responses section above Status Response Reason 200 JSON API document type notification configurations Successfully verified the notification configuration 400 JSON API error object Unable to complete verification request to destination URL Sample request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST https app terraform io api v2 notification configurations nc AeUQ2zfKZzW9TiGZ actions verify Sample response json data id nc AeUQ2zfKZzW9TiGZ type notification configurations attributes enabled true name Webhook server test url https httpstat us 200 destination type generic token null triggers run applying run completed run created run errored run needs attention run planning delivery responses url https httpstat us 200 body 200 OK code 200 headers cache control private content length 129 content type application json charset utf 8 content encoding gzip vary Accept Encoding server Microsoft IIS 10 0 x aspnetmvc version 5 1 access control allow origin x aspnet version 4 0 30319 x powered by ASP NET set cookie ARRAffinity 77c477e3e649643e5771873e1a13179fb00983bc73c71e196bf25967fd453df9 Path HttpOnly Domain httpstat us date Tue 08 Jan 2019 21 34 37 GMT sent at 2019 01 08 21 34 37 UTC successful true created at 2019 01 08T21 32 14 125Z updated at 2019 01 08T21 34 37 274Z relationships subscribable data id ws XdeUVMWShTesDMME type workspaces links self api v2 notification configurations nc AeUQ2zfKZzW9TiGZ Delete a notification configuration This endpoint deletes a notification configuration DELETE notification configurations notification configuration id Parameter Description notification configuration id The id of the notification configuration to delete Status Response Reason 204 None Successfully deleted the notification configuration 404 JSON API error object Notification configuration not found or user unauthorized to perform action Sample request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request DELETE https app terraform io api v2 notification configurations nc AeUQ2zfKZzW9TiGZ Team notification configuration Note Team notifications are in public beta All APIs and workflows are subject to change Team notifications allow you to configure relevant alerts that notify teams you specify whenever a certain event occurs BEGIN TFC only name pnp callout include tfc package callouts notifications mdx END TFC only name pnp callout Create a team notification configuration By default every team has a default email notification configuration with no users assigned If a notification configuration has no users assigned HCP Terraform sends email notifications to all team members Use this endpoint to create a notification configuration to notify a team POST teams team id notification configurations Parameter Description team id The ID of the team to create a configuration for Status Response Reason 201 JSON API document type notification configurations Successfully created a notification configuration 400 JSON API error object Unable to complete verification request to destination URL 404 JSON API error object Team not found or user unauthorized to perform action 422 JSON API error object Malformed request body missing attributes wrong types etc Request body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required If enabled is set to true HCP Terraform sends a verification request before saving the configuration If this request does not receive a response or the response is not successful HTTP 2xx the configuration will not be saved Key path Type Default Description data type string Must be notification configuration data attributes destination type string Type of notification payload to send Valid values are generic email slack or microsoft teams data attributes enabled bool false Disabled configurations will not send any notifications data attributes name string Human readable name for the configuration data attributes token string or null null Optional write only secure token which can be used at the receiving server to verify request authenticity See Notification Authenticity notification authenticity for more details data attributes triggers array Array of triggers for which this configuration will send notifications See Notification Triggers notification triggers for more details and a list of allowed values data attributes url string HTTP or HTTPS URL to which notification requests will be made only for configurations with destination type slack microsoft teams or generic data attributes email all members bool Email all team members only for configurations with destination type email data relationships users array Array of users part of the organization only for configurations with destination type email notification authenticity notification authenticity notification triggers notification triggers Sample payload for generic notification configurations json data type notification configuration attributes destination type generic enabled true name Webhook server test url https httpstat us 200 triggers change request created Sample payload for email notification configurations json data type notification configurations attributes destination type email enabled true name Email teams about change requests triggers change request created relationships users data id organization user id type users Sample request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 teams team 6p5jTwJQXwqZBncC notification configurations Sample response json data id nc AeUQ2zfKZzW9TiGZ type notification configurations attributes enabled true name Webhook server test url https httpstat us 200 destination type generic token null triggers change request created delivery responses url https httpstat us 200 body 200 OK code 200 headers cache control private content length 129 content type application json charset utf 8 content encoding gzip vary Accept Encoding server Microsoft IIS 10 0 x aspnetmvc version 5 1 access control allow origin x aspnet version 4 0 30319 x powered by ASP NET set cookie ARRAffinity 77c477e3e649643e5771873e1a13179fb00983bc73c71e196bf25967fd453df9 Path HttpOnly Domain httpstat us date Tue 08 Jan 2024 21 34 37 GMT sent at 2024 01 08 21 34 37 UTC successful true created at 2024 01 08T21 32 14 125Z updated at 2024 01 08T21 34 37 274Z relationships subscribable data id team 6p5jTwJQXwqZBncC type teams links self api v2 notification configurations nc AeUQ2zfKZzW9TiGZ List team notification configurations Use this endpoint to list notification configurations for a team GET teams team id notification configurations Parameter Description team id The ID of the teams to list configurations from Query Parameters This endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters Remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs Parameter Description page number Optional If omitted the endpoint will return the first page page size Optional If omitted the endpoint will return 20 notification configurations per page Sample request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 teams team 6p5jTwJQXwqZBncC notification configurations Sample response json data id nc W6VGEi8A7Cfoaf4K type notification configurations attributes enabled false name Slack devops url https hooks slack com services T00000000 BC012345 0PWCpQmYyD4bTTRYZ53q4w destination type slack token null triggers change request created delivery responses created at 2019 01 08T21 34 28 367Z updated at 2019 01 08T21 34 28 367Z relationships subscribable data id team TdeUVMWShTesDMME type teams links self api v2 notification configurations nc W6VGEi8A7Cfoaf4K id nc AeUQ2zfKZzW9TiGZ type notification configurations attributes enabled true name Webhook server test url https httpstat us 200 destination type generic token null triggers change request created delivery responses url https httpstat us 200 body 200 OK code 200 headers cache control private content length 129 content type application json charset utf 8 content encoding gzip vary Accept Encoding server Microsoft IIS 10 0 x aspnetmvc version 5 1 access control allow origin x aspnet version 4 0 30319 x powered by ASP NET set cookie ARRAffinity 77c477e3e649643e5771873e1a13179fb00983bc73c71e196bf25967fd453df9 Path HttpOnly Domain httpstat us date Tue 08 Jan 2019 21 34 37 GMT sent at 2019 01 08 21 34 37 UTC successful true created at 2019 01 08T21 32 14 125Z updated at 2019 01 08T21 34 37 274Z relationships subscribable data id team XdeUVMWShTesDMME type teams links self api v2 notification configurations nc AeUQ2zfKZzW9TiGZ
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 page title Plans API Docs HCP Terraform Use the plans endpoint to access Terraform run plans Show a plan and get the JSON formatted execution plan using the HTTP API
--- page_title: Plans - API Docs - HCP Terraform description: >- Use the `/plans` endpoint to access Terraform run plans. Show a plan and get the JSON-formatted execution plan using the HTTP API. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [307]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/307 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # Plans API A plan represents the execution plan of a Run in a Terraform workspace. ## Attributes ### Plan States The plan state is found in `data.attributes.status`, and you can reference the following list of possible states. | State | Description | | ------------------------- | ----------------------------------------------------------------------------- | | `pending` | The initial status of a plan once it has been created. | | `managed_queued`/`queued` | The plan has been queued, awaiting backend service capacity to run terraform. | | `running` | The plan is running. | | `errored` | The plan has errored. This is a final state. | | `canceled` | The plan has been canceled. This is a final state. | | `finished` | The plan has completed successfully. This is a final state. | | `unreachable` | The plan will not run. This is a final state. | ## Show a plan `GET /plans/:id` | Parameter | Description | | --------- | --------------------------- | | `id` | The ID of the plan to show. | There is no endpoint to list plans. You can find the ID for a plan in the `relationships.plan` property of a run object. | Status | Response | Reason | | ------- | --------------------------------------- | ------------------------------------------------------ | | [200][] | [JSON API document][] (`type: "plans"`) | The request was successful | | [404][] | [JSON API error object][] | Plan not found, or user unauthorized to perform action | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/plans/plan-8F5JFydVYAmtTjET ``` ### Sample Response ```json { "data": { "id": "plan-8F5JFydVYAmtTjET", "type": "plans", "attributes": { "execution-details": { "mode": "remote", }, "generated-configuration": false, "has-changes": true, "resource-additions": 0, "resource-changes": 1, "resource-destructions": 0, "resource-imports": 0, "status": "finished", "status-timestamps": { "queued-at": "2018-07-02T22:29:53+00:00", "pending-at": "2018-07-02T22:29:53+00:00", "started-at": "2018-07-02T22:29:54+00:00", "finished-at": "2018-07-02T22:29:58+00:00" }, "log-read-url": "https://archivist.terraform.io/v1/object/dmF1bHQ6djE6OFA1eEdlSFVHRSs4YUcwaW83a1dRRDA0U2E3T3FiWk1HM2NyQlNtcS9JS1hHN3dmTXJmaFhEYTlHdTF1ZlgxZ2wzVC9kVTlNcjRPOEJkK050VFI3U3dvS2ZuaUhFSGpVenJVUFYzSFVZQ1VZYno3T3UyYjdDRVRPRE5pbWJDVTIrNllQTENyTndYd1Y0ak1DL1dPVlN1VlNxKzYzbWlIcnJPa2dRRkJZZGtFeTNiaU84YlZ4QWs2QzlLY3VJb3lmWlIrajF4a1hYZTlsWnFYemRkL2pNOG9Zc0ZDakdVMCtURUE3dDNMODRsRnY4cWl1dUN5dUVuUzdnZzFwL3BNeHlwbXNXZWRrUDhXdzhGNnF4c3dqaXlZS29oL3FKakI5dm9uYU5ZKzAybnloREdnQ3J2Rk5WMlBJemZQTg" }, "relationships": { "state-versions": { "data": [] } }, "links": { "self": "/api/v2/plans/plan-8F5JFydVYAmtTjET", "json-output": "/api/v2/plans/plan-8F5JFydVYAmtTjET/json-output" } } } ``` _Using HCP Terraform agents_ [HCP Terraform agents](/terraform/cloud-docs/api-docs/agents) allow HCP Terraform to communicate with isolated, private, or on-premises infrastructure. When a workspace is set to use the agent execution mode, the plan response will include additional details about the agent pool and agent used. ```json { "data": { "id": "plan-8F5JFydVYAmtTjET", "type": "plans", "attributes": { "execution-details": { "agent-id": "agent-S1Y7tcKxXPJDQAvq", "agent-name": "agent_01", "agent-pool-id": "apool-Zigq2VGreKq7nwph", "agent-pool-name": "first-pool", "mode": "agent", }, "generated-configuration": false, "has-changes": true, "resource-additions": 0, "resource-changes": 1, "resource-destructions": 0, "resource-imports": 0, "status": "finished", "status-timestamps": { "queued-at": "2018-07-02T22:29:53+00:00", "pending-at": "2018-07-02T22:29:53+00:00", "started-at": "2018-07-02T22:29:54+00:00", "finished-at": "2018-07-02T22:29:58+00:00" }, "log-read-url": "https://archivist.terraform.io/v1/object/dmF1bHQ6djE6OFA1eEdlSFVHRSs4YUcwaW83a1dRRDA0U2E3T3FiWk1HM2NyQlNtcS9JS1hHN3dmTXJmaFhEYTlHdTF1ZlgxZ2wzVC9kVTlNcjRPOEJkK050VFI3U3dvS2ZuaUhFSGpVenJVUFYzSFVZQ1VZYno3T3UyYjdDRVRPRE5pbWJDVTIrNllQTENyTndYd1Y0ak1DL1dPVlN1VlNxKzYzbWlIcnJPa2dRRkJZZGtFeTNiaU84YlZ4QWs2QzlLY3VJb3lmWlIrajF4a1hYZTlsWnFYemRkL2pNOG9Zc0ZDakdVMCtURUE3dDNMODRsRnY4cWl1dUN5dUVuUzdnZzFwL3BNeHlwbXNXZWRrUDhXdzhGNnF4c3dqaXlZS29oL3FKakI5dm9uYU5ZKzAybnloREdnQ3J2Rk5WMlBJemZQTg" }, "relationships": { "state-versions": { "data": [] } }, "links": { "self": "/api/v2/plans/plan-8F5JFydVYAmtTjET", "json-output": "/api/v2/plans/plan-8F5JFydVYAmtTjET/json-output" } } } ``` ## Retrieve the JSON execution plan `GET /plans/:id/json-output` `GET /runs/:id/plan/json-output` These endpoints generate a temporary authenticated URL to the location of the [JSON formatted execution plan](/terraform/internals/json-format#format-summary). When successful, this endpoint responds with a temporary redirect that should be followed. If using a client that can follow redirects, you can use this endpoint to save the `.json` file locally without needing to save the temporary URL. This temporary URL provided by the redirect has a life of **1 minute**, and should not be relied upon beyond the initial request. If you need repeat access, you should use this endpoint to generate a new URL each time. -> **Note:** This endpoint is available for plans using Terraform 0.12 and later. For Terraform Enterprise, this endpoint is available from v202005-1, and its stability was improved in v202007-1. -> **Note:** This endpoint cannot be accessed with [organization tokens](/terraform/cloud-docs/users-teams-organizations/api-tokens#organization-api-tokens). You must access it with a [user token](/terraform/cloud-docs/users-teams-organizations/users#api-tokens) or [team token](/terraform/cloud-docs/users-teams-organizations/api-tokens#team-api-tokens) that has admin level access to the workspace. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) [permissions-citation]: #intentionally-unused---keep-for-maintainers | Status | Response | Reason | | ------- | ------------------------- | ------------------------------------------------------------- | | [204][] | No Content | Plan JSON supported, but plan has not yet completed. | | [307][] | Temporary Redirect | Plan JSON found and temporary download URL generated | | [422][] | [JSON API error object][] | Plan does not use a supported version of terraform (< 0.12.X) | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --location \ https://app.terraform.io/api/v2/plans/plan-8F5JFydVYAmtTjET/json-output | > json-output.json ```
terraform
page title Plans API Docs HCP Terraform description Use the plans endpoint to access Terraform run plans Show a plan and get the JSON formatted execution plan using the HTTP API 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 307 https developer mozilla org en US docs Web HTTP Status 307 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects Plans API A plan represents the execution plan of a Run in a Terraform workspace Attributes Plan States The plan state is found in data attributes status and you can reference the following list of possible states State Description pending The initial status of a plan once it has been created managed queued queued The plan has been queued awaiting backend service capacity to run terraform running The plan is running errored The plan has errored This is a final state canceled The plan has been canceled This is a final state finished The plan has completed successfully This is a final state unreachable The plan will not run This is a final state Show a plan GET plans id Parameter Description id The ID of the plan to show There is no endpoint to list plans You can find the ID for a plan in the relationships plan property of a run object Status Response Reason 200 JSON API document type plans The request was successful 404 JSON API error object Plan not found or user unauthorized to perform action Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 plans plan 8F5JFydVYAmtTjET Sample Response json data id plan 8F5JFydVYAmtTjET type plans attributes execution details mode remote generated configuration false has changes true resource additions 0 resource changes 1 resource destructions 0 resource imports 0 status finished status timestamps queued at 2018 07 02T22 29 53 00 00 pending at 2018 07 02T22 29 53 00 00 started at 2018 07 02T22 29 54 00 00 finished at 2018 07 02T22 29 58 00 00 log read url https archivist terraform io v1 object dmF1bHQ6djE6OFA1eEdlSFVHRSs4YUcwaW83a1dRRDA0U2E3T3FiWk1HM2NyQlNtcS9JS1hHN3dmTXJmaFhEYTlHdTF1ZlgxZ2wzVC9kVTlNcjRPOEJkK050VFI3U3dvS2ZuaUhFSGpVenJVUFYzSFVZQ1VZYno3T3UyYjdDRVRPRE5pbWJDVTIrNllQTENyTndYd1Y0ak1DL1dPVlN1VlNxKzYzbWlIcnJPa2dRRkJZZGtFeTNiaU84YlZ4QWs2QzlLY3VJb3lmWlIrajF4a1hYZTlsWnFYemRkL2pNOG9Zc0ZDakdVMCtURUE3dDNMODRsRnY4cWl1dUN5dUVuUzdnZzFwL3BNeHlwbXNXZWRrUDhXdzhGNnF4c3dqaXlZS29oL3FKakI5dm9uYU5ZKzAybnloREdnQ3J2Rk5WMlBJemZQTg relationships state versions data links self api v2 plans plan 8F5JFydVYAmtTjET json output api v2 plans plan 8F5JFydVYAmtTjET json output Using HCP Terraform agents HCP Terraform agents terraform cloud docs api docs agents allow HCP Terraform to communicate with isolated private or on premises infrastructure When a workspace is set to use the agent execution mode the plan response will include additional details about the agent pool and agent used json data id plan 8F5JFydVYAmtTjET type plans attributes execution details agent id agent S1Y7tcKxXPJDQAvq agent name agent 01 agent pool id apool Zigq2VGreKq7nwph agent pool name first pool mode agent generated configuration false has changes true resource additions 0 resource changes 1 resource destructions 0 resource imports 0 status finished status timestamps queued at 2018 07 02T22 29 53 00 00 pending at 2018 07 02T22 29 53 00 00 started at 2018 07 02T22 29 54 00 00 finished at 2018 07 02T22 29 58 00 00 log read url https archivist terraform io v1 object dmF1bHQ6djE6OFA1eEdlSFVHRSs4YUcwaW83a1dRRDA0U2E3T3FiWk1HM2NyQlNtcS9JS1hHN3dmTXJmaFhEYTlHdTF1ZlgxZ2wzVC9kVTlNcjRPOEJkK050VFI3U3dvS2ZuaUhFSGpVenJVUFYzSFVZQ1VZYno3T3UyYjdDRVRPRE5pbWJDVTIrNllQTENyTndYd1Y0ak1DL1dPVlN1VlNxKzYzbWlIcnJPa2dRRkJZZGtFeTNiaU84YlZ4QWs2QzlLY3VJb3lmWlIrajF4a1hYZTlsWnFYemRkL2pNOG9Zc0ZDakdVMCtURUE3dDNMODRsRnY4cWl1dUN5dUVuUzdnZzFwL3BNeHlwbXNXZWRrUDhXdzhGNnF4c3dqaXlZS29oL3FKakI5dm9uYU5ZKzAybnloREdnQ3J2Rk5WMlBJemZQTg relationships state versions data links self api v2 plans plan 8F5JFydVYAmtTjET json output api v2 plans plan 8F5JFydVYAmtTjET json output Retrieve the JSON execution plan GET plans id json output GET runs id plan json output These endpoints generate a temporary authenticated URL to the location of the JSON formatted execution plan terraform internals json format format summary When successful this endpoint responds with a temporary redirect that should be followed If using a client that can follow redirects you can use this endpoint to save the json file locally without needing to save the temporary URL This temporary URL provided by the redirect has a life of 1 minute and should not be relied upon beyond the initial request If you need repeat access you should use this endpoint to generate a new URL each time Note This endpoint is available for plans using Terraform 0 12 and later For Terraform Enterprise this endpoint is available from v202005 1 and its stability was improved in v202007 1 Note This endpoint cannot be accessed with organization tokens terraform cloud docs users teams organizations api tokens organization api tokens You must access it with a user token terraform cloud docs users teams organizations users api tokens or team token terraform cloud docs users teams organizations api tokens team api tokens that has admin level access to the workspace More about permissions terraform cloud docs users teams organizations permissions permissions citation intentionally unused keep for maintainers Status Response Reason 204 No Content Plan JSON supported but plan has not yet completed 307 Temporary Redirect Plan JSON found and temporary download URL generated 422 JSON API error object Plan does not use a supported version of terraform 0 12 X Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json location https app terraform io api v2 plans plan 8F5JFydVYAmtTjET json output json output json
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 Learn about API authentication response codes versioning formatting rate limiting and clients page title API Docs HCP Terraform 201 https developer mozilla org en US docs Web HTTP Status 201
--- page_title: API Docs - HCP Terraform description: >- Learn about API authentication, response codes, versioning, formatting, rate limiting, and clients. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # HCP Terraform API Documentation HCP Terraform provides an API for a subset of its features. If you have any questions or want to request new API features, please email <[email protected]>. -> **Note:** Before planning an API integration, consider whether [the `tfe` Terraform provider](https://registry.terraform.io/providers/hashicorp/tfe/latest/docs) meets your needs. It can't create or approve runs in response to arbitrary events, but it's a useful tool for managing your organizations, teams, and workspaces as code. HashiCorp provides a [stability policy](/terraform/cloud-docs/api-docs/stability-policy) for the HCP Terraform API, ensuring backwards compatibility for stable endpoints. The [changelog](/terraform/cloud-docs/api-docs/changelog) tracks changes to the API for HCP Terraform and Terraform Enterprise. ## Authentication All requests must be authenticated with a bearer token. Use the HTTP header `Authorization` with the value `Bearer <token>`. If the token is absent or invalid, HCP Terraform responds with [HTTP status 401][401] and a [JSON API error object][]. The 401 status code is reserved for problems with the authentication token; forbidden requests with a valid token result in a 404. You can use the following types of tokens to authenticate: - [User tokens](/terraform/cloud-docs/users-teams-organizations/users#api-tokens) — each HCP Terraform user can have any number of API tokens, which can make requests on their behalf. - [Team tokens](/terraform/cloud-docs/users-teams-organizations/api-tokens#team-api-tokens) — each team can have one API token at a time. This is intended for performing plans and applies via a CI/CD pipeline. - [Organization tokens](/terraform/cloud-docs/users-teams-organizations/api-tokens#organization-api-tokens) — each organization can have one API token at a time. This is intended for automating the management of teams, team membership, and workspaces. The organization token cannot perform plans and applies. <!-- BEGIN: TFC:only --> - [Audit trails token](/terraform/cloud-docs/users-teams-organizations/api-tokens#audit-trails-tokens) - each organization can have a single token that can read that organization's audit trails. Use this token type to authenticate integrations pulling audit trail data, for example, using the [HCP Terraform for Splunk](/terraform/cloud-docs/integrations/splunk) app. <!-- END: TFC:only --> ### Blob Storage Authentication HCP Terraform relies on a HashiCorp-developed blob storage service for storing statefiles and multiple other pieces of customer data, all of which are documented on our [data security page](/terraform/cloud-docs/architectural-details/data-security). Unlike the HCP Terraform API, this service does not require that a bearer token be submitted with each request. Instead, each URL includes a securely generated secret and is only valid for 25 hours. For example, the [state versions api](/terraform/cloud-docs/api-docs/state-versions) returns a field named `hosted-state-download`, which is a URL of this form: `https://archivist.terraform.io/v1/object/<secret value>` This is a broadly accepted pattern for secure access. It is important to treat these URLs themselves as secrets. They should not be logged, nor shared with untrusted parties. ## Feature Entitlements HCP Terraform is available at multiple pricing tiers (including free), which offer different feature sets. Each organization has a set of _entitlements_ that corresponds to its pricing tier. These entitlements determine which HCP Terraform features the organization can use. If an organization doesn't have the necessary entitlement to use a given feature, HCP Terraform returns a 404 error for API requests to any endpoints devoted to that feature. The [show entitlement set](/terraform/cloud-docs/api-docs/organizations#show-the-entitlement-set) endpoint can return information about an organization's current entitlements, which is useful if your client needs to change its interface when a given feature isn't available. The following entitlements are available: - `agents` — Allows isolated, private or on-premises infrastructure to communicate with an organization in HCP Terraform. Affects the [agent pools][], [agents][], and [agent tokens][] endpoints. <!-- BEGIN: TFC:only name:tfc-audit-log --> - `audit-logging` — Allows an organization to access [audit trails][]. <!-- END: TFC:only name:tfc-audit-log --> - `configuration-designer` — Allows an organization to use the [Configuration Designer][]. - `cost-estimation` — Allows an organization to access [cost estimation][]. - `global-run-tasks` — Allows an organization to apply [run tasks](/terraform/cloud-docs/workspaces/settings/run-tasks) to every workspace. Affects the [run tasks][] endpoints. This feature is currently in beta. - `module-tests-generation` - Allows an organization to generate tests for private registry modules. This feature is currently in beta. - `operations` — Allows an organization to perform runs within HCP Terraform. Affects the [runs][], [plans][], and [applies][] endpoints. - `policy-enforcement` — Allows an organization to use [Sentinel][]. Affects the [policies][], [policy sets][], and [policy checks][] endpoints. - `private-module-registry` — Allows an organization to publish and use modules with the [private module registry][]. Affects the [registry modules][] endpoints. - `private-policy-agents` - Allows an organization to ensure that HTTP enabled [Sentinel][] and OPA [policies][] can communicate with isolated, private, or on-premises infrastructure. - `run-tasks` — Allows an organization to use [run tasks](/terraform/cloud-docs/workspaces/settings/run-tasks). Affects the [run tasks][] endpoints. - `self-serve-billing` — Allows an organization to pay via credit card using the in-app billing UI. - `sentinel` - **DEPRECATED** Use `policy-enforcement` instead. - `state-storage` — Allows an organization to store state versions in its workspaces, which enables local Terraform runs with HCP Terraform. Affects the [state versions][] endpoints. - `sso` — Allows an organization to manage and authenticate users with single sign on. - `teams` — Allows an organization to manage access to its workspaces with [teams](/terraform/cloud-docs/users-teams-organizations/teams). Without this entitlement, an organization only has an owners team. Affects the [teams][], [team members][], [team access][], and [team tokens][] endpoints. - `user-limit` — An integer value representing the maximum number of users allowed for the organization. If blank, there is no limit. - `vcs-integrations` — Allows an organization to [connect with a VCS provider][vcs integrations] and link VCS repositories to workspaces. Affects the [OAuth Clients][o-clients], and [OAuth Tokens][o-tokens] endpoints, and determines whether the `data.attributes.vcs-repo` property can be set for [workspaces][]. [agents]: /terraform/cloud-docs/api-docs/agents [agent pools]: /terraform/cloud-docs/api-docs/agents [agent tokens]: /terraform/cloud-docs/api-docs/agent-tokens [applies]: /terraform/cloud-docs/api-docs/applies <!-- BEGIN: TFC:only name:tfc-audit-log --> [audit trails]: /terraform/cloud-docs/api-docs/audit-trails <!-- END: TFC:only name:tfc-audit-log --> [Configuration Designer]: /terraform/cloud-docs/registry/design [cost estimation]: /terraform/cloud-docs/cost-estimation [o-clients]: /terraform/cloud-docs/api-docs/oauth-clients [o-tokens]: /terraform/cloud-docs/api-docs/oauth-tokens [plans]: /terraform/cloud-docs/api-docs/plans [policies]: /terraform/cloud-docs/api-docs/policies [policy checks]: /terraform/cloud-docs/api-docs/policy-checks [policy sets]: /terraform/cloud-docs/api-docs/policy-sets [private module registry]: /terraform/cloud-docs/registry [registry modules]: /terraform/cloud-docs/api-docs/private-registry/modules [registry providers]: /terraform/cloud-docs/api-docs/private-registry/providers [runs]: /terraform/cloud-docs/api-docs/run [run tasks]: /terraform/cloud-docs/api-docs/run-tasks/run-tasks [Sentinel]: /terraform/cloud-docs/policy-enforcement/sentinel [single sign on]: /terraform/cloud-docs/users-teams-organizations/single-sign-on [state versions]: /terraform/cloud-docs/api-docs/state-versions [teams]: /terraform/cloud-docs/api-docs/teams [team access]: /terraform/cloud-docs/api-docs/team-access [team members]: /terraform/cloud-docs/api-docs/team-members [team tokens]: /terraform/cloud-docs/api-docs/team-tokens [vcs integrations]: /terraform/cloud-docs/vcs [workspaces]: /terraform/cloud-docs/api-docs/workspaces ## Response Codes This API returns standard HTTP response codes. We return 404 Not Found codes for resources that a user doesn't have access to, as well as for resources that don't exist. This is to avoid telling a potential attacker that a given resource exists. ## Versioning The API documented in these pages is the second version of HCP Terraform's API, and resides under the `/v2` prefix. Future APIs will increment this version, leaving the `/v1` API intact, though in the future we might deprecate certain features. In that case, we'll provide ample notice to migrate to the new API. ## Paths All V2 API endpoints use `/api/v2` as a prefix unless otherwise specified. For example, if the API endpoint documentation defines the path `/runs` then the full path is `/api/v2/runs`. ## JSON API Formatting The HCP Terraform endpoints use the [JSON API specification](https://jsonapi.org/), which specifies key aspects of the API. Most notably: - [HTTP error codes](https://jsonapi.org/examples/#error-objects-error-codes) - [Error objects](https://jsonapi.org/examples/#error-objects-basics) - [Document structure][document] - [HTTP request/response headers](https://jsonapi.org/format/#content-negotiation) [document]: https://jsonapi.org/format/#document-structure ### JSON API Documents Since our API endpoints use the JSON API spec, most of them return [JSON API documents][document]. Endpoints that use the POST method also require a JSON API document as the request payload. A request object usually looks something like this: ```json { "data": { "type":"vars", "attributes": { "key":"some_key", "value":"some_value", "category":"terraform", "hcl":false, "sensitive":false }, "relationships": { "workspace": { "data": { "id":"ws-4j8p6jX1w33MiDC7", "type":"workspaces" } } } } } ``` These objects always include a top-level `data` property, which: - Must have a `type` property to indicate what type of API object you're interacting with. - Often has an `attributes` property to specify attributes of the object you're creating or modifying. - Sometimes has a `relationships` property to specify other objects that are linked to what you're working with. In the documentation for each API method, we use dot notation to explain the structure of nested objects in the request. For example, the properties of the request object above are listed as follows: | Key path | Type | Default | Description | | ---------------------------------------- | ------ | ------- | --------------------------------------------------------------------------------------------------------------- | | `data.type` | string | | Must be `"vars"`. | | `data.attributes.key` | string | | The name of the variable. | | `data.attributes.value` | string | | The value of the variable. | | `data.attributes.category` | string | | Whether this is a Terraform or environment variable. Valid values are `"terraform"` or `"env"`. | | `data.attributes.hcl` | bool | `false` | Whether to evaluate the value of the variable as a string of HCL code. Has no effect for environment variables. | | `data.attributes.sensitive` | bool | `false` | Whether the value is sensitive. If true then the variable is written once and not visible thereafter. | | `data.relationships.workspace.data.type` | string | | Must be `"workspaces"`. | | `data.relationships.workspace.data.id` | string | | The ID of the workspace that owns the variable. | We also always include a sample payload object, to show the document structure more visually. ### Query Parameters Although most of our API endpoints use the POST method and receive their parameters as a JSON object in the request payload, some of them use the GET method. These GET endpoints sometimes require URL query parameters, in the standard `...path?key1=value1&key2=value2` format. Since these parameters were originally designed as part of a JSON object, they sometimes have characters that must be [percent-encoded](https://en.wikipedia.org/wiki/Percent-encoding) in a query parameter. For example, `[` becomes `%5B` and `]` becomes `%5D`. For more about URI structure and query strings, see [the specification (RFC 3986)](https://tools.ietf.org/html/rfc3986) or [the Wikipedia page on URIs](https://en.wikipedia.org/wiki/Uniform_Resource_Identifier). ### Pagination Most of the endpoints that return lists of objects support pagination. A client may pass the following query parameters to control pagination on supported endpoints: | Parameter | Description | | -------------- | --------------------------------------------------------------------------------------------------- | | `page[number]` | **Optional.** If omitted, the endpoint will return the first page. | | `page[size]` | **Optional.** If omitted, the endpoint will return 20 items per page. The maximum page size is 100. | Additional data is returned in the `links` and `meta` top level attributes of the response. ```json { "data": [...], "links": { "self": "https://app.terraform.io/api/v2/organizations/hashicorp/workspaces?page%5Bnumber%5D=1&page%5Bsize%5D=20", "first": "https://app.terraform.io/api/v2/organizations/hashicorp/workspaces?page%5Bnumber%5D=1&page%5Bsize%5D=20", "prev": null, "next": "https://app.terraform.io/api/v2/organizations/hashicorp/workspaces?page%5Bnumber%5D=2&page%5Bsize%5D=20", "last": "https://app.terraform.io/api/v2/organizations/hashicorp/workspaces?page%5Bnumber%5D=2&page%5Bsize%5D=20" }, "meta": { "pagination": { "current-page": 1, "prev-page": null, "next-page": 2, "total-pages": 2, "total-count": 21 } } } ``` ### Inclusion of Related Resources Some of the API's GET endpoints can return additional information about nested resources by adding an `include` query parameter, whose value is a comma-separated list of resource types. The related resource options are listed in each endpoint's documentation where available. The related resources will appear in an `included` section of the response. Example: ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/teams/team-n8UQ6wfhyym25sMe?include=users ``` ```json { "data": { "id": "team-n8UQ6wfhyym25sMe", "type": "teams", "attributes": { "name": "owners", "users-count": 1 ... }, "relationships": { "users": { "data": [ { "id": "user-62goNpx1ThQf689e", "type": "users" } ] } ... } ... }, "included": [ { "id": "user-62goNpx1ThQf689e", "type": "users", "attributes": { "username": "hashibot" ... } ... } ] } ``` ## Rate Limiting You can make up to 30 requests per second to the API as an authenticated or unauthenticated request. If you reach the rate limit then your access will be throttled and an error response will be returned. Some endpoints have lower rate limits to prevent abuse, including endpoints that poll Terraform for a list of runs and endpoints related to user authentication. The adjusted limits are unnoticeable under normal use. If you receive a rate-limited response, the limit is reflected in the `x-ratelimit-limit` header once triggered. Authenticated requests are allocated to the user associated with the authentication token. This means that a user with multiple tokens will still be limited to 30 requests per second, additional tokens will not allow you to increase the requests per second permitted. Unauthenticated requests are associated with the requesting IP address. | Status | Response | Reason | | ------- | ------------------------- | ---------------------------- | | [429][] | [JSON API error object][] | Rate limit has been reached. | ```json { "errors": [ { "detail": "You have exceeded the API's rate limit.", "status": 429, "title": "Too many requests" } ] } ``` ## Client libraries and tools HashiCorp maintains [go-tfe](https://github.com/hashicorp/go-tfe), a Go client for HCP Terraform's API. Additionally, the community of HCP Terraform users and vendors have built client libraries in other languages. These client libraries and tools are not tested nor officially maintained by HashiCorp, but are listed below in order to help users find them easily. If you have built a client library and would like to add it to this community list, please [contribute](https://github.com/hashicorp/terraform-website#contributions-welcome) to [this page](https://github.com/hashicorp/terraform-docs-common/blob/main/website/docs/cloud-docs/api-docs/index.mdx#client-libraries-and-tools). - [tfh](https://github.com/hashicorp-community/tf-helper): UNIX shell console app - [tf_api_gateway](https://github.com/PlethoraOfHate/tf_api_gateway): Python API library and console app - [terrasnek](https://github.com/dahlke/terrasnek): Python API library - [terraform-enterprise-client](https://github.com/skierkowski/terraform-enterprise-client): Ruby API library and console app - [pyterprise](https://github.com/JFryy/terraform-enterprise-api-python-client): A simple Python API client library. - [Tfe.NetClient](https://github.com/everis-technology/Tfe.NetClient): .NET Client Library
terraform
page title API Docs HCP Terraform description Learn about API authentication response codes versioning formatting rate limiting and clients 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects HCP Terraform API Documentation HCP Terraform provides an API for a subset of its features If you have any questions or want to request new API features please email support hashicorp com Note Before planning an API integration consider whether the tfe Terraform provider https registry terraform io providers hashicorp tfe latest docs meets your needs It can t create or approve runs in response to arbitrary events but it s a useful tool for managing your organizations teams and workspaces as code HashiCorp provides a stability policy terraform cloud docs api docs stability policy for the HCP Terraform API ensuring backwards compatibility for stable endpoints The changelog terraform cloud docs api docs changelog tracks changes to the API for HCP Terraform and Terraform Enterprise Authentication All requests must be authenticated with a bearer token Use the HTTP header Authorization with the value Bearer token If the token is absent or invalid HCP Terraform responds with HTTP status 401 401 and a JSON API error object The 401 status code is reserved for problems with the authentication token forbidden requests with a valid token result in a 404 You can use the following types of tokens to authenticate User tokens terraform cloud docs users teams organizations users api tokens each HCP Terraform user can have any number of API tokens which can make requests on their behalf Team tokens terraform cloud docs users teams organizations api tokens team api tokens each team can have one API token at a time This is intended for performing plans and applies via a CI CD pipeline Organization tokens terraform cloud docs users teams organizations api tokens organization api tokens each organization can have one API token at a time This is intended for automating the management of teams team membership and workspaces The organization token cannot perform plans and applies BEGIN TFC only Audit trails token terraform cloud docs users teams organizations api tokens audit trails tokens each organization can have a single token that can read that organization s audit trails Use this token type to authenticate integrations pulling audit trail data for example using the HCP Terraform for Splunk terraform cloud docs integrations splunk app END TFC only Blob Storage Authentication HCP Terraform relies on a HashiCorp developed blob storage service for storing statefiles and multiple other pieces of customer data all of which are documented on our data security page terraform cloud docs architectural details data security Unlike the HCP Terraform API this service does not require that a bearer token be submitted with each request Instead each URL includes a securely generated secret and is only valid for 25 hours For example the state versions api terraform cloud docs api docs state versions returns a field named hosted state download which is a URL of this form https archivist terraform io v1 object secret value This is a broadly accepted pattern for secure access It is important to treat these URLs themselves as secrets They should not be logged nor shared with untrusted parties Feature Entitlements HCP Terraform is available at multiple pricing tiers including free which offer different feature sets Each organization has a set of entitlements that corresponds to its pricing tier These entitlements determine which HCP Terraform features the organization can use If an organization doesn t have the necessary entitlement to use a given feature HCP Terraform returns a 404 error for API requests to any endpoints devoted to that feature The show entitlement set terraform cloud docs api docs organizations show the entitlement set endpoint can return information about an organization s current entitlements which is useful if your client needs to change its interface when a given feature isn t available The following entitlements are available agents Allows isolated private or on premises infrastructure to communicate with an organization in HCP Terraform Affects the agent pools agents and agent tokens endpoints BEGIN TFC only name tfc audit log audit logging Allows an organization to access audit trails END TFC only name tfc audit log configuration designer Allows an organization to use the Configuration Designer cost estimation Allows an organization to access cost estimation global run tasks Allows an organization to apply run tasks terraform cloud docs workspaces settings run tasks to every workspace Affects the run tasks endpoints This feature is currently in beta module tests generation Allows an organization to generate tests for private registry modules This feature is currently in beta operations Allows an organization to perform runs within HCP Terraform Affects the runs plans and applies endpoints policy enforcement Allows an organization to use Sentinel Affects the policies policy sets and policy checks endpoints private module registry Allows an organization to publish and use modules with the private module registry Affects the registry modules endpoints private policy agents Allows an organization to ensure that HTTP enabled Sentinel and OPA policies can communicate with isolated private or on premises infrastructure run tasks Allows an organization to use run tasks terraform cloud docs workspaces settings run tasks Affects the run tasks endpoints self serve billing Allows an organization to pay via credit card using the in app billing UI sentinel DEPRECATED Use policy enforcement instead state storage Allows an organization to store state versions in its workspaces which enables local Terraform runs with HCP Terraform Affects the state versions endpoints sso Allows an organization to manage and authenticate users with single sign on teams Allows an organization to manage access to its workspaces with teams terraform cloud docs users teams organizations teams Without this entitlement an organization only has an owners team Affects the teams team members team access and team tokens endpoints user limit An integer value representing the maximum number of users allowed for the organization If blank there is no limit vcs integrations Allows an organization to connect with a VCS provider vcs integrations and link VCS repositories to workspaces Affects the OAuth Clients o clients and OAuth Tokens o tokens endpoints and determines whether the data attributes vcs repo property can be set for workspaces agents terraform cloud docs api docs agents agent pools terraform cloud docs api docs agents agent tokens terraform cloud docs api docs agent tokens applies terraform cloud docs api docs applies BEGIN TFC only name tfc audit log audit trails terraform cloud docs api docs audit trails END TFC only name tfc audit log Configuration Designer terraform cloud docs registry design cost estimation terraform cloud docs cost estimation o clients terraform cloud docs api docs oauth clients o tokens terraform cloud docs api docs oauth tokens plans terraform cloud docs api docs plans policies terraform cloud docs api docs policies policy checks terraform cloud docs api docs policy checks policy sets terraform cloud docs api docs policy sets private module registry terraform cloud docs registry registry modules terraform cloud docs api docs private registry modules registry providers terraform cloud docs api docs private registry providers runs terraform cloud docs api docs run run tasks terraform cloud docs api docs run tasks run tasks Sentinel terraform cloud docs policy enforcement sentinel single sign on terraform cloud docs users teams organizations single sign on state versions terraform cloud docs api docs state versions teams terraform cloud docs api docs teams team access terraform cloud docs api docs team access team members terraform cloud docs api docs team members team tokens terraform cloud docs api docs team tokens vcs integrations terraform cloud docs vcs workspaces terraform cloud docs api docs workspaces Response Codes This API returns standard HTTP response codes We return 404 Not Found codes for resources that a user doesn t have access to as well as for resources that don t exist This is to avoid telling a potential attacker that a given resource exists Versioning The API documented in these pages is the second version of HCP Terraform s API and resides under the v2 prefix Future APIs will increment this version leaving the v1 API intact though in the future we might deprecate certain features In that case we ll provide ample notice to migrate to the new API Paths All V2 API endpoints use api v2 as a prefix unless otherwise specified For example if the API endpoint documentation defines the path runs then the full path is api v2 runs JSON API Formatting The HCP Terraform endpoints use the JSON API specification https jsonapi org which specifies key aspects of the API Most notably HTTP error codes https jsonapi org examples error objects error codes Error objects https jsonapi org examples error objects basics Document structure document HTTP request response headers https jsonapi org format content negotiation document https jsonapi org format document structure JSON API Documents Since our API endpoints use the JSON API spec most of them return JSON API documents document Endpoints that use the POST method also require a JSON API document as the request payload A request object usually looks something like this json data type vars attributes key some key value some value category terraform hcl false sensitive false relationships workspace data id ws 4j8p6jX1w33MiDC7 type workspaces These objects always include a top level data property which Must have a type property to indicate what type of API object you re interacting with Often has an attributes property to specify attributes of the object you re creating or modifying Sometimes has a relationships property to specify other objects that are linked to what you re working with In the documentation for each API method we use dot notation to explain the structure of nested objects in the request For example the properties of the request object above are listed as follows Key path Type Default Description data type string Must be vars data attributes key string The name of the variable data attributes value string The value of the variable data attributes category string Whether this is a Terraform or environment variable Valid values are terraform or env data attributes hcl bool false Whether to evaluate the value of the variable as a string of HCL code Has no effect for environment variables data attributes sensitive bool false Whether the value is sensitive If true then the variable is written once and not visible thereafter data relationships workspace data type string Must be workspaces data relationships workspace data id string The ID of the workspace that owns the variable We also always include a sample payload object to show the document structure more visually Query Parameters Although most of our API endpoints use the POST method and receive their parameters as a JSON object in the request payload some of them use the GET method These GET endpoints sometimes require URL query parameters in the standard path key1 value1 key2 value2 format Since these parameters were originally designed as part of a JSON object they sometimes have characters that must be percent encoded https en wikipedia org wiki Percent encoding in a query parameter For example becomes 5B and becomes 5D For more about URI structure and query strings see the specification RFC 3986 https tools ietf org html rfc3986 or the Wikipedia page on URIs https en wikipedia org wiki Uniform Resource Identifier Pagination Most of the endpoints that return lists of objects support pagination A client may pass the following query parameters to control pagination on supported endpoints Parameter Description page number Optional If omitted the endpoint will return the first page page size Optional If omitted the endpoint will return 20 items per page The maximum page size is 100 Additional data is returned in the links and meta top level attributes of the response json data links self https app terraform io api v2 organizations hashicorp workspaces page 5Bnumber 5D 1 page 5Bsize 5D 20 first https app terraform io api v2 organizations hashicorp workspaces page 5Bnumber 5D 1 page 5Bsize 5D 20 prev null next https app terraform io api v2 organizations hashicorp workspaces page 5Bnumber 5D 2 page 5Bsize 5D 20 last https app terraform io api v2 organizations hashicorp workspaces page 5Bnumber 5D 2 page 5Bsize 5D 20 meta pagination current page 1 prev page null next page 2 total pages 2 total count 21 Inclusion of Related Resources Some of the API s GET endpoints can return additional information about nested resources by adding an include query parameter whose value is a comma separated list of resource types The related resource options are listed in each endpoint s documentation where available The related resources will appear in an included section of the response Example shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 teams team n8UQ6wfhyym25sMe include users json data id team n8UQ6wfhyym25sMe type teams attributes name owners users count 1 relationships users data id user 62goNpx1ThQf689e type users included id user 62goNpx1ThQf689e type users attributes username hashibot Rate Limiting You can make up to 30 requests per second to the API as an authenticated or unauthenticated request If you reach the rate limit then your access will be throttled and an error response will be returned Some endpoints have lower rate limits to prevent abuse including endpoints that poll Terraform for a list of runs and endpoints related to user authentication The adjusted limits are unnoticeable under normal use If you receive a rate limited response the limit is reflected in the x ratelimit limit header once triggered Authenticated requests are allocated to the user associated with the authentication token This means that a user with multiple tokens will still be limited to 30 requests per second additional tokens will not allow you to increase the requests per second permitted Unauthenticated requests are associated with the requesting IP address Status Response Reason 429 JSON API error object Rate limit has been reached json errors detail You have exceeded the API s rate limit status 429 title Too many requests Client libraries and tools HashiCorp maintains go tfe https github com hashicorp go tfe a Go client for HCP Terraform s API Additionally the community of HCP Terraform users and vendors have built client libraries in other languages These client libraries and tools are not tested nor officially maintained by HashiCorp but are listed below in order to help users find them easily If you have built a client library and would like to add it to this community list please contribute https github com hashicorp terraform website contributions welcome to this page https github com hashicorp terraform docs common blob main website docs cloud docs api docs index mdx client libraries and tools tfh https github com hashicorp community tf helper UNIX shell console app tf api gateway https github com PlethoraOfHate tf api gateway Python API library and console app terrasnek https github com dahlke terrasnek Python API library terraform enterprise client https github com skierkowski terraform enterprise client Ruby API library and console app pyterprise https github com JFryy terraform enterprise api python client A simple Python API client library Tfe NetClient https github com everis technology Tfe NetClient NET Client Library
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 Use the policy checks endpoint to manage the Sentinel checks performed on a Terraform run List show and override policy checks using the HTTP API 201 https developer mozilla org en US docs Web HTTP Status 201 page title Policy Checks API Docs HCP Terraform
--- page_title: Policy Checks - API Docs - HCP Terraform description: >- Use the `/policy-checks` endpoint to manage the Sentinel checks performed on a Terraform run. List, show and override policy checks using the HTTP API. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # Policy Checks API <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/policies.mdx' <!-- END: TFC:only name:pnp-callout --> Policy checks are the default workflow for Sentinel. Policy checks use the latest version of the Sentinel runtime and have access to cost estimation data. This set of APIs provides endpoints to get, list, and override policy checks. ~> **Warning:** Policy checks are deprecated and will be permanently removed in August 2025. We recommend that you start using policy evaluations to avoid disruptions. ## List Policy Checks This endpoint lists the policy checks in a run. -> **Note**: The `sentinel` hash in the `result` attribute structure represents low-level Sentinel details generated by the policy engine. The keys or structure may change over time. Use the data in this hash at your own risk. `GET /runs/:run_id/policy-checks` | Parameter | Description | | --------- | -------------------------------------------- | | `run_id` | The ID of the run to list policy checks for. | ### Query Parameters This endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. If neither pagination query parameters are provided, the endpoint will not be paginated and will return all results. | Parameter | Description | | -------------- | ----------------------------------------------------------------------------- | | `page[number]` | **Optional.** If omitted, the endpoint will return the first page. | | `page[size]` | **Optional.** If omitted, the endpoint will return 20 policy checks per page. | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ https://app.terraform.io/api/v2/runs/run-CZcmD7eagjhyXavN/policy-checks ``` ### Sample Response ```json { "data": [ { "id": "polchk-9VYRc9bpfJEsnwum", "type": "policy-checks", "attributes": { "result": { "result": false, "passed": 0, "total-failed": 1, "hard-failed": 0, "soft-failed": 1, "advisory-failed": 0, "duration-ms": 0, "sentinel": {...} }, "scope": "organization", "status": "soft_failed", "status-timestamps": { "queued-at": "2017-11-29T20:02:17+00:00", "soft-failed-at": "2017-11-29T20:02:20+00:00" }, "actions": { "is-overridable": true }, "permissions": { "can-override": false } }, "relationships": { "run": { "data": { "id": "run-veDoQbv6xh6TbnJD", "type": "runs" } } }, "links": { "output": "/api/v2/policy-checks/polchk-9VYRc9bpfJEsnwum/output" } } ] } ``` ## Show Policy Check This endpoint gets information about a specific policy check ID. Policy check IDs can appear in audit logs. -> **Note**: The `sentinel` hash in the `result` attribute structure represents low-level Sentinel details generated by the policy engine. The keys or structure may change over time. Use the data in this hash at your own risk. `GET /policy-checks/:id` | Parameter | Description | | --------- | ----------------------------------- | | `id` | The ID of the policy check to show. | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ https://app.terraform.io/api/v2/policy-checks/polchk-9VYRc9bpfJEsnwum ``` ### Sample Response ```json { "data": { "id": "polchk-9VYRc9bpfJEsnwum", "type": "policy-checks", "attributes": { "result": { "result": false, "passed": 0, "total-failed": 1, "hard-failed": 0, "soft-failed": 1, "advisory-failed": 0, "duration-ms": 0, "sentinel": {...} }, "scope": "organization", "status": "soft_failed", "status-timestamps": { "queued-at": "2017-11-29T20:02:17+00:00", "soft-failed-at": "2017-11-29T20:02:20+00:00" }, "actions": { "is-overridable": true }, "permissions": { "can-override": false } }, "relationships": { "run": { "data": { "id": "run-veDoQbv6xh6TbnJD", "type": "runs" } } }, "links": { "output": "/api/v2/policy-checks/polchk-9VYRc9bpfJEsnwum/output" } } } ``` ## Override Policy This endpoint overrides a soft-mandatory or warning policy. -> **Note**: The `sentinel` hash in the `result` attribute structure represents low-level Sentinel details generated by the policy engine. The keys or structure may change over time. Use the data in this hash at your own risk. `POST /policy-checks/:id/actions/override` | Parameter | Description | | --------- | --------------------------------------- | | `id` | The ID of the policy check to override. | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ https://app.terraform.io/api/v2/policy-checks/polchk-EasPB4Srx5NAiWAU/actions/override ``` ### Sample Response ```json { "data": { "id": "polchk-EasPB4Srx5NAiWAU", "type": "policy-checks", "attributes": { "result": { "result": false, "passed": 0, "total-failed": 1, "hard-failed": 0, "soft-failed": 1, "advisory-failed": 0, "duration-ms": 0, "sentinel": {...} }, "scope": "organization", "status": "overridden", "status-timestamps": { "queued-at": "2017-11-29T20:13:37+00:00", "soft-failed-at": "2017-11-29T20:13:40+00:00", "overridden-at": "2017-11-29T20:14:11+00:00" }, "actions": { "is-overridable": true }, "permissions": { "can-override": false } }, "links": { "output": "/api/v2/policy-checks/polchk-EasPB4Srx5NAiWAU/output" } } } ``` ### Available Related Resources The GET endpoints above can optionally return related resources, if requested with [the `include` query parameter](/terraform/cloud-docs/api-docs#inclusion-of-related-resources). The following resource types are available: | Resource Name | Description | | ------------------ | -------------------------------------- | | `run` | The run this policy check belongs to. | | `run.workspace` | The associated workspace of the run. |
terraform
page title Policy Checks API Docs HCP Terraform description Use the policy checks endpoint to manage the Sentinel checks performed on a Terraform run List show and override policy checks using the HTTP API 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects Policy Checks API BEGIN TFC only name pnp callout include tfc package callouts policies mdx END TFC only name pnp callout Policy checks are the default workflow for Sentinel Policy checks use the latest version of the Sentinel runtime and have access to cost estimation data This set of APIs provides endpoints to get list and override policy checks Warning Policy checks are deprecated and will be permanently removed in August 2025 We recommend that you start using policy evaluations to avoid disruptions List Policy Checks This endpoint lists the policy checks in a run Note The sentinel hash in the result attribute structure represents low level Sentinel details generated by the policy engine The keys or structure may change over time Use the data in this hash at your own risk GET runs run id policy checks Parameter Description run id The ID of the run to list policy checks for Query Parameters This endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters Remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs If neither pagination query parameters are provided the endpoint will not be paginated and will return all results Parameter Description page number Optional If omitted the endpoint will return the first page page size Optional If omitted the endpoint will return 20 policy checks per page Sample Request shell curl header Authorization Bearer TOKEN https app terraform io api v2 runs run CZcmD7eagjhyXavN policy checks Sample Response json data id polchk 9VYRc9bpfJEsnwum type policy checks attributes result result false passed 0 total failed 1 hard failed 0 soft failed 1 advisory failed 0 duration ms 0 sentinel scope organization status soft failed status timestamps queued at 2017 11 29T20 02 17 00 00 soft failed at 2017 11 29T20 02 20 00 00 actions is overridable true permissions can override false relationships run data id run veDoQbv6xh6TbnJD type runs links output api v2 policy checks polchk 9VYRc9bpfJEsnwum output Show Policy Check This endpoint gets information about a specific policy check ID Policy check IDs can appear in audit logs Note The sentinel hash in the result attribute structure represents low level Sentinel details generated by the policy engine The keys or structure may change over time Use the data in this hash at your own risk GET policy checks id Parameter Description id The ID of the policy check to show Sample Request shell curl header Authorization Bearer TOKEN https app terraform io api v2 policy checks polchk 9VYRc9bpfJEsnwum Sample Response json data id polchk 9VYRc9bpfJEsnwum type policy checks attributes result result false passed 0 total failed 1 hard failed 0 soft failed 1 advisory failed 0 duration ms 0 sentinel scope organization status soft failed status timestamps queued at 2017 11 29T20 02 17 00 00 soft failed at 2017 11 29T20 02 20 00 00 actions is overridable true permissions can override false relationships run data id run veDoQbv6xh6TbnJD type runs links output api v2 policy checks polchk 9VYRc9bpfJEsnwum output Override Policy This endpoint overrides a soft mandatory or warning policy Note The sentinel hash in the result attribute structure represents low level Sentinel details generated by the policy engine The keys or structure may change over time Use the data in this hash at your own risk POST policy checks id actions override Parameter Description id The ID of the policy check to override Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST https app terraform io api v2 policy checks polchk EasPB4Srx5NAiWAU actions override Sample Response json data id polchk EasPB4Srx5NAiWAU type policy checks attributes result result false passed 0 total failed 1 hard failed 0 soft failed 1 advisory failed 0 duration ms 0 sentinel scope organization status overridden status timestamps queued at 2017 11 29T20 13 37 00 00 soft failed at 2017 11 29T20 13 40 00 00 overridden at 2017 11 29T20 14 11 00 00 actions is overridable true permissions can override false links output api v2 policy checks polchk EasPB4Srx5NAiWAU output Available Related Resources The GET endpoints above can optionally return related resources if requested with the include query parameter terraform cloud docs api docs inclusion of related resources The following resource types are available Resource Name Description run The run this policy check belongs to run workspace The associated workspace of the run
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 Use the projects endpoint to manage an organization s projects List show create update and delete projects using the HTTP API 201 https developer mozilla org en US docs Web HTTP Status 201 page title Projects API Docs HCP Terraform
--- page_title: Projects - API Docs - HCP Terraform description: >- Use the `/projects` endpoint to manage an organization's projects. List, show, create, update, and delete projects using the HTTP API. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects [speculative plans]: /terraform/cloud-docs/run/remote-operations#speculative-plans # Projects API This topic provides reference information about the projects API. The scope of the API includes the following endpoints: | Method | Path | Action | | --- | --- | --- | | `POST` | `/organizations/:organization_name/projects` | Call this endpoint to [create a project](#create-a-project). | | `PATCH`| `/projects/:project_id` | Call this endpoint to [update an existing project](#update-a-project). | | `GET` | `/organizations/:organization_name/projects`| Call this endpoint to [list existing projects](#list-projects). | | `GET` | `/projects/:project_id` | Call this endpoint to [show project details](#show-project). | | `DELETE` | `/projects/:project_id` | Call this endpoint to [delete a project](#delete-a-project). | | `GET` | `/projects/:project_id/tag-bindings` | Call this endpoint to [list project tag bindings](#list-project-tag-bindings). (For projects, this returns the same result set as the `effective-tag-bindings` endpoint.) | | `GET` | `/projects/:project_id/effective-tag-bindings` | Call this endpoint to [list project effective tag bindings](#list-project-tag-bindings). (For projects, this returns the same result set as the `tag-bindings` endpoint.) | ## Requirements You must be on a team with one of the **Owners** or **Manage projects** permissions settings enabled to create and manage projects. Refer to [Permissions](/terraform/cloud-docs/users-teams-organizations/permissions) for additional information. You can also provide an organization API token to call project API endpoints. Refer to [Organization API Tokens](/terraform/cloud-docs/users-teams-organizations/api-tokens#organization-api-tokens) for additional information. ## Create a Project `POST /organizations/:organization_name/projects` | Parameter | Description | |----------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `:organization_name` | The name of the organization to create the project in. The organization must already exist in the system, and the user must have permissions to create new projects. | -> **Note:** Project creation is restricted to the owners team, teams with the "Manage Projects" permission, and the [organization API token](/terraform/cloud-docs/users-teams-organizations/api-tokens#organization-api-tokens). ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | |---|---|---|--- | | `data.type` | string | none | Must be `"projects"`. | | `data.attributes.name` | string | | The name of the project. The name can contain letters, numbers, spaces, `-`, and `_`, but cannot start or end with spaces. It must be at least three characters long and no more than 40 characters long. | | `data.attributes.description` | string | none | Optional. The description of the project. It must be no more than 256 characters long. | | `data.attributes.auto-destroy-activity-duration`| string | none | Specifies the default for how long each workspace in the project should wait before automatically destroying its infrastructure. You can specify a duration up to four digits that is greater than `0` followed by either a `d` for days or `h` hours. For example, to queue destroy runs after fourteen days of inactivity set `auto-destroy-activity-duration: "14d"`. All future workspaces in this project inherit this default value. Refer to [Automatically destroy inactive workspaces](/terraform/cloud-docs/projects/managing#automatically-destroy-inactive-workspaces) for additional information. | | `data.relationships.tag-bindings.data` | list of objects | none | Specifies a list of tags to attach to the project. | | `data.relationships.tag-bindings.data.type` | string | none | Must be `tag-bindings` for each object in the list. | | `data.relationships.tag-bindings.data.attributes.key` | string | none | Specifies the tag key for each object in the list. | | `data.relationships.tag-bindings.data.attributes.value` | string | none | Specifies the tag value for each object in the list. | ### Sample Payload ```json { "data": { "attributes": { "name": "Test Project", "description": "An example project for documentation.", }, "type": "projects", "relationships": { "tag-bindings": { "data": [ { "type": "tag-bindings", "attributes": { "key": "environment", "value": "development" } }, ] } } } } ``` ### Sample Request ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/organizations/my-organization/projects ``` ### Sample Response ```json { "data": { "id": "prj-WsVcWRr7SfxRci1v", "type": "projects", "attributes": { "name": "Test Project", "description": "An example project for documentation.", "permissions": { "can-update": true } }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" }, "links": { "related": "/api/v2/organizations/my-organization" } }, "tag-bindings": { "links": { "related": "/api/v2/projects/prj-WsVcWRr7SfxRci1v/tag-bindings" } }, "effective-tag-bindings": { "links": { "related": "/api/v2/projects/prj-WsVcWRr7SfxRci1v/effective-tag-bindings" } } }, "links": { "self": "/api/v2/projects/prj-WsVcWRr7SfxRci1v" } } } ``` ## Update a Project Call the following endpoint to update a project: `PATCH /projects/:project_id` | Parameter | Description | |---------------|---------------------------------| | `:project_id` | The ID of the project to update | ### Request Body These PATCH endpoints require a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | |---|---|---|---| | `data.type` | string | none | Must be `"projects"`. | | `data.attributes.name` | string | existing value | A new name for the project. The name can contain letters, numbers, spaces, `-`, and `_`, but cannot start or end with spaces. It must be at least 3 characters long and no more than 40 characters long. | | `data.attributes.description` | string | existing value | The new description for the project. It must be no more than 256 characters long. | | `data.attributes.auto-destroy-activity-duration`| string | none | Specifies how long each workspace in the project should wait before automatically destroying its infrastructure by default. You can specify a duration up to four digits that is greater than `0` followed by either a `d` for days or `h` hours. For example, to queue destroy runs after fourteen days of inactivity set `auto-destroy-activity-duration: "14d"`. When you update this value, all workspaces in the project receive the new value unless you previously configured an override. Refer to [Automatically destroy inactive workspaces](/terraform/cloud-docs/projects/managing#automatically-destroy-inactive-workspaces) for additional information. | | `data.relationships.tag-bindings.data` | list of objects | none | Specifies a list of tags to attach to the project. | | `data.relationships.tag-bindings.data.type` | string | none | Must be `tag-bindings` for each object in the list. | | `data.relationships.tag-bindings.data.attributes.key` | string | none | Specifies the tag key for each object in the list. | | `data.relationships.tag-bindings.data.attributes.value` | string | none | Specifies the tag value for each object in the list. | ### Sample Payload ```json { "data": { "attributes": { "name": "Infrastructure Project" }, "type": "projects", "relationships": { "tag-bindings": { "data": [ { "type": "tag-bindings", "attributes": { "key": "environment", "value": "staging" } }, ] } } } } ``` ### Sample Request ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request PATCH \ --data @payload.json \ https://app.terraform.io/api/v2/projects/prj-WsVcWRr7SfxRci1v ``` ### Sample Response ```json { "data": { "id": "prj-WsVcWRr7SfxRci1v", "type": "projects", "attributes": { "name": "Infrastructure Project", "description": null, "workspace-count": 4, "team-count": 2, "permissions": { "can-update": true, "can-destroy": true, "can-create-workspace": true } }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" }, "links": { "related": "/api/v2/organizations/my-organization" } }, "tag-bindings": { "links": { "related": "/api/v2/projects/prj-WsVcWRr7SfxRci1v/tag-bindings" } }, "effective-tag-bindings": { "links": { "related": "/api/v2/projects/prj-WsVcWRr7SfxRci1v/effective-tag-bindings" } } }, "links": { "self": "/api/v2/projects/prj-WsVcWRr7SfxRci1v" } } } ``` ## List projects This endpoint lists projects in the organization. `GET /organizations/:organization_name/projects` | Parameter | Description | |----------------------|-------------------------------------------------------| | `:organization_name` | The name of the organization to list the projects of. | ### Query Parameters This endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. | Parameter | Description | |-----------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `page[number]` | **Optional.** If omitted, the endpoint will return the first page. | | `page[size]` | **Optional.** If omitted, the endpoint will return 20 projects per page. | | `q` | **Optional.** A search query string. This query searches projects by name. This search is case-insensitive. If both `q` and `filter[names]` are specified, `filter[names]` will be used. | | `filter[names]` | **Optional.** If specified, returns the project with the matching name. This filter is case-insensitive. If multiple comma separated values are specified, projects matching any of the names are returned. | | `filter[permissions][create-workspace]` | **Optional.** If present, returns a list of projects that the authenticated user can create workspaces in. | | `filter[permissions][update]` | **Optional.** If present, returns a list of projects that the authenticated user can update. | | `sort` | **Optional.** Allows sorting the organization's projects by `"name"`. Prepending a hyphen to the sort parameter reverses the order. For example, `"-name"` sorts by name in reverse alphabetical order. If omitted, the default sort order is arbitrary but stable. | ### Sample Request ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/organizations/my-organization/projects ``` ### Sample Response ```json { "data": [ { "id": "prj-W6k9K23oSXRHGpj3", "type": "projects", "attributes": { "name": "Default Project", "description": null, "workspace-count": 2, "team-count": 1, "permissions": { "can-update": true, "can-destroy": true, "can-create-workspace": true } }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" }, "links": { "related": "/api/v2/organizations/my-organization" } }, "tag-bindings": { "links": { "related": "/api/v2/projects/prj-W6k9K23oSXRHGpj3/tag-bindings" } }, "effective-tag-bindings": { "links": { "related": "/api/v2/projects/prj-W6k9K23oSXRHGpj3/effective-tag-bindings" } } }, "links": { "self": "/api/v2/projects/prj-W6k9K23oSXRHGpj3" } }, { "id": "prj-YoriCxAawTMDLswn", "type": "projects", "attributes": { "name": "Infrastructure Project", "description": null, "workspace-count": 4, "team-count": 2, "permissions": { "can-update": true, "can-destroy": true, "can-create-workspace": true } }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" }, "links": { "related": "/api/v2/organizations/my-organization" } }, "tag-bindings": { "links": { "related": "/api/v2/projects/prj-YoriCxAawTMDLswn/tag-bindings" } }, "effective-tag-bindings": { "links": { "related": "/api/v2/projects/prj-YoriCxAawTMDLswn/effective-tag-bindings" } } }, "links": { "self": "/api/v2/projects/prj-YoriCxAawTMDLswn" } } ], "links": { "self": "https://app.terraform.io/api/v2/organizations/my-organization/projects?page%5Bnumber%5D=1&page%5Bsize%5D=20", "first": "https://app.terraform.io/api/v2/organizations/my-organization/projects?page%5Bnumber%5D=1&page%5Bsize%5D=20", "prev": null, "next": null, "last": "https://app.terraform.io/api/v2/organizations/my-organization/projects?page%5Bnumber%5D=1&page%5Bsize%5D=20" }, "meta": { "status-counts": { "total": 2, "matching": 2 }, "pagination": { "current-page": 1, "page-size": 20, "prev-page": null, "next-page": null, "total-pages": 1, "total-count": 2 } } } ``` ## Show project `GET /projects/:project_id` | Parameter | Description | |---------------|----------------| | `:project_id` | The project ID | ### Sample Request ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/projects/prj-WsVcWRr7SfxRci1v ``` ### Sample Response ```json { "data": { "id": "prj-WsVcWRr7SfxRci1v", "type": "projects", "attributes": { "name": "Infrastructure Project", "description": null, "workspace-count": 4, "team-count": 2, "permissions": { "can-update": true, "can-destroy": true, "can-create-workspace": true }, "auto-destroy-activity-duration": "2d" }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" }, "links": { "related": "/api/v2/organizations/my-organization" } }, "tag-bindings": { "links": { "related": "/api/v2/projects/prj-WsVcWRr7SfxRci1v/tag-bindings" } }, "effective-tag-bindings": { "links": { "related": "/api/v2/projects/prj-WsVcWRr7SfxRci1v/effective-tag-bindings" } } }, "links": { "self": "/api/v2/projects/prj-WsVcWRr7SfxRci1v" } } } ``` ## Delete a project A project cannot be deleted if it contains workspaces. `DELETE /projects/:project_id` | Parameter | Description | |---------------|---------------------------------| | `:project_id` | The ID of the project to delete | | Status | Response | Reason(s) | |---------|---------------------------|-------------------------------------------------------------------| | [204][] | No Content | Successfully deleted the project | | [403][] | [JSON API error object][] | Not authorized to perform a force delete on the project | | [404][] | [JSON API error object][] | Project not found, or user unauthorized to perform project delete | ### Sample Request ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request DELETE \ https://app.terraform.io/api/v2/projects/prj-WsVcWRr7SfxRci1v ``` ## List project tag bindings Call the following endpoints to list the tags associated with a project. - `GET /projects/:project_id/effective-tag-bindings`: Lists the complete set of tags for the project, including any that have been inherited from a parent resource. For projects, this endpoint returns the same set of data as the `tag-bindings` endpoint, so only that endpoint is documented here. | Parameter | Description | |---------------|----------------------- | | `:project_id` | The ID of the project. | ### Sample request The following request returns all tags bound to a project with the ID `prj-WsVcWRr7SfxRci1v`. ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/projects/prj-WsVcWRr7SfxRci1v/effective-tag-bindings ``` ### Sample response ```json { "data": [ { "type": "effective-tag-bindings", "attributes": { "key": "added", "value": "new" } }, { "type": "effective-tag-bindings", "attributes": { "key": "aww", "value": "aww" } } ] } ``` ## Move workspaces into a project This endpoint allows you to move one or more workspaces into a project. You must have permission to move workspaces on the destination project as well as any source project(s). If you are not authorized to move any of the workspaces in the request, or if any workspaces in the request are not found, then no workspaces will be moved. `POST /projects/:project_id/relationships/workspaces` | Parameter | Description | |---------------|-----------------------------------| | `:project_id` | The ID of the destination project | This POST endpoint requires a JSON object with the following properties as a request payload. | Key path | Type | Default | Description | |---------------|--------|---------|------------------------------------------------------------| | `data[].type` | string | | Must be `"workspaces"` | | `data[].id` | string | | The ids of workspaces to move into the destination project | | Status | Response | Reason(s) | |---------|---------------------------|----------------------------------------------------------------------------------------------------------| | [204][] | No Content | Successfully moved workspace(s) | | [403][] | [JSON API error object][] | Workspace(s) not found, or user is not authorized to move all workspaces out of their current project(s) | | [404][] | [JSON API error object][] | Project not found, or user unauthorized to move workspaces into project | ### Sample Payload ```json { "data": [ { "type": "workspaces", "id": "ws-AQEct2XFuH4HBsmS" } ] } ``` ### Sample Request ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/projects/prj-zXm4y2BjeGPgHtkp/relationships/workspaces ``` ### Sample Error Response ```json { "errors": [ { "status": "403", "title": "forbidden", "detail": "Workspace(s) not found, or you are not authorized to move them: ws-AQEct2XFuH4HBmS" } ] } ```
terraform
page title Projects API Docs HCP Terraform description Use the projects endpoint to manage an organization s projects List show create update and delete projects using the HTTP API 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects speculative plans terraform cloud docs run remote operations speculative plans Projects API This topic provides reference information about the projects API The scope of the API includes the following endpoints Method Path Action POST organizations organization name projects Call this endpoint to create a project create a project PATCH projects project id Call this endpoint to update an existing project update a project GET organizations organization name projects Call this endpoint to list existing projects list projects GET projects project id Call this endpoint to show project details show project DELETE projects project id Call this endpoint to delete a project delete a project GET projects project id tag bindings Call this endpoint to list project tag bindings list project tag bindings For projects this returns the same result set as the effective tag bindings endpoint GET projects project id effective tag bindings Call this endpoint to list project effective tag bindings list project tag bindings For projects this returns the same result set as the tag bindings endpoint Requirements You must be on a team with one of the Owners or Manage projects permissions settings enabled to create and manage projects Refer to Permissions terraform cloud docs users teams organizations permissions for additional information You can also provide an organization API token to call project API endpoints Refer to Organization API Tokens terraform cloud docs users teams organizations api tokens organization api tokens for additional information Create a Project POST organizations organization name projects Parameter Description organization name The name of the organization to create the project in The organization must already exist in the system and the user must have permissions to create new projects Note Project creation is restricted to the owners team teams with the Manage Projects permission and the organization API token terraform cloud docs users teams organizations api tokens organization api tokens Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string none Must be projects data attributes name string The name of the project The name can contain letters numbers spaces and but cannot start or end with spaces It must be at least three characters long and no more than 40 characters long data attributes description string none Optional The description of the project It must be no more than 256 characters long data attributes auto destroy activity duration string none Specifies the default for how long each workspace in the project should wait before automatically destroying its infrastructure You can specify a duration up to four digits that is greater than 0 followed by either a d for days or h hours For example to queue destroy runs after fourteen days of inactivity set auto destroy activity duration 14d All future workspaces in this project inherit this default value Refer to Automatically destroy inactive workspaces terraform cloud docs projects managing automatically destroy inactive workspaces for additional information data relationships tag bindings data list of objects none Specifies a list of tags to attach to the project data relationships tag bindings data type string none Must be tag bindings for each object in the list data relationships tag bindings data attributes key string none Specifies the tag key for each object in the list data relationships tag bindings data attributes value string none Specifies the tag value for each object in the list Sample Payload json data attributes name Test Project description An example project for documentation type projects relationships tag bindings data type tag bindings attributes key environment value development Sample Request shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 organizations my organization projects Sample Response json data id prj WsVcWRr7SfxRci1v type projects attributes name Test Project description An example project for documentation permissions can update true relationships organization data id my organization type organizations links related api v2 organizations my organization tag bindings links related api v2 projects prj WsVcWRr7SfxRci1v tag bindings effective tag bindings links related api v2 projects prj WsVcWRr7SfxRci1v effective tag bindings links self api v2 projects prj WsVcWRr7SfxRci1v Update a Project Call the following endpoint to update a project PATCH projects project id Parameter Description project id The ID of the project to update Request Body These PATCH endpoints require a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string none Must be projects data attributes name string existing value A new name for the project The name can contain letters numbers spaces and but cannot start or end with spaces It must be at least 3 characters long and no more than 40 characters long data attributes description string existing value The new description for the project It must be no more than 256 characters long data attributes auto destroy activity duration string none Specifies how long each workspace in the project should wait before automatically destroying its infrastructure by default You can specify a duration up to four digits that is greater than 0 followed by either a d for days or h hours For example to queue destroy runs after fourteen days of inactivity set auto destroy activity duration 14d When you update this value all workspaces in the project receive the new value unless you previously configured an override Refer to Automatically destroy inactive workspaces terraform cloud docs projects managing automatically destroy inactive workspaces for additional information data relationships tag bindings data list of objects none Specifies a list of tags to attach to the project data relationships tag bindings data type string none Must be tag bindings for each object in the list data relationships tag bindings data attributes key string none Specifies the tag key for each object in the list data relationships tag bindings data attributes value string none Specifies the tag value for each object in the list Sample Payload json data attributes name Infrastructure Project type projects relationships tag bindings data type tag bindings attributes key environment value staging Sample Request shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json request PATCH data payload json https app terraform io api v2 projects prj WsVcWRr7SfxRci1v Sample Response json data id prj WsVcWRr7SfxRci1v type projects attributes name Infrastructure Project description null workspace count 4 team count 2 permissions can update true can destroy true can create workspace true relationships organization data id my organization type organizations links related api v2 organizations my organization tag bindings links related api v2 projects prj WsVcWRr7SfxRci1v tag bindings effective tag bindings links related api v2 projects prj WsVcWRr7SfxRci1v effective tag bindings links self api v2 projects prj WsVcWRr7SfxRci1v List projects This endpoint lists projects in the organization GET organizations organization name projects Parameter Description organization name The name of the organization to list the projects of Query Parameters This endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters Remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs Parameter Description page number Optional If omitted the endpoint will return the first page page size Optional If omitted the endpoint will return 20 projects per page q Optional A search query string This query searches projects by name This search is case insensitive If both q and filter names are specified filter names will be used filter names Optional If specified returns the project with the matching name This filter is case insensitive If multiple comma separated values are specified projects matching any of the names are returned filter permissions create workspace Optional If present returns a list of projects that the authenticated user can create workspaces in filter permissions update Optional If present returns a list of projects that the authenticated user can update sort Optional Allows sorting the organization s projects by name Prepending a hyphen to the sort parameter reverses the order For example name sorts by name in reverse alphabetical order If omitted the default sort order is arbitrary but stable Sample Request shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 organizations my organization projects Sample Response json data id prj W6k9K23oSXRHGpj3 type projects attributes name Default Project description null workspace count 2 team count 1 permissions can update true can destroy true can create workspace true relationships organization data id my organization type organizations links related api v2 organizations my organization tag bindings links related api v2 projects prj W6k9K23oSXRHGpj3 tag bindings effective tag bindings links related api v2 projects prj W6k9K23oSXRHGpj3 effective tag bindings links self api v2 projects prj W6k9K23oSXRHGpj3 id prj YoriCxAawTMDLswn type projects attributes name Infrastructure Project description null workspace count 4 team count 2 permissions can update true can destroy true can create workspace true relationships organization data id my organization type organizations links related api v2 organizations my organization tag bindings links related api v2 projects prj YoriCxAawTMDLswn tag bindings effective tag bindings links related api v2 projects prj YoriCxAawTMDLswn effective tag bindings links self api v2 projects prj YoriCxAawTMDLswn links self https app terraform io api v2 organizations my organization projects page 5Bnumber 5D 1 page 5Bsize 5D 20 first https app terraform io api v2 organizations my organization projects page 5Bnumber 5D 1 page 5Bsize 5D 20 prev null next null last https app terraform io api v2 organizations my organization projects page 5Bnumber 5D 1 page 5Bsize 5D 20 meta status counts total 2 matching 2 pagination current page 1 page size 20 prev page null next page null total pages 1 total count 2 Show project GET projects project id Parameter Description project id The project ID Sample Request shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 projects prj WsVcWRr7SfxRci1v Sample Response json data id prj WsVcWRr7SfxRci1v type projects attributes name Infrastructure Project description null workspace count 4 team count 2 permissions can update true can destroy true can create workspace true auto destroy activity duration 2d relationships organization data id my organization type organizations links related api v2 organizations my organization tag bindings links related api v2 projects prj WsVcWRr7SfxRci1v tag bindings effective tag bindings links related api v2 projects prj WsVcWRr7SfxRci1v effective tag bindings links self api v2 projects prj WsVcWRr7SfxRci1v Delete a project A project cannot be deleted if it contains workspaces DELETE projects project id Parameter Description project id The ID of the project to delete Status Response Reason s 204 No Content Successfully deleted the project 403 JSON API error object Not authorized to perform a force delete on the project 404 JSON API error object Project not found or user unauthorized to perform project delete Sample Request shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json request DELETE https app terraform io api v2 projects prj WsVcWRr7SfxRci1v List project tag bindings Call the following endpoints to list the tags associated with a project GET projects project id effective tag bindings Lists the complete set of tags for the project including any that have been inherited from a parent resource For projects this endpoint returns the same set of data as the tag bindings endpoint so only that endpoint is documented here Parameter Description project id The ID of the project Sample request The following request returns all tags bound to a project with the ID prj WsVcWRr7SfxRci1v shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 projects prj WsVcWRr7SfxRci1v effective tag bindings Sample response json data type effective tag bindings attributes key added value new type effective tag bindings attributes key aww value aww Move workspaces into a project This endpoint allows you to move one or more workspaces into a project You must have permission to move workspaces on the destination project as well as any source project s If you are not authorized to move any of the workspaces in the request or if any workspaces in the request are not found then no workspaces will be moved POST projects project id relationships workspaces Parameter Description project id The ID of the destination project This POST endpoint requires a JSON object with the following properties as a request payload Key path Type Default Description data type string Must be workspaces data id string The ids of workspaces to move into the destination project Status Response Reason s 204 No Content Successfully moved workspace s 403 JSON API error object Workspace s not found or user is not authorized to move all workspaces out of their current project s 404 JSON API error object Project not found or user unauthorized to move workspaces into project Sample Payload json data type workspaces id ws AQEct2XFuH4HBsmS Sample Request shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 projects prj zXm4y2BjeGPgHtkp relationships workspaces Sample Error Response json errors status 403 title forbidden detail Workspace s not found or you are not authorized to move them ws AQEct2XFuH4HBmS
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 Use the policies endpoint to manage Sentinel and OPA policies List show create upload update and delete policies using the HTTP API 201 https developer mozilla org en US docs Web HTTP Status 201 page title Policies API Docs HCP Terraform
--- page_title: Policies - API Docs - HCP Terraform description: >- Use the `/policies` endpoint to manage Sentinel and OPA policies. List, show, create, upload, update, and delete policies using the HTTP API. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # Policies API Policies are rules that HCP Terraform enforces on Terraform runs. You can use policies to validate that the Terraform plan complies with security rules and best practices. HCP Terraform policy enforcement lets you use the policy-as-code frameworks Sentinel and Open Policy Agent (OPA) to apply policy checks to HCP Terraform workspaces. Refer to [Policy Enforcement](/terraform/cloud-docs/policy-enforcement) for more details. [Policy sets](/terraform/cloud-docs/policy-enforcement/manage-policy-sets) are collections of policies that you can apply globally or to specific [projects](/terraform/cloud-docs/projects/manage) and workspaces, in your organization. For each run in the selected workspaces, HCP Terraform checks the Terraform plan against the policy set and displays the results in the UI. <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/policies.mdx' <!-- END: TFC:only name:pnp-callout --> This page documents the API endpoints to create, read, update, and delete policies in an organization. To manage policy sets, use the [Policy Sets API](/terraform/cloud-docs/api-docs/policy-sets). To manage the policy results, use the [Runs API](/terraform/cloud-docs/api-docs/run). ## Create a Policy `POST /organizations/:organization_name/policies` | Parameter | Description | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `:organization_name` | The organization to create the policy in. The organization must already exist in the system, and the token authenticating the API request must have permission to manage policies. (([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) | \[permissions-citation]: #intentionally-unused---keep-for-maintainers) This creates a new policy object for the organization, but does not upload the actual policy code. After creation, you must use the [Upload a Policy endpoint (below)](#upload-a-policy) with the new policy's upload path. (This endpoint's response body includes the upload path in its `links.upload` property.) | Status | Response | Reason | | ------- | ------------------------------------------ | -------------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "policies"`) | Successfully created a policy | | [404][] | [JSON API error object][] | Organization not found, or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (missing attributes, wrong types, etc.) | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | --------------------------------------- | -------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `data.type` | string | | Must be `"policies"`. | | `data.attributes.name` | string | | The name of the policy, which can include letters, numbers, `-`, and `_`. You cannot modify this name after creation. | | `data.attributes.description` | string | `null` | Text describing the policy's purpose. This field supports Markdown and appears in the HCP Terraform UI. | | `data.attributes.kind` | string | `sentinel` | The policy-as-code framework for the policy. Valid values are `"sentinel"` and `"opa"`. | | `data.attributes.query` | string | | The OPA query to run. Only valid for OPA policies. | | `data.attributes.enforcement-level` | string | | The enforcement level of the policy. For Sentinel, valid values are `"hard-mandatory"`, `"soft-mandatory"`, and `"advisory"`. For OPA, Valid values are `"mandatory"`and `"advisory"`. Refer to [Managing Policies](/terraform/cloud-docs/policy-enforcement/manage-policy-sets) for details. | | `data.attributes.enforce` | array\[object] | | **DEPRECATED** Use `enforcement-level` instead. An array of enforcement configurations that map policy file paths to their enforcement modes. Policies support a single file, so this array should consist of a single element. For Sentinel, if the path in the enforcement map does not match the Sentinel policy (`<NAME>.sentinel`), then HCP Terraform uses the default `hard-mandatory` enforcement level. For OPA, the default enforcement level is `advisory`. | | `data.attributes.enforce[].path` | string | | **DEPRECATED** For Sentinel, must be `<NAME>.sentinel`, where `<NAME>` has the same value as `data.attributes.name`. For OPA, must be `<NAME>.rego`. | | `data.attributes.enforce[].mode` | string | | **DEPRECATED** Use `enforcement-level` instead. The enforcement level of the policy. For Sentinel, valid values are `"hard-mandatory"`, `"soft-mandatory"`, and `"advisory"`. For OPA, Valid values are `"mandatory"`and `"advisory"`. Refer to [Managing Policies](/terraform/cloud-docs/policy-enforcement/manage-policy-sets) for details. | | `data.relationships.policy-sets.data[]` | array\[object] | `[]` | A list of resource identifier objects to define which policy sets include the new policy. These objects must contain `id` and `type` properties, and the `type` property must be `policy-sets`. For example,`{ "id": "polset-3yVQZvHzf5j3WRJ1","type": "policy-sets" }`. | ### Sample Payload (Sentinel) ```json { "data": { "attributes": { "enforcement-level": "hard-mandatory", "name": "my-example-policy", "description": "An example policy.", "kind": "sentinel" }, "relationships": { "policy-sets": { "data": [ { "id": "polset-3yVQZvHzf5j3WRJ1", "type": "policy-sets" } ] } }, "type": "policies" } } ``` ### Sample Payload (OPA) -> **Note**: We have deprecated the `enforce` property in requests and responses but continue to provide it for backward compatibility. The below sample uses the deprecated `enforce` property. ```json { "data": { "attributes": { "enforce": [ { "path": "my-example-policy.rego", "mode": "advisory" } ], "name": "my-example-policy", "description": "An example policy.", "kind": "opa", "query": "terraform.main" }, "relationships": { "policy-sets": { "data": [ { "id": "polset-3yVQZvHzf5j3WRJ1", "type": "policy-sets" } ] } }, "type": "policies" } } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/organizations/my-organization/policies ``` ### Sample Response (Sentinel) ```json { "data": { "id":"pol-u3S5p2Uwk21keu1s", "type":"policies", "attributes": { "name":"my-example-policy", "description":"An example policy.", "enforcement-level":"advisory", "enforce": [ { "path":"my-example-policy.sentinel", "mode":"advisory" } ], "policy-set-count": 1, "updated-at": null }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" } }, "policy-sets": { "data": [ { "id": "polset-3yVQZvHzf5j3WRJ1", "type": "policy-sets" } ] } }, "links": { "self":"/api/v2/policies/pol-u3S5p2Uwk21keu1s", "upload":"/api/v2/policies/pol-u3S5p2Uwk21keu1s/upload" } } } ``` ### Sample Response (OPA) ```json { "data": { "id":"pol-u3S5p2Uwk21keu1s", "type":"policies", "attributes": { "name":"my-example-policy", "description":"An example policy.", "kind": "opa", "query": "terraform.main", "enforcement-level": "advisory", "enforce": [ { "path":"my-example-policy.rego", "mode":"advisory" } ], "policy-set-count": 1, "updated-at": null }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" } }, "policy-sets": { "data": [ { "id": "polset-3yVQZvHzf5j3WRJ1", "type": "policy-sets" } ] } }, "links": { "self":"/api/v2/policies/pol-u3S5p2Uwk21keu1s", "upload":"/api/v2/policies/pol-u3S5p2Uwk21keu1s/upload" } } } ``` ## Show a Policy `GET /policies/:policy_id` | Parameter | Description | | ------------ | --------------------------------------------------------------------------- | | `:policy_id` | The ID of the policy to show. Refer to [List Policies](/terraform/cloud-docs/api-docs/policies#list-policies) for reference information about finding IDs. | | Status | Response | Reason | | ------- | ------------------------------------------ | ------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "policies"`) | The request was successful | | [404][] | [JSON API error object][] | Policy not found or user unauthorized to perform action | ### Sample Request ```shell curl --request GET \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/policies/pol-oXUppaX2ximkqp8w ``` ### Sample Response ```json { "data": { "id": "pol-oXUppaX2ximkqp8w", "type": "policies", "attributes": { "name": "my-example-policy", "description":"An example policy.", "kind": "sentinel", "enforcement-level": "soft-mandatory", "enforce": [ { "path": "my-example-policy.sentinel", "mode": "soft-mandatory" } ], "policy-set-count": 1, "updated-at": "2018-09-11T18:21:21.784Z" }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" } }, "policy-sets": { "data": [ { "id": "polset-3yVQZvHzf5j3WRJ1", "type": "policy-sets" } ] } }, "links": { "self": "/api/v2/policies/pol-oXUppaX2ximkqp8w", "upload": "/api/v2/policies/pol-oXUppaX2ximkqp8w/upload", "download": "/api/v2/policies/pol-oXUppaX2ximkqp8w/download" } } } ``` ## Upload a Policy `PUT /policies/:policy_id/upload` | Parameter | Description | | ------------ | ------------------------------------------------------------------------------------------------------------------------------------ | | `:policy_id` | The ID of the policy to upload code to. Refer to [List Policies](/terraform/cloud-docs/api-docs/policies#list-policies) for reference information about finding the policy ID. The ID also appears in the response when you create a policy. | This endpoint uploads code to an existing Sentinel or OPA policy. -> **Note**: This endpoint does not use JSON-API's conventions for HTTP headers and body serialization. -> **Note**: This endpoint limits the size of uploaded policies to 10MB. If a larger payload is uploaded, an HTTP 413 error will be returned, and the policy will not be saved. Consider refactoring policies into multiple smaller, more concise documents if you reach this limit. ### Request Body This PUT endpoint requires the text of a valid Sentinel or OPA policy with a `Content-Type` of `application/octet-stream`. - Refer to [Defining Sentinel Policies](/terraform/cloud-docs/policy-enforcement/sentinel) for details about writing Sentinel code. - Refer to [Defining OPA Policies](/terraform/cloud-docs/policy-enforcement/opa) for details about writing OPA code. ### Sample Payload ```plain main = rule { true } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/octet-stream" \ --request PUT \ --data-binary @payload.file \ https://app.terraform.io/api/v2/policies/pol-u3S5p2Uwk21keu1s/upload ``` ## Update a Policy `PATCH /policies/:policy_id` | Parameter | Description | | ------------ | ----------------------------------------------------------------------------- | | `:policy_id` | The ID of the policy to update. Refer to [List Policies](/terraform/cloud-docs/api-docs/policies#list-policies) for reference information about finding IDs. | This endpoint can update the enforcement mode of an existing policy. To update the policy code itself, use the upload endpoint. | Status | Response | Reason | | ------- | ------------------------------------------ | -------------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "policies"`) | Successfully updated the policy | | [404][] | [JSON API error object][] | Policy not found, or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (missing attributes, wrong types, etc.) | ### Request Body This PATCH endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | ----------------------------------- | -------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `data.type` | string | | Must be `"policies"`. | | `data.attributes.description` | string | `null` | Text describing the policy's purpose. This field supports Markdown and appears in the HCP Terraform UI. | | `data.attributes.query` | string | | The OPA query to run. This is only valid for OPA policies. | | `data.attributes.enforcement-level` | string | | The enforcement level of the policy. For Sentinel, valid values are `"hard-mandatory"`, `"soft-mandatory"`, and `"advisory"`. For OPA, Valid values are `"mandatory"`and `"advisory"`. Refer to [Managing Policies](/terraform/cloud-docs/policy-enforcement/manage-policy-sets) for details. | | `data.attributes.enforce` | array\[object] | | **DEPRECATED** Use `enforcement-level` instead. An array of enforcement configurations that map policy file paths to their enforcement modes. Policies support a single file, so this array should consist of a single element. For Sentinel, if the path in the enforcement map does not match the Sentinel policy (`<NAME>.sentinel`), then HCP Terraform uses the default `hard-mandatory` enforcement level. For OPA, the default enforcement level is `advisory`. | | `data.attributes.enforce[].path` | string | | **DEPRECATED** For Sentinel, must be `<NAME>.sentinel`, where `<NAME>` has the same value as `data.attributes.name`. For OPA, must be `<NAME>.rego`. | | `data.attributes.enforce[].mode` | string | | **DEPRECATED** Use `enforcement-level` instead. The enforcement level of the policy. For Sentinel, valid values are `"hard-mandatory"`, `"soft-mandatory"`, and `"advisory"`. For OPA, Valid values are `"mandatory"`and `"advisory"`. Refer to [Managing Policies](/terraform/cloud-docs/policy-enforcement/manage-policy-sets) for details. | ### Sample Payload ```json { "data": { "attributes": { "enforcement-level": "soft-mandatory" }, "type":"policies" } } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request PATCH \ --data @payload.json \ https://app.terraform.io/api/v2/policies/pol-u3S5p2Uwk21keu1s ``` ### Sample Response ```json { "data": { "id":"pol-u3S5p2Uwk21keu1s", "type":"policies", "attributes": { "name":"my-example-policy", "description":"An example policy.", "kind": "sentinel", "enforcement-level": "soft-mandatory", "enforce": [ { "path":"my-example-policy.sentinel", "mode":"soft-mandatory" } ], "policy-set-count": 0, "updated-at":"2017-10-10T20:58:04.621Z" }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" } }, }, "links": { "self":"/api/v2/policies/pol-u3S5p2Uwk21keu1s", "upload":"/api/v2/policies/pol-u3S5p2Uwk21keu1s/upload", "download":"/api/v2/policies/pol-u3S5p2Uwk21keu1s/download" } } } ``` ## List Policies `GET /organizations/:organization_name/policies` | Parameter | Description | | -------------------- | -------------------------------------- | | `:organization_name` | The organization to list policies for. | | Status | Response | Reason | | ------- | ---------------------------------------------------- | -------------------------------------------------------------- | | [200][] | Array of [JSON API document][]s (`type: "policies"`) | Success | | [404][] | [JSON API error object][] | Organization not found, or user unauthorized to perform action | ### Query Parameters This endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters); remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. | Parameter | Description | | -------------- | --------------------------------------------------------------------------------------------------------------------------------- | | `page[number]` | **Optional.** If omitted, the endpoint will return the first page. | | `page[size]` | **Optional.** If omitted, the endpoint will return 20 policies per page. | | `search[name]` | **Optional.** Allows searching the organization's policies by name. | | `filter[kind]` | **Optional.** If specified, restricts results to those with the matching policy kind value. Valid values are `sentinel` and `opa` | | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ https://app.terraform.io/api/v2/organizations/my-organization/policies ``` ### Sample Response ```json { "data": [ { "attributes": { "enforcement-level": "advisory", "enforce": [ { "mode": "advisory", "path": "my-example-policy.sentinel" } ], "name": "my-example-policy", "description": "An example policy.", "policy-set-count": 0, "updated-at": "2017-10-10T20:52:13.898Z", "kind": "sentinel" }, "id": "pol-u3S5p2Uwk21keu1s", "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" } }, }, "links": { "download": "/api/v2/policies/pol-u3S5p2Uwk21keu1s/download", "self": "/api/v2/policies/pol-u3S5p2Uwk21keu1s", "upload": "/api/v2/policies/pol-u3S5p2Uwk21keu1s/upload" }, "type": "policies" }, { "id":"pol-vM2rBfj7V2Faq8By", "type":"policies", "attributes":{ "name":"policy1", "description":null, "enforcement-level": "advisory", "enforce":[ { "path":"policy1.rego", "mode":"advisory" } ], "policy-set-count":1, "updated-at":"2022-09-13T04:57:43.516Z", "kind":"opa", "query":"data.terraform.rules.policy1.rule" }, "relationships":{ "organization":{ "data":{ "id":"hashicorp", "type":"organizations" } }, "policy-sets":{ "data":[ { "id":"polset-FYu3k5WY5eecwwdt", "type":"policy-sets" } ] } }, "links":{ "self":"/api/v2/policies/pol-vM2rBfj7V2Faq8By", "upload":"/api/v2/policies/pol-vM2rBfj7V2Faq8By/upload", "download":"/api/v2/policies/pol-vM2rBfj7V2Faq8By/download" } } ] } ``` ## Delete a Policy `DELETE /policies/:policy_id` | Parameter | Description | | ------------ | ----------------------------------------------------------------------------- | | `:policy_id` | The ID of the policy to delete. Refer to [List Policies](/terraform/cloud-docs/api-docs/policies#list-policies) for reference information about finding IDs. | | Status | Response | Reason | | ------- | ------------------------- | -------------------------------------------------------- | | [204][] | No Content | Successfully deleted the policy | | [404][] | [JSON API error object][] | Policy not found, or user unauthorized to perform action | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request DELETE \ https://app.terraform.io/api/v2/policies/pl-u3S5p2Uwk21keu1s ``` ## Available Related Resources The GET endpoints above can optionally return related resources, if requested with [the `include` query parameter](/terraform/cloud-docs/api-docs#inclusion-of-related-resources). The following resource types are available: | Resource Name | Description | | ------------- | ------------------------------------------------------ | | `policy_sets` | Policy sets that any returned policies are members of. |
terraform
page title Policies API Docs HCP Terraform description Use the policies endpoint to manage Sentinel and OPA policies List show create upload update and delete policies using the HTTP API 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects Policies API Policies are rules that HCP Terraform enforces on Terraform runs You can use policies to validate that the Terraform plan complies with security rules and best practices HCP Terraform policy enforcement lets you use the policy as code frameworks Sentinel and Open Policy Agent OPA to apply policy checks to HCP Terraform workspaces Refer to Policy Enforcement terraform cloud docs policy enforcement for more details Policy sets terraform cloud docs policy enforcement manage policy sets are collections of policies that you can apply globally or to specific projects terraform cloud docs projects manage and workspaces in your organization For each run in the selected workspaces HCP Terraform checks the Terraform plan against the policy set and displays the results in the UI BEGIN TFC only name pnp callout include tfc package callouts policies mdx END TFC only name pnp callout This page documents the API endpoints to create read update and delete policies in an organization To manage policy sets use the Policy Sets API terraform cloud docs api docs policy sets To manage the policy results use the Runs API terraform cloud docs api docs run Create a Policy POST organizations organization name policies Parameter Description organization name The organization to create the policy in The organization must already exist in the system and the token authenticating the API request must have permission to manage policies More about permissions terraform cloud docs users teams organizations permissions permissions citation intentionally unused keep for maintainers This creates a new policy object for the organization but does not upload the actual policy code After creation you must use the Upload a Policy endpoint below upload a policy with the new policy s upload path This endpoint s response body includes the upload path in its links upload property Status Response Reason 200 JSON API document type policies Successfully created a policy 404 JSON API error object Organization not found or user unauthorized to perform action 422 JSON API error object Malformed request body missing attributes wrong types etc Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string Must be policies data attributes name string The name of the policy which can include letters numbers and You cannot modify this name after creation data attributes description string null Text describing the policy s purpose This field supports Markdown and appears in the HCP Terraform UI data attributes kind string sentinel The policy as code framework for the policy Valid values are sentinel and opa data attributes query string The OPA query to run Only valid for OPA policies data attributes enforcement level string The enforcement level of the policy For Sentinel valid values are hard mandatory soft mandatory and advisory For OPA Valid values are mandatory and advisory Refer to Managing Policies terraform cloud docs policy enforcement manage policy sets for details data attributes enforce array object DEPRECATED Use enforcement level instead An array of enforcement configurations that map policy file paths to their enforcement modes Policies support a single file so this array should consist of a single element For Sentinel if the path in the enforcement map does not match the Sentinel policy NAME sentinel then HCP Terraform uses the default hard mandatory enforcement level For OPA the default enforcement level is advisory data attributes enforce path string DEPRECATED For Sentinel must be NAME sentinel where NAME has the same value as data attributes name For OPA must be NAME rego data attributes enforce mode string DEPRECATED Use enforcement level instead The enforcement level of the policy For Sentinel valid values are hard mandatory soft mandatory and advisory For OPA Valid values are mandatory and advisory Refer to Managing Policies terraform cloud docs policy enforcement manage policy sets for details data relationships policy sets data array object A list of resource identifier objects to define which policy sets include the new policy These objects must contain id and type properties and the type property must be policy sets For example id polset 3yVQZvHzf5j3WRJ1 type policy sets Sample Payload Sentinel json data attributes enforcement level hard mandatory name my example policy description An example policy kind sentinel relationships policy sets data id polset 3yVQZvHzf5j3WRJ1 type policy sets type policies Sample Payload OPA Note We have deprecated the enforce property in requests and responses but continue to provide it for backward compatibility The below sample uses the deprecated enforce property json data attributes enforce path my example policy rego mode advisory name my example policy description An example policy kind opa query terraform main relationships policy sets data id polset 3yVQZvHzf5j3WRJ1 type policy sets type policies Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 organizations my organization policies Sample Response Sentinel json data id pol u3S5p2Uwk21keu1s type policies attributes name my example policy description An example policy enforcement level advisory enforce path my example policy sentinel mode advisory policy set count 1 updated at null relationships organization data id my organization type organizations policy sets data id polset 3yVQZvHzf5j3WRJ1 type policy sets links self api v2 policies pol u3S5p2Uwk21keu1s upload api v2 policies pol u3S5p2Uwk21keu1s upload Sample Response OPA json data id pol u3S5p2Uwk21keu1s type policies attributes name my example policy description An example policy kind opa query terraform main enforcement level advisory enforce path my example policy rego mode advisory policy set count 1 updated at null relationships organization data id my organization type organizations policy sets data id polset 3yVQZvHzf5j3WRJ1 type policy sets links self api v2 policies pol u3S5p2Uwk21keu1s upload api v2 policies pol u3S5p2Uwk21keu1s upload Show a Policy GET policies policy id Parameter Description policy id The ID of the policy to show Refer to List Policies terraform cloud docs api docs policies list policies for reference information about finding IDs Status Response Reason 200 JSON API document type policies The request was successful 404 JSON API error object Policy not found or user unauthorized to perform action Sample Request shell curl request GET H Authorization Bearer TOKEN H Content Type application vnd api json https app terraform io api v2 policies pol oXUppaX2ximkqp8w Sample Response json data id pol oXUppaX2ximkqp8w type policies attributes name my example policy description An example policy kind sentinel enforcement level soft mandatory enforce path my example policy sentinel mode soft mandatory policy set count 1 updated at 2018 09 11T18 21 21 784Z relationships organization data id my organization type organizations policy sets data id polset 3yVQZvHzf5j3WRJ1 type policy sets links self api v2 policies pol oXUppaX2ximkqp8w upload api v2 policies pol oXUppaX2ximkqp8w upload download api v2 policies pol oXUppaX2ximkqp8w download Upload a Policy PUT policies policy id upload Parameter Description policy id The ID of the policy to upload code to Refer to List Policies terraform cloud docs api docs policies list policies for reference information about finding the policy ID The ID also appears in the response when you create a policy This endpoint uploads code to an existing Sentinel or OPA policy Note This endpoint does not use JSON API s conventions for HTTP headers and body serialization Note This endpoint limits the size of uploaded policies to 10MB If a larger payload is uploaded an HTTP 413 error will be returned and the policy will not be saved Consider refactoring policies into multiple smaller more concise documents if you reach this limit Request Body This PUT endpoint requires the text of a valid Sentinel or OPA policy with a Content Type of application octet stream Refer to Defining Sentinel Policies terraform cloud docs policy enforcement sentinel for details about writing Sentinel code Refer to Defining OPA Policies terraform cloud docs policy enforcement opa for details about writing OPA code Sample Payload plain main rule true Sample Request shell curl header Authorization Bearer TOKEN header Content Type application octet stream request PUT data binary payload file https app terraform io api v2 policies pol u3S5p2Uwk21keu1s upload Update a Policy PATCH policies policy id Parameter Description policy id The ID of the policy to update Refer to List Policies terraform cloud docs api docs policies list policies for reference information about finding IDs This endpoint can update the enforcement mode of an existing policy To update the policy code itself use the upload endpoint Status Response Reason 200 JSON API document type policies Successfully updated the policy 404 JSON API error object Policy not found or user unauthorized to perform action 422 JSON API error object Malformed request body missing attributes wrong types etc Request Body This PATCH endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string Must be policies data attributes description string null Text describing the policy s purpose This field supports Markdown and appears in the HCP Terraform UI data attributes query string The OPA query to run This is only valid for OPA policies data attributes enforcement level string The enforcement level of the policy For Sentinel valid values are hard mandatory soft mandatory and advisory For OPA Valid values are mandatory and advisory Refer to Managing Policies terraform cloud docs policy enforcement manage policy sets for details data attributes enforce array object DEPRECATED Use enforcement level instead An array of enforcement configurations that map policy file paths to their enforcement modes Policies support a single file so this array should consist of a single element For Sentinel if the path in the enforcement map does not match the Sentinel policy NAME sentinel then HCP Terraform uses the default hard mandatory enforcement level For OPA the default enforcement level is advisory data attributes enforce path string DEPRECATED For Sentinel must be NAME sentinel where NAME has the same value as data attributes name For OPA must be NAME rego data attributes enforce mode string DEPRECATED Use enforcement level instead The enforcement level of the policy For Sentinel valid values are hard mandatory soft mandatory and advisory For OPA Valid values are mandatory and advisory Refer to Managing Policies terraform cloud docs policy enforcement manage policy sets for details Sample Payload json data attributes enforcement level soft mandatory type policies Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request PATCH data payload json https app terraform io api v2 policies pol u3S5p2Uwk21keu1s Sample Response json data id pol u3S5p2Uwk21keu1s type policies attributes name my example policy description An example policy kind sentinel enforcement level soft mandatory enforce path my example policy sentinel mode soft mandatory policy set count 0 updated at 2017 10 10T20 58 04 621Z relationships organization data id my organization type organizations links self api v2 policies pol u3S5p2Uwk21keu1s upload api v2 policies pol u3S5p2Uwk21keu1s upload download api v2 policies pol u3S5p2Uwk21keu1s download List Policies GET organizations organization name policies Parameter Description organization name The organization to list policies for Status Response Reason 200 Array of JSON API document s type policies Success 404 JSON API error object Organization not found or user unauthorized to perform action Query Parameters This endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs Parameter Description page number Optional If omitted the endpoint will return the first page page size Optional If omitted the endpoint will return 20 policies per page search name Optional Allows searching the organization s policies by name filter kind Optional If specified restricts results to those with the matching policy kind value Valid values are sentinel and opa Sample Request shell curl header Authorization Bearer TOKEN https app terraform io api v2 organizations my organization policies Sample Response json data attributes enforcement level advisory enforce mode advisory path my example policy sentinel name my example policy description An example policy policy set count 0 updated at 2017 10 10T20 52 13 898Z kind sentinel id pol u3S5p2Uwk21keu1s relationships organization data id my organization type organizations links download api v2 policies pol u3S5p2Uwk21keu1s download self api v2 policies pol u3S5p2Uwk21keu1s upload api v2 policies pol u3S5p2Uwk21keu1s upload type policies id pol vM2rBfj7V2Faq8By type policies attributes name policy1 description null enforcement level advisory enforce path policy1 rego mode advisory policy set count 1 updated at 2022 09 13T04 57 43 516Z kind opa query data terraform rules policy1 rule relationships organization data id hashicorp type organizations policy sets data id polset FYu3k5WY5eecwwdt type policy sets links self api v2 policies pol vM2rBfj7V2Faq8By upload api v2 policies pol vM2rBfj7V2Faq8By upload download api v2 policies pol vM2rBfj7V2Faq8By download Delete a Policy DELETE policies policy id Parameter Description policy id The ID of the policy to delete Refer to List Policies terraform cloud docs api docs policies list policies for reference information about finding IDs Status Response Reason 204 No Content Successfully deleted the policy 404 JSON API error object Policy not found or user unauthorized to perform action Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request DELETE https app terraform io api v2 policies pl u3S5p2Uwk21keu1s Available Related Resources The GET endpoints above can optionally return related resources if requested with the include query parameter terraform cloud docs api docs inclusion of related resources The following resource types are available Resource Name Description policy sets Policy sets that any returned policies are members of
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 Use the explorer endpoint to explore your data Query filter and sort data page title Explorer API Docs HCP Terraform from a variety of views using the HTTP API tfc only true
--- page_title: Explorer - API Docs - HCP Terraform description: >- Use the `/explorer` endpoint to explore your data. Query, filter, and sort data from a variety of views using the HTTP API. tfc_only: true --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects [speculative plans]: /terraform/cloud-docs/run/remote-operations#speculative-plans # Explorer API Explorer allows you to query your HCP Terraform data across workspaces in an organization. You can select from a variety of available views and supply optional sort and filter parameters to present your data in the format that best suits your needs. Queries are scoped to the organization level. You must have owner permissions in the organization, or read access to workspaces and projects. ## Execute a query `GET /organizations/:organization_name/explorer` | Parameter | Description | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `:organization_name` | The name of the organization to query. The organization must already exist and you must have permissions to read the organization's workspaces and projects. | -> **Note:** Explorer is restricted to the owners team, teams with the "Read all workspaces" permission, teams with the "Read all projects" permission, and the [organization API token](/terraform/cloud-docs/users-teams-organizations/api-tokens#organization-api-tokens). Explorer queries will time out after 60 seconds. If the desired query is timing out, try a simpler query that uses less filters. Requests to the explorer are subject to [rate limiting](/terraform/cloud-docs/api-docs#rate-limiting). Explorer will return a 429 status code when rate limiting is active for the authenticated context. Data presented by the explorer is eventually consistent. Query results typically contain data that represents the current state of the system, but in some cases a small delay may be necessary before querying for data that has recently been updated. ### Query parameters This GET endpoint requires a query string that supports the following properties. | Parameter | Description | | -------------- | ----------------------------------------------------------------------------- | | `type` | **Required.** Must be one of the following available views: `workspaces`, `tf_versions`, `providers`, or `modules`. See the [View Types](#view-types) section for more information about each. | | `sort` | Optionally sort the returned data by the specified field name. The field name must use snake case and exist within the supplied view type. The field name supplied can be prefixed with a hyphen (`-`) to perform a descending sort. | | `filter` | Optionally specify one or more filters to limit the data returned. See [Filtering](#filtering) for more information. | | `fields` | Optionally limit the data returned only to the specified fields. The field names supplied must use snake case and be submitted in comma-separated format. If omitted, all available fields will be returned for the requested view type. | | `page[number]` | Optional. If omitted, the endpoint will return the first page. | | `page[size]` | Optional. If omitted, the endpoint will use a default page size. | ### View Types Explorer queries each require a view, specified by the `type` query string parameter. There are several contextual views available for querying: | Type | Description | | ------------- | ----------------------------------------------------------------------------- | | `workspaces` | Information about the workspaces in the target organization and any current runs associated with them. Each row returned represents a single workspace. See [View Type: workspaces](#view-type-workspaces) for available fields. | | `tf_versions` | Information about the Terraform versions in use across this organization. Each row returned represents a Terraform version in use. See [View Type: tf_versions](#view-type-tf_versions) for available fields. | | `providers` | Information about the Terraform providers in use across the target organization. Each row returned represents a Terraform provider in use. See [View Type: providers](#view-type-providers) for available fields. | | `modules` | Information about the Terraform modules in use across the target organization. Each row returned represents a Terraform module in use. See [View Type: modules](#view-type-modules) for available fields. | The fields returned by a given query are specific to the view type used. The fields available for each view type are detailed below: #### View Type: `workspaces` | Field | Type | Description | | --------------------------------- | ---------- | ----------------------------------------------------------------------------- | | `all_checks_succeeded` | `boolean` | True if checks have succeeded for the workspace, false otherwise. | | `checks_errored` | `number` | The number of checks that errored without completing. | | `checks_failed` | `number` | The number of checks that completed and failed. | | `checks_passed` | `number` | The number of checks that completed and passed. | | `checks_unknown` | `number` | The number of checks that could not be assessed. | | `current_run_applied_at` | `datetime` | Represents the time that this workspace's current run was applied. | | `current_run_external_id` | `string` | The external ID of this workspace's current run. | | `current_run_status` | `string` | The status of this workspace's current run. | | `drifted` | `boolean` | True if drift has been detected for the workspace, false otherwise. | | `external_id` | `string` | The external ID of this workspace. | | `module_count` | `number` | The number of distinct modules used by this workspace. | | `modules` | `string` | A comma separated list of modules used by this workspace. | | `organization_name` | `string` | The name of the organization this workspace belongs to. | | `project_external_id` | `string` | The external ID of the project this workspace belongs to. | | `project_name` | `string` | The name of the project this workspace belongs to. | `provider_count` | `number` | The number of distinct providers used in this workspace. | | `providers` | `string` | A comma separated list of providers used in this workspace. | | `resources_drifted` | `number` | The count of resources that drift was detected for. | | `resources_undrifted` | `number` | The count of resources that drift was not detected for. | | `state_version_terraform_version` | `string` | The Terraform version used to create the current run's state file. | | `vcs_repo_identifier` | `string` | The name of the repository configured for this workspace, if available. | | `workspace_created_at` | `datetime` | The time this workspace was created. | | `workspace_name` | `string` | The name of this workspace. | | `workspace_terraform_version` | `string` | The Terraform version currently configured for this workspace. | | `workspace_updated_at` | `datetime` | The time this workspace was last updated. | #### View Type: `tf_versions` | Field | Type | Description | | ------------------ | -------- | ------------------------------------------------------------------ | | `version` | `string` | The semantic version string for this Terraform version. | | `workspace_count` | `number` | The number of workspaces using this terraform version. | | `workspaces` | `string` | A comma-separated list of workspaces using this terraform version. | #### View Type: `providers` | Field | Type | Description | | ------------------| -------- | --------------------------------------------------------- | | `name` | `string` | The name of this provider. | | `source` | `string` | The source of this provider. | | `version` | `string` | The semantic version string for this provider. | | `workspace_count` | `number` | The number of workspaces using this provider. | | `workspaces` | `string` | A comma-separated list of workspaces using this provider. | #### View Type: `modules` | Field | Type | Description | | ------------------| -------- | ------------------------------------------------------- | | `name` | `string` | The name of this module. | | `source` | `string` | The source of this module. | | `version` | `string` | The semantic version string for this module. | | `workspace_count` | `number` | The number of workspaces using this module version. | | `workspaces` | `string` | A comma-separated list of workspaces using this module version. | ### Filtering The explorer can present filtered data from any view type using a variety of operators. Filter strings begin with the reserved string `filter`, and are passed as URL query string parameters using key-value pairs. The parameter key contains the filter's target field and operator, and the parameter value contains the filter value to be used during the query. Multiple filters can be used in a query by providing multiple filter query string parameters separated with `&`. When multiple filters are used, a logical AND is used to evaluate the results. Each filter string must use the following format: ``` filter[<FILTER_INDEX>][<FIELD_NAME>][<FIELD_OPERATOR>][FIELD_VALUE_INDEX]=<FILTER VALUE> ``` **Filter string sub-parameters** - **FILTER_INDEX**: The index of the filter. Each filter requires a unique index. The first filter should use a `0` and each additional filter should use an index that is the previous filter's index incremented by 1. - **FIELD_NAME**: The name of the field to apply the filter to. The field must be a valid field for the view type being queried. See [View Types](#view-types) for a list of fields available for each type. - **FIELD_OPERATOR**: The operator to use when filtering. Must be supported by the field type being filtered. See [Filter Operators](#filter-operators) for the available operators and their supported field types. - **FIELD_VALUE_INDEX**: Must be `0`. This sub-parameter is reserved for future use. - **FILTER_VALUE**: The filter value used by the filter during the query. Once the desired filter strings have been added to a request URI, they should be percent-encoded along with the rest of the query string parameters. #### Sample Filter Strings **View Type: `workspace`** _Show workspaces that contain `test` in their name:_ ``` filter[0][workspace_name][contains][0]=test ``` _After encoding:_ ``` filter%5B0%5D%5Bworkspace_name%5D%5Bcontains%5D%5B0%5D=test ``` **View Type: `modules`** _Show modules that contain `aws` in their name and version string equal to `1.1`_ ``` filter[0][name][contains][0]=aws&filter[0][version][is][0]=1.1 ``` _After encoding:_ ``` filter%5B0%5D%5Bname%5D%5Bcontains%5D%5B0%5D=aws&filter%5B0%5D%5Bversion%5D%5Bis%5D%5B0%5D=1.1 ``` #### Filter Operators | Operator | Supported Field Types | Description | | ------------------ | ----------------------------- | ----------- | | `is` | `boolean`, `number`, `string` | Filters data to rows where the field value is equivalent to the filter value. | | `is_not` | `number`, `string` | Filters data to rows where the field value is different from the filter value. | | `contains` | `string` | Filters data to rows where the field value contains the filter value as a sub-string. | | `does not contain` | `string` | Filters data to rows where the field value does not contain the filter value as a sub-string. | | `is_empty` | `boolean`, `number`, `string` | Filters data to rows where the field does not contain a value. | | `is_not_empty` | `boolean`, `number`, `string` | Filters data to rows where the field contains any value. | | `gt` | `number` | Filters data to rows where the field value is greater than the filter value. | | `lt` | `number` | Filters data to rows where the field value is less than the filter value. | | `gteq` | `number` | Filters data to rows where the field value is greater than or equal to the filter value. | | `lteq` | `number` | Filters data to rows where the field value is less than or equal to the filter value. | | `is_before` | `datetime` | Filters data to rows where the field value is earlier than the filter value. ISO 8601 formatted timestamps are required for filter values. If no time zone offset is provided, the filter value will be interpreted as UTC. | | `is_after` | `datetime` | Filters data to rows where the field value is earlier than the filter value. ISO 8601 formatted timestamps are required for filter values. If no time zone offset is provided, the filter value will be interpreted as UTC. | ### Pagination This endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. ### Sample requests **View Type: `workspaces`** _Show data for all workspaces_ ```shell curl \ --header "Authorization: Bearer $TOKEN" \ 'https://app.terraform.io/api/v2/organizations/$ORG_NAME/explorer?type=workspaces' ``` _Show data for all workspaces with `test` in their name_ ```shell curl \ --header "Authorization: Bearer $TOKEN" \ 'https://app.terraform.io/api/v2/organizations/$ORG_NAME/explorer?type=workspaces&&filter%5B0%5D%5Bworkspace_name%5D%5Bcontains%5D%5B0%5D=test' ``` **View Type: `modules`** _Show modules used across all workspaces_ ```shell curl \ --header "Authorization: Bearer $TOKEN" \ 'https://app.terraform.io/api/v2/organizations/$ORG_NAME/explorer?type=modules' ``` _Show public modules only_ ```shell curl \ --header "Authorization: Bearer $TOKEN" \ 'https://app.terraform.io/api/v2/organizations/$ORG_NAME/explorer?type=modules&filter%5B0%5D%5Bregistry_type%5D%5Bis%5D%5B0%5D=public' ``` **View Type: `provider`** _Show providers used across all workspaces_ ```shell curl \ --header "Authorization: Bearer $TOKEN" \ 'https://app.terraform.io/api/v2/organizations/$ORG_NAME/explorer?type=providers' ``` _Show most used providers across all workspaces_ ```shell curl \ --header "Authorization: Bearer $TOKEN" \ 'https://app.terraform.io/api/v2/organizations/$ORG_NAME/explorer?type=providers&sort=-workspace_count' ``` **View Type: `tf_versions`** _Show Terraform versions used across all workspaces_ ```shell curl \ --header "Authorization: Bearer $TOKEN" \ 'https://app.terraform.io/api/v2/organizations/$ORG_NAME/explorer?type=tf_versions' ``` _Show all Terraform versions used in more than 10 workspaces_ ```shell curl \ --header "Authorization: Bearer $TOKEN" \ 'https://app.terraform.io/api/v2/organizations/$ORG_NAME/explorer?type=tf_versions&filter%5B0%5D%5Bworkspace_count%5D%5Bgt%5D%5B0%5D=10' ``` ### Sample response _Show data for all workspaces_ ```json { "data": [ { "attributes": { "all-checks-succeeded": true, "checks-errored": 0, "checks-failed": 0, "checks-passed": 0, "checks-unknown": 0, "current-run-applied-at": null, "current-run-external-id": "run-rdoEKh2Gy3K6SbCZ", "current-run-status": "planned_and_finished", "drifted": false, "external-id": "ws-j2sAeWRxou1b5HYf", "module-count": 0, "modules": null, "organization-name": "acme-corp", "project-external-id": "prj-V61QLE8tvs4NvVZG", "project-name": "Default Project", "provider-count": 0, "providers": null, "resources-drifted": 0, "resources-undrifted": 0, "state-version-terraform-version": "1.5.7", "vcs-repo-identifier": null, "workspace-created-at": "2023-10-17T21:56:45.570+00:00", "workspace-name": "payments-service", "workspace-terraform-version": "1.5.7", "workspace-updated-at": "2023-12-08T19:58:15.513+00:00" }, "id": "ws-j2sAWeRxuo1b5HYf", "type": "visibility-workspace" }, { "attributes": { "all-checks-succeeded": true, "checks-errored": 0, "checks-failed": 0, "checks-passed": 0, "checks-unknown": 0, "current-run-applied-at": "2023-08-18T16:24:59.000+00:00", "current-run-external-id": "run-9MmJaoQTvDCh5wUa", "current-run-status": "applied", "drifted": true, "external-id": "ws-igUVNQSYVXRkhYuo", "module-count": 0, "modules": null, "organization-name": "acme-corp", "project-external-id": "prj-uU2xNqGeG86U9WgT", "project-name": "web", "provider-count": 0, "providers": null, "resources-drifted": 3, "resources-undrifted": 3, "state-version-terraform-version": "1.4.5", "vcs-repo-identifier": "acmecorp/api", "workspace-created-at": "2023-04-25T17:09:14.960+00:00", "workspace-name": "api-service", "workspace-terraform-version": "1.4.5", "workspace-updated-at": "2023-12-08T20:43:16.779+00:00" }, "id": "ws-igUNVQSYXVRkhYuo", "type": "visibility-workspace" } ], "links": { "self": "https://app.terraform.io/api/v2/organizations/acme-corp/explorer?page%5Bnumber%5D=1&page%5Bsize%5D=20&type=workspaces", "first": "https://app.terraform.io/api/v2/organizations/acme-corp/explorer?page%5Bnumber%5D=1&page%5Bsize%5D=20&type=workspaces", "last": "https://app.terraform.io/api/v2/organizations/acme-corp/explorer?page%5Bnumber%5D=1&page%5Bsize%5D=20&type=workspaces", "prev": null, "next": null }, "meta": { "pagination": { "current-page": 1, "page-size": 20, "next-page": null, "prev-page": null, "total-pages": 1, "total-count": 2 } } } ``` ## Export data as CSV `GET /organizations/:organization_name/explorer/export/csv` | Parameter | Description | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `:organization_name` | The name of the organization to query. The organization must already exist in the system, and the user must have permissions to read the workspaces and projects within it. | This endpoint can be used to download a full, unpaged export of the query results in CSV format (with the filter, sort, and field selections applied). Explorer queries will time out after 60 seconds. If the desired query is timing out, try a simpler query that uses less filters. Requests to the explorer are subject to [rate limiting](/terraform/cloud-docs/api-docs#rate-limiting). Explorer will return a 429 status code when rate limiting is active for the authenticated context. Data presented by the explorer is eventually consistent. Query results typically contain data that represents the current state of the system, but in some cases a small delay may be necessary before querying for data that has recently been updated. ### Query parameters This GET endpoint supports the same query string parameters as the Explorer [Query endpoint](#execute-a-query). ### Sample requests **View Type: `workspaces`** _Show data for all workspaces_ ```shell curl \ --header "Authorization: Bearer $TOKEN" \ https://app.terraform.io/api/v2/organizations/$ORG_NAME/explorer/export/csv?type=workspaces ``` ### Sample response _Show data for all workspaces_ ```csv all_checks_succeeded,checks_errored,checks_failed,checks_passed,checks_unknown,current_run_applied_at,current_run_external_id,current_run_status,drifted,external_id,module_count,modules,organization_name,project_external_id,project_name,provider_count,providers,resources_drifted,resources_undrifted,state_version_terraform_version,vcs_repo_identifier,workspace_created_at,workspace_name,workspace_terraform_version,workspace_updated_at "true","0","0","0","0","","run-rdoEKh2Gy3K6SbCZ","planned_and_finished","false","ws-j2sAeWRxou1b5HYf","0","","acme-corp","prj-V61QLE8tvs4NvVZG","Default Project","0","","0","0","1.5.7","","2023-10-17T21:56:45+00:00","payments-service","1.5.7","2023-12-13T15:48:16+00:00" "true","0","0","0","0","2023-08-18T16:24:59+00:00","run-9MmJaoQTvDCh5wUa","applied","true","ws-igUVNQSYVXRkhYuo","0","","acme-corp","prj-uU2xNqGeG86U9WgT","web","0","","3","3","1.4.5","acmecorp/api","2023-04-25T17:09:14+00:00","api-service","1.4.5","2023-12-13T15:29:03+00:00" ``` ## List saved views -> **Note**: The ability to save views in the explorer is in public beta. All APIs and workflows are subject to change. Use this endpoint to display all of the explorer's [saved views](/terraform/cloud-docs/workspaces/explorer#saved-views) in an organization. `GET /api/v2/organizations/:organization_name/explorer/views` | Parameter | Description | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `:organization_name` | The name of the organization to query. To view a query, you must have permission to read the workspaces and projects within that query. | ### Sample request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --request GET \ 'https://app.terraform.io/api/v2/organizations/$ORG_NAME/explorer/views' ``` ### Sample response ```json { "data": [{ "id": "sq-P9Yn6Ad6EiVMz77s", "type": "explorer-saved-queries", "attributes": { "name": "my saved query", "created-at": "2024-10-11T16:18:51.442Z", "query": { "filter": [{ "field": "workspace_name", "operator": "contains", "value": ["child"], }, { "field": "workspace_name", "operator": "contains", "value": ["-"], }], "type": "workspaces" }, "query-type": "workspaces" } }] } ``` ## Create saved view -> **Note**: The ability to save views in the explorer is in public beta. All APIs and workflows are subject to change. Use this endpoint to create a [saved view](/terraform/cloud-docs/workspaces/explorer#saved-views) in the explorer. `POST /api/v2/organizations/:organization_name/explorer/views` | Parameter | Description | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `:organization_name` | The name of the organization to query. To view a query, you must have permission to read the workspaces and projects within that query. | To create a saved view, provide the following data in your payload. | Key path | Type | Default | Description | |------------|------|---------|-------------| | `data.name` | string | | The name of the saved view. | | `data.query_type` | string | | The primary type that the view is querying. Refer to [View Types](#view-types) for details. | | `data.query` | object | | A list of filters, fields, and sorting rules for the view. Refer to [Query parameters](#query-parameters) for full details. | | `data.query.filter` | array\[objects]| | A list of filters composed of fields, operators, and values. | | `data.query.filter.field` | string | | The field name to filter by. | | `data.query.filter.operator` | string | | The operator applied to field and value. | | `data.query.filter.value` | array\[strings] | | A list of values to filter by. | | `data.query.fields` | array\[strings] | | A list of fields to include in the view. | | `data.query.sort` | array\[strings] | | A list of fields to sort by. Prefix with `-` for descending sort. | ### Sample request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --request POST \ --data @payload.json \ 'https://app.terraform.io/api/v2/organizations/$ORG_NAME/explorer/views' ``` ### Sample response ```json { "data": { "id": "sq-P9Yn6Ad6EiVMz77s", "type": "explorer-saved-queries", "attributes": { "name": "my saved query", "created-at": "2024-10-11T16:18:51.442Z", "query": { "filter": [{ "field": "workspace_name", "operator": "contains", "value": ["child"], }, { "field": "workspace_name", "operator": "contains", "value": ["-"], }], "type": "workspaces" }, "query-type": "workspaces" } } } ``` ## Show saved view Use this endpoint to display a specific saved view from the explorer. `GET /api/v2/organizations/:organization_name/explorer/views/:view_id` | Parameter | Description | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `:organization_name` | The name of the organization to query. To view a query, you must have permission to read the workspaces and projects within that query. | | `:view_id` | The ID of the saved view to show. | ### Sample request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --request GET \ 'https://app.terraform.io/api/v2/organizations/$ORG_NAME/explorer/views/$VIEW_ID` ``` ### Sample response ```json { "data": { "id": "sq-P9Yn6Ad6EiVMz77s", "type": "explorer-saved-queries", "attributes": { "name": "my saved query", "created-at": "2024-10-11T16:18:51.442Z", "query": { "filter": [{ "field": "workspace_name", "operator": "contains", "value": ["child"], }, { "field": "workspace_name", "operator": "contains", "value": ["-"], }], "type": "workspaces" }, "query-type": "workspaces" } } } ``` ## Update a saved view Use this endpoint to update the data a saved view queries. `PATCH /api/v2/organizations/:organization_name/explorer/views/:view_id` | Parameter | Description | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `:organization_name` | The name of the organization to query. To view a query, you must have permission to read the workspaces and projects within that query. | | `:view_id` | The external id of the saved view to update. | You must have the following fields in the payload for your request. | Key path | Type | Default | Description | |------------|------|---------|-------------| | `data.name` | string | | The name of the saved view. | | `data.query` | object | | A list of filters, fields, and sorting rules for the view. See [Query parameters](#query-parameters) for full details. | | `data.query.filter` | array\[objects]| | A list of filters composed of fields, operators, and values. See [Filtering](#filtering) for more information. | | `data.query.filter.field` | string | | The field name to filter by. | | `data.query.filter.operator` | string | | The operator applied to field and value. | | `data.query.filter.value` | array\[strings] | | A list of values to filter by. | | `data.query.fields` | array\[strings] | | A list of fields to include in the view. Refer to [execute a query](#execute-a-query) for a list of available parameters. | | `data.query.sort` | array\[strings] | | A list of fields to sort by. Prefix with `-` for descending sort. | ### Sample request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --request PATCH \ --data @payload.json \ 'https://app.terraform.io/api/v2/organizations/$ORG_NAME/explorer/viewsi/$VIEW_ID' ``` ### Sample response ```json { "data": { "id": "sq-P9Yn6Ad6EiVMz77s", "type": "explorer-saved-queries", "attributes": { "name": "my saved query", "created-at": "2024-10-11T16:18:51.442Z", "query": { "filter": [{ "field": "workspace_name", "operator": "contains", "value": ["candy"], }, { "field": "workspace_name", "operator": "contains", "value": ["pumpkins"], }], "type": "workspaces" }, "query-type": "workspaces" } } } ``` ## Delete a saved view Use this endpoint to delete a saved view. `DELETE /api/v2/organizations/:organization_name/explorer/views/:view_id` | Parameter | Description | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `:organization_name` | The name of the organization to query. To view a query, you must have permission to read the workspaces and projects within that query. | | `:view_id` | The ID of the saved view you want to delete. | ### Sample request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --request DELETE \ 'https://app.terraform.io/api/v2/organizations/$ORG_NAME/explorer/views/$VIEW_ID` ``` ### Sample response ```json { "data": { "id": "sq-P9Yn6Ad6EiVMz77s", "type": "explorer-saved-queries", "attributes": { "name": "my saved query", "created-at": "2024-10-11T16:18:51.442Z", "query": { "filter": [{ "field": "workspace_name", "operator": "contains", "value": ["candy"], }, { "field": "workspace_name", "operator": "contains", "value": ["pumpkins"], }], "type": "workspaces" }, "query-type": "workspaces" } } } ``` ## Query a saved view Re-execute a saved view's query to retrieve current results. `GET /api/v2/organizations/:organization_name/explorer/views/:view_id/results` | Parameter | Description | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `:organization_name` | The name of the organization to query. To view a query, you must have permission to read the workspaces and projects within that query. | | `:view_id` | The ID of the saved view to re-query. | ### Sample request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --request GET \ 'https://app.terraform.io/api/v2/organizations/$ORG_NAME/explorer/views/$VIEW_ID/results` ``` ### Sample response ```json { "data": [ { "attributes": { "all-checks-succeeded": true, "checks-errored": 0, "checks-failed": 0, "checks-passed": 0, "checks-unknown": 0, "current-run-applied-at": null, "current-run-external-id": "run-rdoEKh2Gy3K6SbCZ", "current-run-status": "planned_and_finished", "drifted": false, "external-id": "ws-j2sAeWRxou1b5HYf", "module-count": 0, "modules": null, "organization-name": "acme-corp", "project-external-id": "prj-V61QLE8tvs4NvVZG", "project-name": "Default Project", "provider-count": 0, "providers": null, "resources-drifted": 0, "resources-undrifted": 0, "state-version-terraform-version": "1.5.7", "vcs-repo-identifier": null, "workspace-created-at": "2023-10-17T21:56:45.570+00:00", "workspace-name": "candy distribution system", "workspace-terraform-version": "1.5.7", "workspace-updated-at": "2023-12-08T19:58:15.513+00:00" }, "id": "ws-j2sAWeRxuo1b5HYf", "type": "visibility-workspace" }, { "attributes": { "all-checks-succeeded": true, "checks-errored": 0, "checks-failed": 0, "checks-passed": 0, "checks-unknown": 0, "current-run-applied-at": "2023-08-18T16:24:59.000+00:00", "current-run-external-id": "run-9MmJaoQTvDCh5wUa", "current-run-status": "applied", "drifted": true, "external-id": "ws-igUVNQSYVXRkhYuo", "module-count": 0, "modules": null, "organization-name": "acme-corp", "project-external-id": "prj-uU2xNqGeG86U9WgT", "project-name": "web", "provider-count": 0, "providers": null, "resources-drifted": 3, "resources-undrifted": 3, "state-version-terraform-version": "1.4.5", "vcs-repo-identifier": "acmecorp/api", "workspace-created-at": "2023-04-25T17:09:14.960+00:00", "workspace-name": "pumpkin smasher", "workspace-terraform-version": "1.4.5", "workspace-updated-at": "2023-12-08T20:43:16.779+00:00" }, "id": "ws-igUNVQSYXVRkhYuo", "type": "visibility-workspace" } ], "links": { "self": "https://app.terraform.io/api/v2/organizations/acme-corp/explorer?page%5Bnumber%5D=1&page%5Bsize%5D=20&type=workspaces", "first": "https://app.terraform.io/api/v2/organizations/acme-corp/explorer?page%5Bnumber%5D=1&page%5Bsize%5D=20&type=workspaces", "last": "https://app.terraform.io/api/v2/organizations/acme-corp/explorer?page%5Bnumber%5D=1&page%5Bsize%5D=20&type=workspaces", "prev": null, "next": null }, "meta": { "pagination": { "current-page": 1, "page-size": 20, "next-page": null, "prev-page": null, "total-pages": 1, "total-count": 2 } } } ``` ## Query a saved view as CSV Re-execute a saved view's query to retrieve current results, HCP Terraform returns results as a CSV. `GET /api/v2/organizations/:organization_name/explorer/views/:view_id/csv` | Parameter | Description | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `:organization_name` | The name of the organization to query. To view a query, you must have permission to read the workspaces and projects within that query. | | `:view_id` | The external id of the saved view to query. | ### Sample request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --request GET \ 'https://app.terraform.io/api/v2/organizations/$ORG_NAME/explorer/views/$VIEW_ID/csv` ``` ### Sample response ```csv all_checks_succeeded,checks_errored,checks_failed,checks_passed,checks_unknown,current_run_applied_at,current_run_external_id,current_run_status,drifted,external_id,module_count,modules,organization_name,project_external_id,project_name,provider_count,providers,resources_drifted,resources_undrifted,state_version_terraform_version,vcs_repo_identifier,workspace_created_at,workspace_name,workspace_terraform_version,workspace_updated_at "true","0","0","0","0","","run-rdoEKh2Gy3K6SbCZ","planned_and_finished","false","ws-j2sAeWRxou1b5HYf","0","","acme-corp","prj-V61QLE8tvs4NvVZG","Default Project","0","","0","0","1.5.7","","2023-10-17T21:56:45+00:00","candy distribution service","1.5.7","2023-12-13T15:48:16+00:00" "true","0","0","0","0","2023-08-18T16:24:59+00:00","run-9MmJaoQTvDCh5wUa","applied","true","ws-igUVNQSYVXRkhYuo","0","","acme-corp","prj-uU2xNqGeG86U9WgT","web","0","","3","3","1.4.5","acmecorp/api","2023-04-25T17:09:14+00:00","api-service","1.4.5","2023-12-13T15:29:03+00:00" ``
terraform
page title Explorer API Docs HCP Terraform description Use the explorer endpoint to explore your data Query filter and sort data from a variety of views using the HTTP API tfc only true 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects speculative plans terraform cloud docs run remote operations speculative plans Explorer API Explorer allows you to query your HCP Terraform data across workspaces in an organization You can select from a variety of available views and supply optional sort and filter parameters to present your data in the format that best suits your needs Queries are scoped to the organization level You must have owner permissions in the organization or read access to workspaces and projects Execute a query GET organizations organization name explorer Parameter Description organization name The name of the organization to query The organization must already exist and you must have permissions to read the organization s workspaces and projects Note Explorer is restricted to the owners team teams with the Read all workspaces permission teams with the Read all projects permission and the organization API token terraform cloud docs users teams organizations api tokens organization api tokens Explorer queries will time out after 60 seconds If the desired query is timing out try a simpler query that uses less filters Requests to the explorer are subject to rate limiting terraform cloud docs api docs rate limiting Explorer will return a 429 status code when rate limiting is active for the authenticated context Data presented by the explorer is eventually consistent Query results typically contain data that represents the current state of the system but in some cases a small delay may be necessary before querying for data that has recently been updated Query parameters This GET endpoint requires a query string that supports the following properties Parameter Description type Required Must be one of the following available views workspaces tf versions providers or modules See the View Types view types section for more information about each sort Optionally sort the returned data by the specified field name The field name must use snake case and exist within the supplied view type The field name supplied can be prefixed with a hyphen to perform a descending sort filter Optionally specify one or more filters to limit the data returned See Filtering filtering for more information fields Optionally limit the data returned only to the specified fields The field names supplied must use snake case and be submitted in comma separated format If omitted all available fields will be returned for the requested view type page number Optional If omitted the endpoint will return the first page page size Optional If omitted the endpoint will use a default page size View Types Explorer queries each require a view specified by the type query string parameter There are several contextual views available for querying Type Description workspaces Information about the workspaces in the target organization and any current runs associated with them Each row returned represents a single workspace See View Type workspaces view type workspaces for available fields tf versions Information about the Terraform versions in use across this organization Each row returned represents a Terraform version in use See View Type tf versions view type tf versions for available fields providers Information about the Terraform providers in use across the target organization Each row returned represents a Terraform provider in use See View Type providers view type providers for available fields modules Information about the Terraform modules in use across the target organization Each row returned represents a Terraform module in use See View Type modules view type modules for available fields The fields returned by a given query are specific to the view type used The fields available for each view type are detailed below View Type workspaces Field Type Description all checks succeeded boolean True if checks have succeeded for the workspace false otherwise checks errored number The number of checks that errored without completing checks failed number The number of checks that completed and failed checks passed number The number of checks that completed and passed checks unknown number The number of checks that could not be assessed current run applied at datetime Represents the time that this workspace s current run was applied current run external id string The external ID of this workspace s current run current run status string The status of this workspace s current run drifted boolean True if drift has been detected for the workspace false otherwise external id string The external ID of this workspace module count number The number of distinct modules used by this workspace modules string A comma separated list of modules used by this workspace organization name string The name of the organization this workspace belongs to project external id string The external ID of the project this workspace belongs to project name string The name of the project this workspace belongs to provider count number The number of distinct providers used in this workspace providers string A comma separated list of providers used in this workspace resources drifted number The count of resources that drift was detected for resources undrifted number The count of resources that drift was not detected for state version terraform version string The Terraform version used to create the current run s state file vcs repo identifier string The name of the repository configured for this workspace if available workspace created at datetime The time this workspace was created workspace name string The name of this workspace workspace terraform version string The Terraform version currently configured for this workspace workspace updated at datetime The time this workspace was last updated View Type tf versions Field Type Description version string The semantic version string for this Terraform version workspace count number The number of workspaces using this terraform version workspaces string A comma separated list of workspaces using this terraform version View Type providers Field Type Description name string The name of this provider source string The source of this provider version string The semantic version string for this provider workspace count number The number of workspaces using this provider workspaces string A comma separated list of workspaces using this provider View Type modules Field Type Description name string The name of this module source string The source of this module version string The semantic version string for this module workspace count number The number of workspaces using this module version workspaces string A comma separated list of workspaces using this module version Filtering The explorer can present filtered data from any view type using a variety of operators Filter strings begin with the reserved string filter and are passed as URL query string parameters using key value pairs The parameter key contains the filter s target field and operator and the parameter value contains the filter value to be used during the query Multiple filters can be used in a query by providing multiple filter query string parameters separated with When multiple filters are used a logical AND is used to evaluate the results Each filter string must use the following format filter FILTER INDEX FIELD NAME FIELD OPERATOR FIELD VALUE INDEX FILTER VALUE Filter string sub parameters FILTER INDEX The index of the filter Each filter requires a unique index The first filter should use a 0 and each additional filter should use an index that is the previous filter s index incremented by 1 FIELD NAME The name of the field to apply the filter to The field must be a valid field for the view type being queried See View Types view types for a list of fields available for each type FIELD OPERATOR The operator to use when filtering Must be supported by the field type being filtered See Filter Operators filter operators for the available operators and their supported field types FIELD VALUE INDEX Must be 0 This sub parameter is reserved for future use FILTER VALUE The filter value used by the filter during the query Once the desired filter strings have been added to a request URI they should be percent encoded along with the rest of the query string parameters Sample Filter Strings View Type workspace Show workspaces that contain test in their name filter 0 workspace name contains 0 test After encoding filter 5B0 5D 5Bworkspace name 5D 5Bcontains 5D 5B0 5D test View Type modules Show modules that contain aws in their name and version string equal to 1 1 filter 0 name contains 0 aws filter 0 version is 0 1 1 After encoding filter 5B0 5D 5Bname 5D 5Bcontains 5D 5B0 5D aws filter 5B0 5D 5Bversion 5D 5Bis 5D 5B0 5D 1 1 Filter Operators Operator Supported Field Types Description is boolean number string Filters data to rows where the field value is equivalent to the filter value is not number string Filters data to rows where the field value is different from the filter value contains string Filters data to rows where the field value contains the filter value as a sub string does not contain string Filters data to rows where the field value does not contain the filter value as a sub string is empty boolean number string Filters data to rows where the field does not contain a value is not empty boolean number string Filters data to rows where the field contains any value gt number Filters data to rows where the field value is greater than the filter value lt number Filters data to rows where the field value is less than the filter value gteq number Filters data to rows where the field value is greater than or equal to the filter value lteq number Filters data to rows where the field value is less than or equal to the filter value is before datetime Filters data to rows where the field value is earlier than the filter value ISO 8601 formatted timestamps are required for filter values If no time zone offset is provided the filter value will be interpreted as UTC is after datetime Filters data to rows where the field value is earlier than the filter value ISO 8601 formatted timestamps are required for filter values If no time zone offset is provided the filter value will be interpreted as UTC Pagination This endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters Remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs Sample requests View Type workspaces Show data for all workspaces shell curl header Authorization Bearer TOKEN https app terraform io api v2 organizations ORG NAME explorer type workspaces Show data for all workspaces with test in their name shell curl header Authorization Bearer TOKEN https app terraform io api v2 organizations ORG NAME explorer type workspaces filter 5B0 5D 5Bworkspace name 5D 5Bcontains 5D 5B0 5D test View Type modules Show modules used across all workspaces shell curl header Authorization Bearer TOKEN https app terraform io api v2 organizations ORG NAME explorer type modules Show public modules only shell curl header Authorization Bearer TOKEN https app terraform io api v2 organizations ORG NAME explorer type modules filter 5B0 5D 5Bregistry type 5D 5Bis 5D 5B0 5D public View Type provider Show providers used across all workspaces shell curl header Authorization Bearer TOKEN https app terraform io api v2 organizations ORG NAME explorer type providers Show most used providers across all workspaces shell curl header Authorization Bearer TOKEN https app terraform io api v2 organizations ORG NAME explorer type providers sort workspace count View Type tf versions Show Terraform versions used across all workspaces shell curl header Authorization Bearer TOKEN https app terraform io api v2 organizations ORG NAME explorer type tf versions Show all Terraform versions used in more than 10 workspaces shell curl header Authorization Bearer TOKEN https app terraform io api v2 organizations ORG NAME explorer type tf versions filter 5B0 5D 5Bworkspace count 5D 5Bgt 5D 5B0 5D 10 Sample response Show data for all workspaces json data attributes all checks succeeded true checks errored 0 checks failed 0 checks passed 0 checks unknown 0 current run applied at null current run external id run rdoEKh2Gy3K6SbCZ current run status planned and finished drifted false external id ws j2sAeWRxou1b5HYf module count 0 modules null organization name acme corp project external id prj V61QLE8tvs4NvVZG project name Default Project provider count 0 providers null resources drifted 0 resources undrifted 0 state version terraform version 1 5 7 vcs repo identifier null workspace created at 2023 10 17T21 56 45 570 00 00 workspace name payments service workspace terraform version 1 5 7 workspace updated at 2023 12 08T19 58 15 513 00 00 id ws j2sAWeRxuo1b5HYf type visibility workspace attributes all checks succeeded true checks errored 0 checks failed 0 checks passed 0 checks unknown 0 current run applied at 2023 08 18T16 24 59 000 00 00 current run external id run 9MmJaoQTvDCh5wUa current run status applied drifted true external id ws igUVNQSYVXRkhYuo module count 0 modules null organization name acme corp project external id prj uU2xNqGeG86U9WgT project name web provider count 0 providers null resources drifted 3 resources undrifted 3 state version terraform version 1 4 5 vcs repo identifier acmecorp api workspace created at 2023 04 25T17 09 14 960 00 00 workspace name api service workspace terraform version 1 4 5 workspace updated at 2023 12 08T20 43 16 779 00 00 id ws igUNVQSYXVRkhYuo type visibility workspace links self https app terraform io api v2 organizations acme corp explorer page 5Bnumber 5D 1 page 5Bsize 5D 20 type workspaces first https app terraform io api v2 organizations acme corp explorer page 5Bnumber 5D 1 page 5Bsize 5D 20 type workspaces last https app terraform io api v2 organizations acme corp explorer page 5Bnumber 5D 1 page 5Bsize 5D 20 type workspaces prev null next null meta pagination current page 1 page size 20 next page null prev page null total pages 1 total count 2 Export data as CSV GET organizations organization name explorer export csv Parameter Description organization name The name of the organization to query The organization must already exist in the system and the user must have permissions to read the workspaces and projects within it This endpoint can be used to download a full unpaged export of the query results in CSV format with the filter sort and field selections applied Explorer queries will time out after 60 seconds If the desired query is timing out try a simpler query that uses less filters Requests to the explorer are subject to rate limiting terraform cloud docs api docs rate limiting Explorer will return a 429 status code when rate limiting is active for the authenticated context Data presented by the explorer is eventually consistent Query results typically contain data that represents the current state of the system but in some cases a small delay may be necessary before querying for data that has recently been updated Query parameters This GET endpoint supports the same query string parameters as the Explorer Query endpoint execute a query Sample requests View Type workspaces Show data for all workspaces shell curl header Authorization Bearer TOKEN https app terraform io api v2 organizations ORG NAME explorer export csv type workspaces Sample response Show data for all workspaces csv all checks succeeded checks errored checks failed checks passed checks unknown current run applied at current run external id current run status drifted external id module count modules organization name project external id project name provider count providers resources drifted resources undrifted state version terraform version vcs repo identifier workspace created at workspace name workspace terraform version workspace updated at true 0 0 0 0 run rdoEKh2Gy3K6SbCZ planned and finished false ws j2sAeWRxou1b5HYf 0 acme corp prj V61QLE8tvs4NvVZG Default Project 0 0 0 1 5 7 2023 10 17T21 56 45 00 00 payments service 1 5 7 2023 12 13T15 48 16 00 00 true 0 0 0 0 2023 08 18T16 24 59 00 00 run 9MmJaoQTvDCh5wUa applied true ws igUVNQSYVXRkhYuo 0 acme corp prj uU2xNqGeG86U9WgT web 0 3 3 1 4 5 acmecorp api 2023 04 25T17 09 14 00 00 api service 1 4 5 2023 12 13T15 29 03 00 00 List saved views Note The ability to save views in the explorer is in public beta All APIs and workflows are subject to change Use this endpoint to display all of the explorer s saved views terraform cloud docs workspaces explorer saved views in an organization GET api v2 organizations organization name explorer views Parameter Description organization name The name of the organization to query To view a query you must have permission to read the workspaces and projects within that query Sample request shell curl header Authorization Bearer TOKEN request GET https app terraform io api v2 organizations ORG NAME explorer views Sample response json data id sq P9Yn6Ad6EiVMz77s type explorer saved queries attributes name my saved query created at 2024 10 11T16 18 51 442Z query filter field workspace name operator contains value child field workspace name operator contains value type workspaces query type workspaces Create saved view Note The ability to save views in the explorer is in public beta All APIs and workflows are subject to change Use this endpoint to create a saved view terraform cloud docs workspaces explorer saved views in the explorer POST api v2 organizations organization name explorer views Parameter Description organization name The name of the organization to query To view a query you must have permission to read the workspaces and projects within that query To create a saved view provide the following data in your payload Key path Type Default Description data name string The name of the saved view data query type string The primary type that the view is querying Refer to View Types view types for details data query object A list of filters fields and sorting rules for the view Refer to Query parameters query parameters for full details data query filter array objects A list of filters composed of fields operators and values data query filter field string The field name to filter by data query filter operator string The operator applied to field and value data query filter value array strings A list of values to filter by data query fields array strings A list of fields to include in the view data query sort array strings A list of fields to sort by Prefix with for descending sort Sample request shell curl header Authorization Bearer TOKEN request POST data payload json https app terraform io api v2 organizations ORG NAME explorer views Sample response json data id sq P9Yn6Ad6EiVMz77s type explorer saved queries attributes name my saved query created at 2024 10 11T16 18 51 442Z query filter field workspace name operator contains value child field workspace name operator contains value type workspaces query type workspaces Show saved view Use this endpoint to display a specific saved view from the explorer GET api v2 organizations organization name explorer views view id Parameter Description organization name The name of the organization to query To view a query you must have permission to read the workspaces and projects within that query view id The ID of the saved view to show Sample request shell curl header Authorization Bearer TOKEN request GET https app terraform io api v2 organizations ORG NAME explorer views VIEW ID Sample response json data id sq P9Yn6Ad6EiVMz77s type explorer saved queries attributes name my saved query created at 2024 10 11T16 18 51 442Z query filter field workspace name operator contains value child field workspace name operator contains value type workspaces query type workspaces Update a saved view Use this endpoint to update the data a saved view queries PATCH api v2 organizations organization name explorer views view id Parameter Description organization name The name of the organization to query To view a query you must have permission to read the workspaces and projects within that query view id The external id of the saved view to update You must have the following fields in the payload for your request Key path Type Default Description data name string The name of the saved view data query object A list of filters fields and sorting rules for the view See Query parameters query parameters for full details data query filter array objects A list of filters composed of fields operators and values See Filtering filtering for more information data query filter field string The field name to filter by data query filter operator string The operator applied to field and value data query filter value array strings A list of values to filter by data query fields array strings A list of fields to include in the view Refer to execute a query execute a query for a list of available parameters data query sort array strings A list of fields to sort by Prefix with for descending sort Sample request shell curl header Authorization Bearer TOKEN request PATCH data payload json https app terraform io api v2 organizations ORG NAME explorer viewsi VIEW ID Sample response json data id sq P9Yn6Ad6EiVMz77s type explorer saved queries attributes name my saved query created at 2024 10 11T16 18 51 442Z query filter field workspace name operator contains value candy field workspace name operator contains value pumpkins type workspaces query type workspaces Delete a saved view Use this endpoint to delete a saved view DELETE api v2 organizations organization name explorer views view id Parameter Description organization name The name of the organization to query To view a query you must have permission to read the workspaces and projects within that query view id The ID of the saved view you want to delete Sample request shell curl header Authorization Bearer TOKEN request DELETE https app terraform io api v2 organizations ORG NAME explorer views VIEW ID Sample response json data id sq P9Yn6Ad6EiVMz77s type explorer saved queries attributes name my saved query created at 2024 10 11T16 18 51 442Z query filter field workspace name operator contains value candy field workspace name operator contains value pumpkins type workspaces query type workspaces Query a saved view Re execute a saved view s query to retrieve current results GET api v2 organizations organization name explorer views view id results Parameter Description organization name The name of the organization to query To view a query you must have permission to read the workspaces and projects within that query view id The ID of the saved view to re query Sample request shell curl header Authorization Bearer TOKEN request GET https app terraform io api v2 organizations ORG NAME explorer views VIEW ID results Sample response json data attributes all checks succeeded true checks errored 0 checks failed 0 checks passed 0 checks unknown 0 current run applied at null current run external id run rdoEKh2Gy3K6SbCZ current run status planned and finished drifted false external id ws j2sAeWRxou1b5HYf module count 0 modules null organization name acme corp project external id prj V61QLE8tvs4NvVZG project name Default Project provider count 0 providers null resources drifted 0 resources undrifted 0 state version terraform version 1 5 7 vcs repo identifier null workspace created at 2023 10 17T21 56 45 570 00 00 workspace name candy distribution system workspace terraform version 1 5 7 workspace updated at 2023 12 08T19 58 15 513 00 00 id ws j2sAWeRxuo1b5HYf type visibility workspace attributes all checks succeeded true checks errored 0 checks failed 0 checks passed 0 checks unknown 0 current run applied at 2023 08 18T16 24 59 000 00 00 current run external id run 9MmJaoQTvDCh5wUa current run status applied drifted true external id ws igUVNQSYVXRkhYuo module count 0 modules null organization name acme corp project external id prj uU2xNqGeG86U9WgT project name web provider count 0 providers null resources drifted 3 resources undrifted 3 state version terraform version 1 4 5 vcs repo identifier acmecorp api workspace created at 2023 04 25T17 09 14 960 00 00 workspace name pumpkin smasher workspace terraform version 1 4 5 workspace updated at 2023 12 08T20 43 16 779 00 00 id ws igUNVQSYXVRkhYuo type visibility workspace links self https app terraform io api v2 organizations acme corp explorer page 5Bnumber 5D 1 page 5Bsize 5D 20 type workspaces first https app terraform io api v2 organizations acme corp explorer page 5Bnumber 5D 1 page 5Bsize 5D 20 type workspaces last https app terraform io api v2 organizations acme corp explorer page 5Bnumber 5D 1 page 5Bsize 5D 20 type workspaces prev null next null meta pagination current page 1 page size 20 next page null prev page null total pages 1 total count 2 Query a saved view as CSV Re execute a saved view s query to retrieve current results HCP Terraform returns results as a CSV GET api v2 organizations organization name explorer views view id csv Parameter Description organization name The name of the organization to query To view a query you must have permission to read the workspaces and projects within that query view id The external id of the saved view to query Sample request shell curl header Authorization Bearer TOKEN request GET https app terraform io api v2 organizations ORG NAME explorer views VIEW ID csv Sample response csv all checks succeeded checks errored checks failed checks passed checks unknown current run applied at current run external id current run status drifted external id module count modules organization name project external id project name provider count providers resources drifted resources undrifted state version terraform version vcs repo identifier workspace created at workspace name workspace terraform version workspace updated at true 0 0 0 0 run rdoEKh2Gy3K6SbCZ planned and finished false ws j2sAeWRxou1b5HYf 0 acme corp prj V61QLE8tvs4NvVZG Default Project 0 0 0 1 5 7 2023 10 17T21 56 45 00 00 candy distribution service 1 5 7 2023 12 13T15 48 16 00 00 true 0 0 0 0 2023 08 18T16 24 59 00 00 run 9MmJaoQTvDCh5wUa applied true ws igUVNQSYVXRkhYuo 0 acme corp prj uU2xNqGeG86U9WgT web 0 3 3 1 4 5 acmecorp api 2023 04 25T17 09 14 00 00 api service 1 4 5 2023 12 13T15 29 03 00 00
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 page title Configuration Versions API Docs HCP Terraform 201 https developer mozilla org en US docs Web HTTP Status 201 Use the configuration versions endpoint to manage configuration versions for a workspace List show and create configuration versions and their files using the HTTP API
--- page_title: Configuration Versions - API Docs - HCP Terraform description: >- Use the `/configuration-versions` endpoint to manage configuration versions for a workspace. List, show, and create configuration versions and their files using the HTTP API. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [302]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # Configuration Versions API -> **Note:** Before working with the runs or configuration versions APIs, read the [API-driven run workflow](/terraform/cloud-docs/run/api) page, which includes both a full overview of this workflow and a walkthrough of a simple implementation of it. A configuration version (`configuration-version`) is a resource used to reference the uploaded configuration files. It is associated with the run to use the uploaded configuration files for performing the plan and apply. You need read runs permission to list and view configuration versions for a workspace, and you need queue plans permission to create new configuration versions. Refer to the [permissions](/terraform/cloud-docs/users-teams-organizations/permissions#general-workspace-permissions) documentation for more details. [permissions-citation]: #intentionally-unused---keep-for-maintainers ## Attributes ### Configuration Version States The configuration version state is found in `data.attributes.status`, and you can reference the following list of possible states. A configuration version created through the API or CLI can only be used in runs if it is in an `uploaded` state. A configuration version created through a linked VCS repository may also be used in runs if it is in an `archived` state. | State | Description | | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `pending` | The initial status of a configuration version after it has been created. Pending configuration versions cannot be used to create new runs. | | `fetching` | For configuration versions created from a commit to a connected VCS repository, HCP Terraform is currently fetching the associated files from VCS. | | `uploaded` | The configuration version is fully processed and can be used in runs. | | `archived` | All immediate runs are complete and HCP Terraform has discarded the files associated with this configuration version. If the configuration version was created through a connected VCS repository, it can still be used in new runs. In those cases, HCP Terraform will re-fetch the files from VCS. | | `errored` | HCP Terraform could not process this configuration version, and it cannot be used to create new runs. You can try again by pushing a new commit to your linked VCS repository or creating a new configuration version with the API or CLI. | | `backing_data_soft_deleted` | <EnterpriseAlert inline /> Indicates that the configuration version's backing data is marked for garbage collection. If no action is taken, the backing data associated with this configuration version is permanently deleted after a set number of days. You can restore the backing data associated with the configuration version before it is permanently deleted. | | | `backing_data_permanently_deleted` | <EnterpriseAlert inline /> The configuration version's backing data has been permanently deleted and can no longer be restored. | ## List Configuration Versions `GET /workspaces/:workspace_id/configuration-versions` | Parameter | Description | | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `:workspace_id` | The ID of the workspace to list configurations from. Obtain this from the [workspace settings](/terraform/cloud-docs/workspaces/settings) or the [Show Workspace](/terraform/cloud-docs/api-docs/workspaces#show-workspace) endpoint. | ### Query Parameters This endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. | Parameter | Description | | -------------- | -------------------------------------------------------------------------------------- | | `page[number]` | **Optional.** If omitted, the endpoint will return the first page. | | `page[size]` | **Optional.** If omitted, the endpoint will return 20 configuration versions per page. | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/workspaces/ws-2Qhk7LHgbMrm3grF/configuration-versions ``` ### Sample Response ```json { "data": [ { "id": "cv-ntv3HbhJqvFzamy7", "type": "configuration-versions", "attributes": { "error": null, "error-message": null, "source": "gitlab", "speculative":false, "status": "uploaded", "status-timestamps": {}, "provisional": false }, "relationships": { "ingress-attributes": { "data": { "id": "ia-i4MrTxmQXYxH2nYD", "type": "ingress-attributes" }, "links": { "related": "/api/v2/configuration-versions/cv-ntv3HbhJqvFzamy7/ingress-attributes" } } }, "links": { "self": "/api/v2/configuration-versions/cv-ntv3HbhJqvFzamy7", "download": "/api/v2/configuration-versions/cv-ntv3HbhJqvFzamy7/download" } } ] } ``` ## Show a Configuration Version `GET /configuration-versions/:configuration-id` | Parameter | Description | | ------------------- | ------------------------------------ | | `:configuration-id` | The id of the configuration to show. | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/configuration-versions/cv-ntv3HbhJqvFzamy7 ``` ### Sample Response ```json { "data": { "id": "cv-ntv3HbhJqvFzamy7", "type": "configuration-versions", "attributes": { "error": null, "error-message": null, "source": "gitlab", "speculative":false, "status": "uploaded", "status-timestamps": {}, "provisional": false }, "relationships": { "ingress-attributes": { "data": { "id": "ia-i4MrTxmQXYxH2nYD", "type": "ingress-attributes" }, "links": { "related": "/api/v2/configuration-versions/cv-ntv3HbhJqvFzamy7/ingress-attributes" } } }, "links": { "self": "/api/v2/configuration-versions/cv-ntv3HbhJqvFzamy7", "download": "/api/v2/configuration-versions/cv-ntv3HbhJqvFzamy7/download" } } } ``` ## Show a Configuration Version's Commit Information An ingress attributes resource (`ingress-attributes`) is used to reference commit information for configuration versions created in a workspace with a VCS repository. `GET /configuration-versions/:configuration-id/ingress-attributes` | Parameter | Description | | ------------------- | ------------------------------------ | | `:configuration-id` | The id of the configuration to show. | Ingress attributes can also be fetched as part of a query to a particular configuration version via `include`: `GET /configuration-versions/:configuration-id?include=ingress-attributes` | Parameter | Description | | ------------------- | ------------------------------------ | | `:configuration-id` | The id of the configuration to show. | <!-- Note: /ingress-attributes/:ingress-attributes-id is purposely not documented here, as its usefulness is questionable given the routes above; IAs are inherently a part of a CV and their separate resource is a vestige of the original Terraform Enterprise --> ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/configuration-versions/cv-TrHjxIzad9Ae9i8x/ingress-attributes ``` ### Sample Response ```json { "data": { "id": "ia-zqHjxJzaB9Ae6i9t", "type": "ingress-attributes", "attributes": { "branch": "add-cool-stuff", "clone-url": "https://github.com/hashicorp/foobar.git", "commit-message": "Adding really cool infrastructure", "commit-sha": "1e1c1018d1bbc0b8517d072718e0d87c1a0eda95", "commit-url": "https://github.com/hashicorp/foobar/commit/1e1c1018d1bbc0b8517d072718e0d87c1a0eda95", "compare-url": "https://github.com/hashicorp/foobar/pull/163", "identifier": "hashicorp/foobar", "is-pull-request": true, "on-default-branch": false, "pull-request-number": 163, "pull-request-url": "https://github.com/hashicorp/foobar/pull/163", "pull-request-title": "Adding really cool infrastructure", "pull-request-body": "These are changes to add really cool stuff. We should absolutely merge this.", "tag": null, "sender-username": "chrisarcand", "sender-avatar-url": "https://avatars.githubusercontent.com/u/2430490?v=4", "sender-html-url": "https://github.com/chrisarcand" }, "relationships": { "created-by": { "data": { "id": "user-PQk2Z3dfXAax18P6s", "type": "users" }, "links": { "related": "/api/v2/ingress-attributes/ia-zqHjxJzaB9Ae6i9t/created-by" } } }, "links": { "self": "/api/v2/ingress-attributes/ia-zqHjxJzaB9Ae6i9t" } } } ``` ## Create a Configuration Version `POST /workspaces/:workspace_id/configuration-versions` | Parameter | Description | | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `:workspace_id` | The ID of the workspace to create the new configuration version in. Obtain this from the [workspace settings](/terraform/cloud-docs/workspaces/settings) or the [Show Workspace](/terraform/cloud-docs/api-docs/workspaces#show-workspace) endpoint. | -> **Note:** This endpoint cannot be accessed with [organization tokens](/terraform/cloud-docs/users-teams-organizations/api-tokens#organization-api-tokens). You must access it with a [user token](/terraform/cloud-docs/users-teams-organizations/users#api-tokens) or [team token](/terraform/cloud-docs/users-teams-organizations/api-tokens#team-api-tokens). ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | --------------------------------- | ------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data.attributes.auto-queue-runs` | boolean | true | When true, runs are queued automatically when the configuration version is uploaded. | | `data.attributes.speculative` | boolean | false | When true, this configuration version may only be used to create runs which are speculative, that is, can neither be confirmed nor applied. | | `data.attributes.provisional` | boolean | false | When true, this configuration version does not immediately become the workspace current configuration version. If the associated run is applied, it then becomes the current configuration version unless a newer one exists.| ### Sample Payload ```json { "data": { "type": "configuration-versions", "attributes": { "auto-queue-runs": true } } } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/workspaces/ws-2Qhk7LHgbMrm3grF/configuration-versions ``` ### Sample Response ```json { "data": { "id": "cv-UYwHEakurukz85nW", "type": "configuration-versions", "attributes": { "auto-queue-runs": true, "error": null, "error-message": null, "source": "tfe-api", "speculative":false, "status": "pending", "status-timestamps": {}, "upload-url": "https://archivist.terraform.io/v1/object/9224c6b3-2e14-4cd7-adff-ed484d7294c2", "provisional": false }, "relationships": { "ingress-attributes": { "data": null, "links": { "related": "/api/v2/configuration-versions/cv-UYwHEakurukz85nW/ingress-attributes" } } }, "links": { "self": "/api/v2/configuration-versions/cv-UYwHEakurukz85nW" } } } ``` ### Configuration Files Upload URL Once a configuration version is created, use the `upload-url` attribute to [upload configuration files](#upload-configuration-files) associated with that version. The `upload-url` attribute is only provided in the response when creating configuration versions. ## Upload Configuration Files -> **Note**: If `auto-queue-runs` was either not provided or set to `true` during creation of the configuration version, a run using this configuration version will be automatically queued on the workspace. If `auto-queue-runs` was set to `false` explicitly, then it is necessary to [create a run on the workspace](/terraform/cloud-docs/api-docs/run#create-a-run) manually after the configuration version is uploaded. `PUT https://archivist.terraform.io/v1/object/<UNIQUE OBJECT ID>` **The URL is provided in the `upload-url` attribute when creating a `configuration-versions` resource. After creation, the URL is hidden on the resource and no longer available.** ### Sample Request **@filename is the name of configuration file you wish to upload.** ```shell curl \ --header "Content-Type: application/octet-stream" \ --request PUT \ --data-binary @filename \ https://archivist.terraform.io/v1/object/4c44d964-eba7-4dd5-ad29-1ece7b99e8da ``` ## Archive a Configuration Version `POST /configuration-versions/:configuration_version_id/actions/archive` | Parameter | Description | | --------------------------- | ---------------------------------------------- | | `configuration_version_id` | The ID of the configuration version to archive. | This endpoint notifies HCP Terraform to discard the uploaded `.tar.gz` file associated with this configuration version. This endpoint can only archive configuration versions that were created with the API or CLI, are in an `uploaded` [state](#configuration-version-states), have no runs in progress, and are not the current configuration version for any workspace. Otherwise, calling this endpoint will result in an error. HCP Terraform automatically archives configuration versions created through VCS when associated runs are complete and then re-fetches the files for subsequent runs. | Status | Response | Reason(s) | | ------- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | [202][] | none | Successfully initiated the archive process. | | [409][] | [JSON API error object][] | Configuration version was in a non-archivable state or the configuration version was created with VCS and cannot be archived through the API. | | [404][] | [JSON API error object][] | Configuration version was not found or user not authorized. | ### Request Body This POST endpoint does not take a request body. ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ https://app.terraform.io/api/v2/configuration-versions/cv-ntv3HbhJqvFzamy7/actions/archive ``` ## Download Configuration Files `GET /configuration-versions/:configuration_version_id/download` | Parameter | Description | | --------------------------- | ------------------------------------------------ | | `configuration_version_id` | The ID of the configuration version to download. | `GET /runs/:run_id/configuration-version/download` | Parameter | Description | | --------------------------- | ------------------------------------------------------------------- | | `run_id` | The ID of the run whose configuration version should be downloaded. | These endpoints generate a temporary URL to the location of the configuration version in a `.tar.gz` archive, and then redirect to that link. If using a client that can follow redirects, you can use these endpoints to save the `.tar.gz` archive locally without needing to save the temporary URL. These endpoints will return an error if attempting to download a configuration version that is not in an `uploaded` [state](#configuration-version-states). | Status | Response | Reason | |---------|---------------------------|-----------------------------------------------------------------------------------------------------------------------------| | [302][] | HTTP Redirect | Configuration version found and temporary download URL generated | | [404][] | [JSON API error object][] | Configuration version not found, or specified configuration version is not uploaded, or user unauthorized to perform action | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --location \ https://app.terraform.io/api/v2/configuration-versions/cv-C6Py6WQ1cUXQX2x2/download \ > export.tar.gz ``` ## Mark a Configuration Version for Garbage Collection <EnterpriseAlert> This endpoint is exclusive to Terraform Enterprise, and not available in HCP Terraform. <a href="https://developer.hashicorp.com/terraform/enterprise">Learn more about Terraform Enterprise</a>. </EnterpriseAlert> `POST /api/v2/configuration-versions/:configuration-id/actions/soft_delete_backing_data` | Parameter | Description | | --------------------------- | ---------------------------------------------- | | `:configuration-id` | The ID of the configuration version to soft delete. | This endpoint directs Terraform Enterprise to _soft delete_ the backing files associated with the configuration version. Soft deletion refers to marking the configuration version for garbage collection. Terraform permanently deletes configuration versions marked for soft deletion after a set number of days unless the configuration version is restored. Once a configuration version is soft deleted, any attempts to read the configuration version will fail. Refer to [Configuration Version States](#configuration-version-states) for information about all data states. This endpoint can only soft delete configuration versions that meet the following criteria: - Were created using the API or CLI, - are in an [`uploaded` state](#configuration-version-states), - and are not the current configuration version. Otherwise, the endpoint returns an error. | Status | Response | Reason(s) | | ------- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | [200][] | none | Terraform successfully marked the data for garbage collection. | | [400][] | [JSON API error object][] | Terraform failed to transition the state to `backing_data_soft_deleted`. | | [404][] | [JSON API error object][] | Terraform did not find the configuration version or the user is not authorized to modify the configuration version state. | ### Request Body This POST endpoint does not take a request body. ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ https://app.terraform.io/api/v2/configuration-versions/cv-ntv3HbhJqvFzamy7/actions/soft_delete_backing_data --data {"data": {"attributes": {"delete-older-than-n-days": 23}}} ``` ## Restore Configuration Versions Marked for Garbage Collection <EnterpriseAlert> This endpoint is exclusive to Terraform Enterprise, and not available in HCP Terraform. <a href="https://developer.hashicorp.com/terraform/enterprise">Learn more about Terraform Enterprise</a>. </EnterpriseAlert> `POST /api/v2/configuration-versions/:configuration-id/actions/restore_backing_data` | Parameter | Description | | --------------------------- | ---------------------------------------------- | | `:configuration-id` | The ID of the configuration version to restore back to its uploaded state if applicable. | This endpoint directs Terraform Enterprise to restore backing files associated with this configuration version. This endpoint can only restore delete configuration versions that meet the following criteria: - are not in a [`backing_data_permanently_deleted` state](#configuration-version-states). Otherwise, the endpoint returns an error. Terraform restores applicable configuration versions back to their `uploaded` state. | Status | Response | Reason(s) | | ------- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | [200][] | none | Terraform successfully initiated the restore process. | | [400][] | [JSON API error object][] | Terraform failed to transition the state to `uploaded`. | | [404][] | [JSON API error object][] | Terraform did not find the configuration version or the user is not authorized to modify the configuration version state. | ### Request Body This POST endpoint does not take a request body. ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ https://app.terraform.io/api/v2/configuration-versions/cv-ntv3HbhJqvFzamy7/actions/restore_backing_data ``` ## Permanently Delete a Configuration Version <EnterpriseAlert> This endpoint is exclusive to Terraform Enterprise, and not available in HCP Terraform. <a href="https://developer.hashicorp.com/terraform/enterprise">Learn more about Terraform Enterprise</a>. </EnterpriseAlert> `POST /api/v2/configuration-versions/:configuration-id/actions/permanently_delete_backing_data` | Parameter | Description | | --------------------------- | ---------------------------------------------- | | `:configuration-id` | The ID of the configuration version to permanently delete. | This endpoint directs Terraform Enterprise to permanently delete backing files associated with this configuration version. This endpoint can only permanently delete configuration versions that meet the following criteria: - Were created using the API or CLI, - are in a [`backing_data_soft_deleted` state](#configuration-version-states), - and are not the current configuration version. Otherwise, the endpoint returns an error. | Status | Response | Reason(s) | | ------- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | [200][] | none | Terraform successfully deleted the data permanently. | | [400][] | [JSON API error object][] | Terraform failed to transition the state to `backing_data_permanently_deleted`. | | [404][] | [JSON API error object][] | Terraform did not find the configuration version or the user is not authorized to modify the configuration version state. | ### Request Body This POST endpoint does not take a request body. ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ https://app.terraform.io/api/v2/configuration-versions/cv-ntv3HbhJqvFzamy7/actions/permanently_delete_backing_data ``` ## Available Related Resources The GET endpoints above can optionally return related resources, if requested with [the `include` query parameter](/terraform/cloud-docs/api-docs#inclusion-of-related-resources). The following resource types are available: | Resource Name | Description | | -------------------- | ------------------------------------------------- | | `ingress_attributes` | The commit information used in the configuration. | | `run` | The run created by the configuration. |
terraform
page title Configuration Versions API Docs HCP Terraform description Use the configuration versions endpoint to manage configuration versions for a workspace List show and create configuration versions and their files using the HTTP API 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 302 https developer mozilla org en US docs Web HTTP Status 302 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects Configuration Versions API Note Before working with the runs or configuration versions APIs read the API driven run workflow terraform cloud docs run api page which includes both a full overview of this workflow and a walkthrough of a simple implementation of it A configuration version configuration version is a resource used to reference the uploaded configuration files It is associated with the run to use the uploaded configuration files for performing the plan and apply You need read runs permission to list and view configuration versions for a workspace and you need queue plans permission to create new configuration versions Refer to the permissions terraform cloud docs users teams organizations permissions general workspace permissions documentation for more details permissions citation intentionally unused keep for maintainers Attributes Configuration Version States The configuration version state is found in data attributes status and you can reference the following list of possible states A configuration version created through the API or CLI can only be used in runs if it is in an uploaded state A configuration version created through a linked VCS repository may also be used in runs if it is in an archived state State Description pending The initial status of a configuration version after it has been created Pending configuration versions cannot be used to create new runs fetching For configuration versions created from a commit to a connected VCS repository HCP Terraform is currently fetching the associated files from VCS uploaded The configuration version is fully processed and can be used in runs archived All immediate runs are complete and HCP Terraform has discarded the files associated with this configuration version If the configuration version was created through a connected VCS repository it can still be used in new runs In those cases HCP Terraform will re fetch the files from VCS errored HCP Terraform could not process this configuration version and it cannot be used to create new runs You can try again by pushing a new commit to your linked VCS repository or creating a new configuration version with the API or CLI backing data soft deleted EnterpriseAlert inline Indicates that the configuration version s backing data is marked for garbage collection If no action is taken the backing data associated with this configuration version is permanently deleted after a set number of days You can restore the backing data associated with the configuration version before it is permanently deleted backing data permanently deleted EnterpriseAlert inline The configuration version s backing data has been permanently deleted and can no longer be restored List Configuration Versions GET workspaces workspace id configuration versions Parameter Description workspace id The ID of the workspace to list configurations from Obtain this from the workspace settings terraform cloud docs workspaces settings or the Show Workspace terraform cloud docs api docs workspaces show workspace endpoint Query Parameters This endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters Remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs Parameter Description page number Optional If omitted the endpoint will return the first page page size Optional If omitted the endpoint will return 20 configuration versions per page Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 workspaces ws 2Qhk7LHgbMrm3grF configuration versions Sample Response json data id cv ntv3HbhJqvFzamy7 type configuration versions attributes error null error message null source gitlab speculative false status uploaded status timestamps provisional false relationships ingress attributes data id ia i4MrTxmQXYxH2nYD type ingress attributes links related api v2 configuration versions cv ntv3HbhJqvFzamy7 ingress attributes links self api v2 configuration versions cv ntv3HbhJqvFzamy7 download api v2 configuration versions cv ntv3HbhJqvFzamy7 download Show a Configuration Version GET configuration versions configuration id Parameter Description configuration id The id of the configuration to show Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 configuration versions cv ntv3HbhJqvFzamy7 Sample Response json data id cv ntv3HbhJqvFzamy7 type configuration versions attributes error null error message null source gitlab speculative false status uploaded status timestamps provisional false relationships ingress attributes data id ia i4MrTxmQXYxH2nYD type ingress attributes links related api v2 configuration versions cv ntv3HbhJqvFzamy7 ingress attributes links self api v2 configuration versions cv ntv3HbhJqvFzamy7 download api v2 configuration versions cv ntv3HbhJqvFzamy7 download Show a Configuration Version s Commit Information An ingress attributes resource ingress attributes is used to reference commit information for configuration versions created in a workspace with a VCS repository GET configuration versions configuration id ingress attributes Parameter Description configuration id The id of the configuration to show Ingress attributes can also be fetched as part of a query to a particular configuration version via include GET configuration versions configuration id include ingress attributes Parameter Description configuration id The id of the configuration to show Note ingress attributes ingress attributes id is purposely not documented here as its usefulness is questionable given the routes above IAs are inherently a part of a CV and their separate resource is a vestige of the original Terraform Enterprise Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 configuration versions cv TrHjxIzad9Ae9i8x ingress attributes Sample Response json data id ia zqHjxJzaB9Ae6i9t type ingress attributes attributes branch add cool stuff clone url https github com hashicorp foobar git commit message Adding really cool infrastructure commit sha 1e1c1018d1bbc0b8517d072718e0d87c1a0eda95 commit url https github com hashicorp foobar commit 1e1c1018d1bbc0b8517d072718e0d87c1a0eda95 compare url https github com hashicorp foobar pull 163 identifier hashicorp foobar is pull request true on default branch false pull request number 163 pull request url https github com hashicorp foobar pull 163 pull request title Adding really cool infrastructure pull request body These are changes to add really cool stuff We should absolutely merge this tag null sender username chrisarcand sender avatar url https avatars githubusercontent com u 2430490 v 4 sender html url https github com chrisarcand relationships created by data id user PQk2Z3dfXAax18P6s type users links related api v2 ingress attributes ia zqHjxJzaB9Ae6i9t created by links self api v2 ingress attributes ia zqHjxJzaB9Ae6i9t Create a Configuration Version POST workspaces workspace id configuration versions Parameter Description workspace id The ID of the workspace to create the new configuration version in Obtain this from the workspace settings terraform cloud docs workspaces settings or the Show Workspace terraform cloud docs api docs workspaces show workspace endpoint Note This endpoint cannot be accessed with organization tokens terraform cloud docs users teams organizations api tokens organization api tokens You must access it with a user token terraform cloud docs users teams organizations users api tokens or team token terraform cloud docs users teams organizations api tokens team api tokens Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data attributes auto queue runs boolean true When true runs are queued automatically when the configuration version is uploaded data attributes speculative boolean false When true this configuration version may only be used to create runs which are speculative that is can neither be confirmed nor applied data attributes provisional boolean false When true this configuration version does not immediately become the workspace current configuration version If the associated run is applied it then becomes the current configuration version unless a newer one exists Sample Payload json data type configuration versions attributes auto queue runs true Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 workspaces ws 2Qhk7LHgbMrm3grF configuration versions Sample Response json data id cv UYwHEakurukz85nW type configuration versions attributes auto queue runs true error null error message null source tfe api speculative false status pending status timestamps upload url https archivist terraform io v1 object 9224c6b3 2e14 4cd7 adff ed484d7294c2 provisional false relationships ingress attributes data null links related api v2 configuration versions cv UYwHEakurukz85nW ingress attributes links self api v2 configuration versions cv UYwHEakurukz85nW Configuration Files Upload URL Once a configuration version is created use the upload url attribute to upload configuration files upload configuration files associated with that version The upload url attribute is only provided in the response when creating configuration versions Upload Configuration Files Note If auto queue runs was either not provided or set to true during creation of the configuration version a run using this configuration version will be automatically queued on the workspace If auto queue runs was set to false explicitly then it is necessary to create a run on the workspace terraform cloud docs api docs run create a run manually after the configuration version is uploaded PUT https archivist terraform io v1 object UNIQUE OBJECT ID The URL is provided in the upload url attribute when creating a configuration versions resource After creation the URL is hidden on the resource and no longer available Sample Request filename is the name of configuration file you wish to upload shell curl header Content Type application octet stream request PUT data binary filename https archivist terraform io v1 object 4c44d964 eba7 4dd5 ad29 1ece7b99e8da Archive a Configuration Version POST configuration versions configuration version id actions archive Parameter Description configuration version id The ID of the configuration version to archive This endpoint notifies HCP Terraform to discard the uploaded tar gz file associated with this configuration version This endpoint can only archive configuration versions that were created with the API or CLI are in an uploaded state configuration version states have no runs in progress and are not the current configuration version for any workspace Otherwise calling this endpoint will result in an error HCP Terraform automatically archives configuration versions created through VCS when associated runs are complete and then re fetches the files for subsequent runs Status Response Reason s 202 none Successfully initiated the archive process 409 JSON API error object Configuration version was in a non archivable state or the configuration version was created with VCS and cannot be archived through the API 404 JSON API error object Configuration version was not found or user not authorized Request Body This POST endpoint does not take a request body Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST https app terraform io api v2 configuration versions cv ntv3HbhJqvFzamy7 actions archive Download Configuration Files GET configuration versions configuration version id download Parameter Description configuration version id The ID of the configuration version to download GET runs run id configuration version download Parameter Description run id The ID of the run whose configuration version should be downloaded These endpoints generate a temporary URL to the location of the configuration version in a tar gz archive and then redirect to that link If using a client that can follow redirects you can use these endpoints to save the tar gz archive locally without needing to save the temporary URL These endpoints will return an error if attempting to download a configuration version that is not in an uploaded state configuration version states Status Response Reason 302 HTTP Redirect Configuration version found and temporary download URL generated 404 JSON API error object Configuration version not found or specified configuration version is not uploaded or user unauthorized to perform action Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json location https app terraform io api v2 configuration versions cv C6Py6WQ1cUXQX2x2 download export tar gz Mark a Configuration Version for Garbage Collection EnterpriseAlert This endpoint is exclusive to Terraform Enterprise and not available in HCP Terraform a href https developer hashicorp com terraform enterprise Learn more about Terraform Enterprise a EnterpriseAlert POST api v2 configuration versions configuration id actions soft delete backing data Parameter Description configuration id The ID of the configuration version to soft delete This endpoint directs Terraform Enterprise to soft delete the backing files associated with the configuration version Soft deletion refers to marking the configuration version for garbage collection Terraform permanently deletes configuration versions marked for soft deletion after a set number of days unless the configuration version is restored Once a configuration version is soft deleted any attempts to read the configuration version will fail Refer to Configuration Version States configuration version states for information about all data states This endpoint can only soft delete configuration versions that meet the following criteria Were created using the API or CLI are in an uploaded state configuration version states and are not the current configuration version Otherwise the endpoint returns an error Status Response Reason s 200 none Terraform successfully marked the data for garbage collection 400 JSON API error object Terraform failed to transition the state to backing data soft deleted 404 JSON API error object Terraform did not find the configuration version or the user is not authorized to modify the configuration version state Request Body This POST endpoint does not take a request body Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST https app terraform io api v2 configuration versions cv ntv3HbhJqvFzamy7 actions soft delete backing data data data attributes delete older than n days 23 Restore Configuration Versions Marked for Garbage Collection EnterpriseAlert This endpoint is exclusive to Terraform Enterprise and not available in HCP Terraform a href https developer hashicorp com terraform enterprise Learn more about Terraform Enterprise a EnterpriseAlert POST api v2 configuration versions configuration id actions restore backing data Parameter Description configuration id The ID of the configuration version to restore back to its uploaded state if applicable This endpoint directs Terraform Enterprise to restore backing files associated with this configuration version This endpoint can only restore delete configuration versions that meet the following criteria are not in a backing data permanently deleted state configuration version states Otherwise the endpoint returns an error Terraform restores applicable configuration versions back to their uploaded state Status Response Reason s 200 none Terraform successfully initiated the restore process 400 JSON API error object Terraform failed to transition the state to uploaded 404 JSON API error object Terraform did not find the configuration version or the user is not authorized to modify the configuration version state Request Body This POST endpoint does not take a request body Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST https app terraform io api v2 configuration versions cv ntv3HbhJqvFzamy7 actions restore backing data Permanently Delete a Configuration Version EnterpriseAlert This endpoint is exclusive to Terraform Enterprise and not available in HCP Terraform a href https developer hashicorp com terraform enterprise Learn more about Terraform Enterprise a EnterpriseAlert POST api v2 configuration versions configuration id actions permanently delete backing data Parameter Description configuration id The ID of the configuration version to permanently delete This endpoint directs Terraform Enterprise to permanently delete backing files associated with this configuration version This endpoint can only permanently delete configuration versions that meet the following criteria Were created using the API or CLI are in a backing data soft deleted state configuration version states and are not the current configuration version Otherwise the endpoint returns an error Status Response Reason s 200 none Terraform successfully deleted the data permanently 400 JSON API error object Terraform failed to transition the state to backing data permanently deleted 404 JSON API error object Terraform did not find the configuration version or the user is not authorized to modify the configuration version state Request Body This POST endpoint does not take a request body Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST https app terraform io api v2 configuration versions cv ntv3HbhJqvFzamy7 actions permanently delete backing data Available Related Resources The GET endpoints above can optionally return related resources if requested with the include query parameter terraform cloud docs api docs inclusion of related resources The following resource types are available Resource Name Description ingress attributes The commit information used in the configuration run The run created by the configuration
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 Use the authentication token endpoint to manage organization level API tokens Generate and delete organization tokens using the HTTP API page title Organization Tokens API Docs HCP Terraform 201 https developer mozilla org en US docs Web HTTP Status 201
--- page_title: Organization Tokens - API Docs - HCP Terraform description: >- Use the `/authentication-token` endpoint to manage organization-level API tokens. Generate and delete organization tokens using the HTTP API. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # Organization Token API ## Generate a new organization token `POST /organizations/:organization_name/authentication-token` | Parameter | Description | | -------------------- | ----------------------------------------------------- | | `:organization_name` | The name of the organization to generate a token for. | Generates a new [organization API token](/terraform/cloud-docs/users-teams-organizations/api-tokens#organization-api-tokens), replacing any existing token. Only members of the owners team, the owners [team API token](/terraform/cloud-docs/users-teams-organizations/api-tokens#team-api-tokens), and the [organization API token](/terraform/cloud-docs/users-teams-organizations/api-tokens#organization-api-tokens) can access this endpoint. This endpoint returns the secret text of the new authentication token. You can only access this token when you create it and can not recover it later. [permissions-citation]: #intentionally-unused---keep-for-maintainers | Status | Response | Reason | | ------- | ------------------------------------------------------- | ------------------- | | [201][] | [JSON API document][] (`type: "authentication-tokens"`) | Success | | [404][] | [JSON API error object][] | User not authorized | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. | Key path | Type | Default | Description | | ----------------------------- | ------ | ------- | ----------------------------------------------------------------------------------------------------------------------- | | `data.type` | string | | Must be `"authentication-token"`. | | `data.attributes.expired-at` | string | `null` | The UTC date and time that the Organization Token will expire, in ISO 8601 format. If omitted or set to `null` the token will never expire. | ### Sample Payload ```json { "data": { "type": "authentication-token", "attributes": { "expired-at": "2023-04-06T12:00:00.000Z" } } } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/organizations/my-organization/authentication-token ``` ### Sample Response ```json { "data": { "id": "4111756", "type": "authentication-tokens", "attributes": { "created-at": "2017-11-29T19:11:28.075Z", "last-used-at": null, "description": null, "token": "ZgqYdzuvlv8Iyg.atlasv1.6nV7t1OyFls341jo1xdZTP72fN0uu9VL55ozqzekfmToGFbhoFvvygIRy2mwVAXomOE", "expired-at": "2023-04-06T12:00:00.000Z" }, "relationships": { "created-by": { "data": { "id": "user-62goNpx1ThQf689e", "type": "users" } } } } } ``` ## Delete the organization token `DELETE /organizations/:organization/authentication-token` | Parameter | Description | | -------------------- | --------------------------------------------- | | `:organization_name` | Which organization's token should be deleted. | Only members of the owners team, the owners [team API token](/terraform/cloud-docs/users-teams-organizations/api-tokens#team-api-tokens), and the [organization API token](/terraform/cloud-docs/users-teams-organizations/api-tokens#organization-api-tokens) can access this endpoint. [permissions-citation]: #intentionally-unused---keep-for-maintainers | Status | Response | Reason | | ------- | ------------------------- | ------------------- | | [204][] | No Content | Success | | [404][] | [JSON API error object][] | User not authorized | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request DELETE \ https://app.terraform.io/api/v2/organizations/my-organization/authentication-token ```
terraform
page title Organization Tokens API Docs HCP Terraform description Use the authentication token endpoint to manage organization level API tokens Generate and delete organization tokens using the HTTP API 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects Organization Token API Generate a new organization token POST organizations organization name authentication token Parameter Description organization name The name of the organization to generate a token for Generates a new organization API token terraform cloud docs users teams organizations api tokens organization api tokens replacing any existing token Only members of the owners team the owners team API token terraform cloud docs users teams organizations api tokens team api tokens and the organization API token terraform cloud docs users teams organizations api tokens organization api tokens can access this endpoint This endpoint returns the secret text of the new authentication token You can only access this token when you create it and can not recover it later permissions citation intentionally unused keep for maintainers Status Response Reason 201 JSON API document type authentication tokens Success 404 JSON API error object User not authorized Request Body This POST endpoint requires a JSON object with the following properties as a request payload Key path Type Default Description data type string Must be authentication token data attributes expired at string null The UTC date and time that the Organization Token will expire in ISO 8601 format If omitted or set to null the token will never expire Sample Payload json data type authentication token attributes expired at 2023 04 06T12 00 00 000Z Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 organizations my organization authentication token Sample Response json data id 4111756 type authentication tokens attributes created at 2017 11 29T19 11 28 075Z last used at null description null token ZgqYdzuvlv8Iyg atlasv1 6nV7t1OyFls341jo1xdZTP72fN0uu9VL55ozqzekfmToGFbhoFvvygIRy2mwVAXomOE expired at 2023 04 06T12 00 00 000Z relationships created by data id user 62goNpx1ThQf689e type users Delete the organization token DELETE organizations organization authentication token Parameter Description organization name Which organization s token should be deleted Only members of the owners team the owners team API token terraform cloud docs users teams organizations api tokens team api tokens and the organization API token terraform cloud docs users teams organizations api tokens organization api tokens can access this endpoint permissions citation intentionally unused keep for maintainers Status Response Reason 204 No Content Success 404 JSON API error object User not authorized Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request DELETE https app terraform io api v2 organizations my organization authentication token
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 Use the subscriptions endpoint to access subscription information Get an organization s subscription and access a subscription by ID using the HTTP API tfc only true page title Subscriptions API Docs HCP Terraform
--- page_title: Subscriptions - API Docs - HCP Terraform tfc_only: true description: >- Use the `/subscriptions` endpoint to access subscription information. Get an organization's subscription, and access a subscription by ID using the HTTP API. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # Subscriptions API -> **Note:** The subscriptions API is only available in HCP Terraform. An organization can subscribe to different [feature sets](/terraform/cloud-docs/api-docs/feature-sets), which represent the [pricing plans](/terraform/cloud-docs/overview) available in HCP Terraform. An organization's [entitlement set](/terraform/cloud-docs/api-docs#feature-entitlements) is calculated using its subscription and feature set. To change the subscription for an organization, use the billing settings in the HCP Terraform UI. ## Show Subscription For Organization `GET /organizations/:organization_name/subscription` | Parameter | Description | | -------------------- | ----------------------------- | | `:organization_name` | The name of the organization. | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/organizations/hashicorp/subscription ``` ### Sample Response ```json { "data": { "id": "sub-kyjptCZYXQ6amEVu", "type": "subscriptions", "attributes": { "end-at": null, "is-active": true, "start-at": "2021-01-20T07:03:53.492Z", "runs-ceiling": 1, "contract-start-at": null, "contract-user-limit": null, "contract-apply-limit": null, "run-task-limit": null, "run-task-workspace-limit": null, "run-task-mandatory-enforcement-limit": null, "policy-set-limit": null, "policy-limit": null, "policy-mandatory-enforcement-limit": null, "versioned-policy-set-limit": null, "agents-ceiling": 0, "is-public-free-tier": true, "is-self-serve-trial": false }, "relationships": { "organization": { "data": { "id": "hashicorp", "type": "organizations" } }, "billing-account": { "data": null }, "feature-set": { "data": { "id": "fs-EvCGYfpx9CVRzteA", "type": "feature-sets" } } }, "links": { "self": "/api/v2/subscriptions/sub-kyjptCZYXQ6amEVu" } }, "included": [ { "id": "fs-EvCGYfpx9CVRzteA", "type": "feature-sets", "attributes": { "audit-logging": false, "comparison-description": "Essential collaboration features for practitioners and small teams.", "cost-estimation": false, "cost": 0, "description": "State storage, locking, run history, VCS integration, private module registry, and remote operations", "global-run-tasks": false, "identifier": "free", "is-current": true, "is-free-tier": true, "module-tests-generation": false, "name": "Free", "plan": null, "policy-enforcement": false, "policy-limit": null, "policy-mandatory-enforcement-limit": null, "policy-set-limit": null, "private-networking": false, "private-policy-agents": false, "private-vcs": false, "run-task-limit": null, "run-task-mandatory-enforcement-limit": null, "run-task-workspace-limit": null, "run-tasks": false, "self-serve-billing": true, "sentinel": false, "sso": false, "teams": false, "user-limit": 5, "versioned-policy-set-limit": null } } ] } ``` ## Show Subscription By ID `GET /subscriptions/:id` | Parameter | Description | | --------- | ---------------------------------- | | `:id` | The ID of the Subscription to show | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/organizations/hashicorp/subscription ``` ### Sample Response ```json { "data": { "id": "sub-kyjptCZYXQ6amEVu", "type": "subscriptions", "attributes": { "end-at": null, "is-active": true, "start-at": "2021-01-20T07:03:53.492Z", "runs-ceiling": 1, "contract-start-at": null, "contract-user-limit": null, "contract-apply-limit": null, "agents-ceiling": 0, "run-task-limit": null, "run-task-workspace-limit": null, "run-task-mandatory-enforcement-limit": null, "policy-set-limit": null, "policy-limit": null, "policy-mandatory-enforcement-limit": null, "versioned-policy-set-limit": null, "is-public-free-tier": true, "is-self-serve-trial": false }, "relationships": { "organization": { "data": { "id": "hashicorp", "type": "organizations" } }, "billing-account": { "data": null }, "feature-set": { "data": { "id": "fs-EvCGYfpx9CVRzteA", "type": "feature-sets" } } }, "links": { "self": "/api/v2/subscriptions/sub-kyjptCZYXQ6amEVu" } }, "included": [ { "id": "fs-EvCGYfpx9CVRzteA", "type": "feature-sets", "attributes": { "audit-logging": false, "comparison-description": "Essential collaboration features for practitioners and small teams.", "cost-estimation": false, "cost": 0, "description": "State storage, locking, run history, VCS integration, private module registry, and remote operations", "global-run-tasks": false, "identifier": "free", "is-current": true, "is-free-tier": true, "module-tests-generation": false, "name": "Free", "plan": null, "policy-enforcement": false, "policy-limit": null, "policy-mandatory-enforcement-limit": null, "policy-set-limit": null, "private-networking": false, "private-policy-agents": false, "private-vcs": false, "run-task-limit": null, "run-task-mandatory-enforcement-limit": null, "run-task-workspace-limit": null, "run-tasks": false, "self-serve-billing": true, "sentinel": false, "sso": false, "teams": false, "user-limit": 5, "versioned-policy-set-limit": null } } ] } ```
terraform
page title Subscriptions API Docs HCP Terraform tfc only true description Use the subscriptions endpoint to access subscription information Get an organization s subscription and access a subscription by ID using the HTTP API 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects Subscriptions API Note The subscriptions API is only available in HCP Terraform An organization can subscribe to different feature sets terraform cloud docs api docs feature sets which represent the pricing plans terraform cloud docs overview available in HCP Terraform An organization s entitlement set terraform cloud docs api docs feature entitlements is calculated using its subscription and feature set To change the subscription for an organization use the billing settings in the HCP Terraform UI Show Subscription For Organization GET organizations organization name subscription Parameter Description organization name The name of the organization Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 organizations hashicorp subscription Sample Response json data id sub kyjptCZYXQ6amEVu type subscriptions attributes end at null is active true start at 2021 01 20T07 03 53 492Z runs ceiling 1 contract start at null contract user limit null contract apply limit null run task limit null run task workspace limit null run task mandatory enforcement limit null policy set limit null policy limit null policy mandatory enforcement limit null versioned policy set limit null agents ceiling 0 is public free tier true is self serve trial false relationships organization data id hashicorp type organizations billing account data null feature set data id fs EvCGYfpx9CVRzteA type feature sets links self api v2 subscriptions sub kyjptCZYXQ6amEVu included id fs EvCGYfpx9CVRzteA type feature sets attributes audit logging false comparison description Essential collaboration features for practitioners and small teams cost estimation false cost 0 description State storage locking run history VCS integration private module registry and remote operations global run tasks false identifier free is current true is free tier true module tests generation false name Free plan null policy enforcement false policy limit null policy mandatory enforcement limit null policy set limit null private networking false private policy agents false private vcs false run task limit null run task mandatory enforcement limit null run task workspace limit null run tasks false self serve billing true sentinel false sso false teams false user limit 5 versioned policy set limit null Show Subscription By ID GET subscriptions id Parameter Description id The ID of the Subscription to show Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 organizations hashicorp subscription Sample Response json data id sub kyjptCZYXQ6amEVu type subscriptions attributes end at null is active true start at 2021 01 20T07 03 53 492Z runs ceiling 1 contract start at null contract user limit null contract apply limit null agents ceiling 0 run task limit null run task workspace limit null run task mandatory enforcement limit null policy set limit null policy limit null policy mandatory enforcement limit null versioned policy set limit null is public free tier true is self serve trial false relationships organization data id hashicorp type organizations billing account data null feature set data id fs EvCGYfpx9CVRzteA type feature sets links self api v2 subscriptions sub kyjptCZYXQ6amEVu included id fs EvCGYfpx9CVRzteA type feature sets attributes audit logging false comparison description Essential collaboration features for practitioners and small teams cost estimation false cost 0 description State storage locking run history VCS integration private module registry and remote operations global run tasks false identifier free is current true is free tier true module tests generation false name Free plan null policy enforcement false policy limit null policy mandatory enforcement limit null policy set limit null private networking false private policy agents false private vcs false run task limit null run task mandatory enforcement limit null run task workspace limit null run tasks false self serve billing true sentinel false sso false teams false user limit 5 versioned policy set limit null
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 Use the workspace resources endpoint to interact with workspace resources List resources using the HTTP API page title Workspace Resources API Docs HCP Terraform
--- page_title: Workspace Resources - API Docs - HCP Terraform description: >- Use the workspace `/resources` endpoint to interact with workspace resources. List resources using the HTTP API. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # Workspace Resources API ## List Workspace Resources `GET /workspaces/:workspace_id/resources` | Parameter | Description | | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `:workspace_id` | The ID of the workspace to retrieve resources from. Obtain this from the [workspace settings](/terraform/cloud-docs/workspaces/settings) or the [show workspace](/terraform/cloud-docs/api-docs/workspaces#show-workspace) endpoint. | | Status | Response | Reason | | ------- | ------------------------------------------- | ----------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "resources"`) | Request was successful. | | [404][] | [JSON API error object][] | Workspace not found or user unauthorized to perform action. | ### Query Parameters This endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. | Parameter | Description | | -------------- | ----------------------------------------------------------------------------------- | | `page[number]` | **Optional.** If omitted, the endpoint will return the first page. | | `page[size]` | **Optional.** If omitted, the endpoint will return 20 workspace resources per page. | ### Permissions To list resources the user must have permission to read resources for the specified workspace. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) [permissions-citation]: #intentionally-unused---keep-for-maintainers ### Sample Request ```shell curl \ --request GET \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/workspaces/ws-DiTzUDRpjrArAfSS/resources ``` ### Sample Response ```json { "data": [ { "id": "wsr-KNYb3Jj3JTBgoBFs", "type": "resources", "attributes": { "address": "random_pet.animal", "name": "animal", "created-at": "2021-10-27", "updated-at": "2021-10-27", "module": "root", "provider": "hashicorp/random", "provider-type": "random_pet", "modified-by-state-version-id": "sv-y4pjfGHkGUBAa9AX", "name-index": null } }, { "id": "wsr-kYsf5A3hQ1y9zFWq", "type": "resources", "attributes": { "address": "random_pet.animal2", "name": "animal2", "created-at": "2021-10-27", "updated-at": "2021-10-27", "module": "root", "provider": "hashicorp/random", "provider-type": "random_pet", "modified-by-state-version-id": "sv-y4pjfGHkGUBAa9AX", "name-index": null } } ], "links": { "self": "https://app.terraform.io/api/v2/workspaces/ws-DiTzUDRpjrArAfSS/resources?page%5Bnumber%5D=1&page%5Bsize%5D=20", "first": "https://app.terraform.io/api/v2/workspaces/ws-DiTzUDRpjrArAfSS/resources?page%5Bnumber%5D=1&page%5Bsize%5D=20", "prev": null, "next": null, "last": "https://app.terraform.io/api/v2/workspaces/ws-DiTzUDRpjrArAfSS/resources?page%5Bnumber%5D=1&page%5Bsize%5D=20" }, ... } ```
terraform
page title Workspace Resources API Docs HCP Terraform description Use the workspace resources endpoint to interact with workspace resources List resources using the HTTP API 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects Workspace Resources API List Workspace Resources GET workspaces workspace id resources Parameter Description workspace id The ID of the workspace to retrieve resources from Obtain this from the workspace settings terraform cloud docs workspaces settings or the show workspace terraform cloud docs api docs workspaces show workspace endpoint Status Response Reason 200 JSON API document type resources Request was successful 404 JSON API error object Workspace not found or user unauthorized to perform action Query Parameters This endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters Remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs Parameter Description page number Optional If omitted the endpoint will return the first page page size Optional If omitted the endpoint will return 20 workspace resources per page Permissions To list resources the user must have permission to read resources for the specified workspace More about permissions terraform cloud docs users teams organizations permissions permissions citation intentionally unused keep for maintainers Sample Request shell curl request GET header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 workspaces ws DiTzUDRpjrArAfSS resources Sample Response json data id wsr KNYb3Jj3JTBgoBFs type resources attributes address random pet animal name animal created at 2021 10 27 updated at 2021 10 27 module root provider hashicorp random provider type random pet modified by state version id sv y4pjfGHkGUBAa9AX name index null id wsr kYsf5A3hQ1y9zFWq type resources attributes address random pet animal2 name animal2 created at 2021 10 27 updated at 2021 10 27 module root provider hashicorp random provider type random pet modified by state version id sv y4pjfGHkGUBAa9AX name index null links self https app terraform io api v2 workspaces ws DiTzUDRpjrArAfSS resources page 5Bnumber 5D 1 page 5Bsize 5D 20 first https app terraform io api v2 workspaces ws DiTzUDRpjrArAfSS resources page 5Bnumber 5D 1 page 5Bsize 5D 20 prev null next null last https app terraform io api v2 workspaces ws DiTzUDRpjrArAfSS resources page 5Bnumber 5D 1 page 5Bsize 5D 20
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 page title Workspaces API Docs HCP Terraform 201 https developer mozilla org en US docs Web HTTP Status 201 Use the workspaces endpoint to interact with workspaces List show create update lock unlock and delete a workspace and manage SSH keys remote state consumers and tags using the HTTP API
--- page_title: Workspaces - API Docs - HCP Terraform description: >- Use the `/workspaces` endpoint to interact with workspaces. List, show, create, update, lock, unlock, and delete a workspace, and manage SSH keys, remote state consumers, and tags using the HTTP API. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects [speculative plans]: /terraform/cloud-docs/run/remote-operations#speculative-plans # Workspaces API This topic provides reference information about the workspaces AP. Workspaces represent running infrastructure managed by Terraform. ## Overview The scope of the API includes the following endpoints: | Method | Path | Action | | --- | --- | --- | | `POST` | `/organizations/:organization_name/workspaces` | Call this endpoint to [create a workspace](#create-a-workspace). You can apply tags stored as key-value pairs when creating the workspace. | | `POST` | `/organizations/:organization_name/workspaces/:name/actions/safe-delete` | Call this endpoint to [safely delete a workspace](#safe-delete-a-workspace) by querying the organization and workspace names. | | `POST` | `/workspaces/:workspace_id/actions/safe-delete` | Call this endpoint [safely delete a workspace](#safe-delete-a-workspace) by querying the workspace ID. | |`POST` | `/workspaces/:workspace_id/actions/lock` | Call this endpoint to [lock a workspace](#lock-a-workspace). | | `POST` | `/workspaces/:workspace_id/actions/unlock` | Call this endpoint to [unlock a workspace](#unlock-a-workspace).| | `POST` | `/workspaces/:workspace_id/actions/force-unlock` | Call this endpoint to [force a workspace to unlock](#force-unlock-a-workspace). | | `POST` | `/workspaces/:workspace_id/relationships/remote-state-consumers` | Call this endpoint to [add remote state consumers](#get-remote-state-consumers). | | `POST` | `/workspaces/:workspace_id/relationships/tags` | Call this endpoint to [bind flat string tags to an existing workspace](#add-tags-to-a-workspace). | | `POST` | `/workspaces/:workspace_id/relationships/data-retention-policy` | Call this endpoint to [show the workspace data retention policy](#show-data-retention-policy). | | `GET` | `/organizations/:organization_name/workspaces` | Call this endpoint to [list existing workspaces](#list-workspaces). Each project in the response contains a link to `effective-tag-bindings` and `tag-bindings` collections. You can filter the response by tag keys and values using a query string parameter. | | `GET` | `/organizations/:organization_name/workspaces/:name` | Call this endpoint to [show workspace details](#show-workspace) by querying the organization and workspace names. | | `GET` | `/workspaces/:workspace_id` | Call this endpoint to [show workspace details](#show-workspace). | | `GET` | `/workspaces/:workspace_id/relationships/remote-state-consumers` | Call this endpoint to [list remote state consumers](#get-remote-state-consumers). | | `GET` | `/workspaces/:workspace_id/relationships/tags` | Call this endpoint to [list flat string workspace tags](#get-tags). | | `GET` | `/workspaces/:workspace_id/tag-bindings` | Call this endpoint to [list workspace key-value tags](#get-tags) bound directly to this workspace. | | `GET` | `/workspaces/:workspace_id/effective-tag-bindings` | Call this endpoint to [list all workspace key-value tags](#get-tags), including both those bound directly to the workspace as well as those inherited from the parent project. | | `GET` | `/workspaces/:workspace_id/relationships/data-retention-policy` | Call this endpoint to [show the workspace data retention policy](#show-data-retention-policy). <alert enterprise/> | | `PATCH` | `/workspaces/:workspace_id/relationships/ssh-key` | Call this endpoint to manage SSH key assignments for workspaces. Refer to [Assign an SSH key to a workspace](#assign-an-ssh-key-to-a-workspace) and [Unassign an SSH key from a workspace](#unassign-an-ssh-key-from-a-workspace) for instructions. | | `PATCH` | `/workspaces/:workspace_id` | Call this endpoint to [update a workspace](#update-a-workspace). You can apply tags stored as key-value pairs when updating the workspace. | | `PATCH` | `/organizations/:organization_name/workspaces/:name` | Call this endpoint to [update a workspace](#update-a-workspace) by querying the organization and workspace names. | | `PATCH` | `/workspaces/:workspace_id/relationships/remote-state-consumers` | Call this endpoint to [replace remote state consumers](#replace-remote-state-consumers). | | `DELETE` | `/workspaces/:workspace_id/relationships/remote-state-consumers` | Call this endpoint to [delete remote state consumers](#delete-remote-state-consumers). | | `DELETE` | `/workspaces/:workspace_id/relationships/tags` | Call this endpoint to [delete flat string workspace tags](#remove-tags-from-workspace) from the workspace. | | `DELETE` | `/workspaces/:workspace_id/relationships/data-retention-policy` | Call this endpoint to [remove a workspace data retention policy](#remove-data-retention-policy). | | `DELETE` | `/workspaces/:workspace_id` | Call this endpoint to [force delete a workspace](#force-delete-a-workspace), which deletes the workspace without first checking for managed resources.| | `DELETE` | `/organizations/:organization_name/workspaces/:name` | Call this endpoint to [force delete a workspace](#force-delete-a-workspace), which deletes the workspace without first checking for managed resources, by querying the organization and workspace names. | ## Requirements - You must be a member of a team with the **Read** permission enabled for Terraform runs to view workspaces. - You must be a member of a team with the **Admin** permissions enabled on the workspace to change settings and force-unlock it. - You must be a member of a team with the **Lock/unlock** permission enabled to lock and unlock the workspace. - You must meet one of the following requirements to create a workspace: - Be the team owner - Be on a team with the **Manage all workspaces** permission enabled - Present an [organization API token](/terraform/cloud-docs/users-teams-organizations/api-tokens#organization-api-tokens) when calling the API. Refer to [Workspace Permissions](/terraform/cloud-docs/users-teams-organizations/permissions#workspace-permissions) for additional information. [permissions-citation]: #intentionally-unused---keep-for-maintainers ## Create a Workspace Use the following endpoint to create a new workspace: `POST /organizations/:organization_name/workspaces` | Parameter | Description | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `:organization_name` | The name of the organization to create the workspace in. The organization must already exist in the system, and the user must have permissions to create new workspaces. | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. By supplying the necessary attributes under a `vcs-repository` object, you can create a workspace that is configured against a VCS Repository. | Key path | Type | Default | Description | |--- | --- | ---| ---| | `data.type` | string | none | Must be `"workspaces"`. | | `data.attributes.name` | string | none | The name of the workspace. Workspace names can only include letters, numbers, `-`, and `_`. The name a unique identifier n the organization. | | `data.attributes.agent-pool-id` | string | none | Required when `execution-mode` is set to `agent`. The ID of the agent pool belonging to the workspace's organization. This value must not be specified if `execution-mode` is set to `remote` or `local` or if `operations` is set to `true`. | | `data.attributes.allow-destroy-plan` | boolean | `true` | Whether destroy plans can be queued on the workspace. | | `data.attributes.assessments-enabled` | boolean | `false` | (previously `drift-detection`) Whether or not HCP Terraform performs health assessments for the workspace. May be overridden by the organization setting `assessments-enforced`. Only available for Plus tier organizations, in workspaces running Terraform version 0.15.4+ and operating in [Remote execution mode](/terraform/cloud-docs/workspaces/settings#execution-mode). | | `data.attributes.auto-apply` | boolean | `false` | Whether to automatically apply changes when a Terraform plan is successful in runs initiated by VCS, UI or CLI, [with some exceptions](/terraform/cloud-docs/workspaces/settings#auto-apply-and-manual-apply). | | `data.attributes.auto-apply-run-trigger` | boolean | `false` | Whether to automatically apply changes when a Terraform plan is successful in runs initiated by run triggers. | | `data.attributes.auto-destroy-at` | string | (nothing) | Timestamp when the next scheduled destroy run will occur, refer to [Scheduled Destroy](/terraform/cloud-docs/workspaces/settings/deletion#automatically-destroy). | | `data.attributes.auto-destroy-activity-duration`| string | (nothing) | Value and units for [automatically scheduled destroy runs based on workspace activity](/terraform/cloud-docs/workspaces/settings/deletion#automatically-destroy). Valid values are greater than 0 and four digits or less. Valid units are `d` and `h`. For example, to queue destroy runs after fourteen days of inactivity set `auto-destroy-activity-duration: "14d"`. | | `data.attributes.description` | string | (nothing) | A description for the workspace. | | `data.attributes.execution-mode` | string | (nothing) | Which [execution mode](/terraform/cloud-docs/workspaces/settings#execution-mode) to use. Valid values are `remote`, `local`, and `agent`. When set to `local`, the workspace will be used for state storage only. This value _must not_ be specified if `operations` is specified, and _must_ be specified if `setting-overwrites.execution-mode` is set to `true`. | | `data.attributes.file-triggers-enabled` | boolean | `true` | Whether to filter runs based on the changed files in a VCS push. If enabled, it uses either `trigger-prefixes` in conjunction with `working_directory` or `trigger-patterns` to describe the set of changed files that will start a run. If disabled, any push triggers a run. | | `data.attributes.global-remote-state` | boolean | `false` | Whether the workspace should allow all workspaces in the organization to [access its state data](/terraform/cloud-docs/workspaces/state) during runs. If `false`, then only specifically approved workspaces can access its state. Manage allowed workspaces using the [Remote State Consumers](/terraform/cloud-docs/api-docs/workspaces#get-remote-state-consumers) endpoints, documented later on this page. Terraform Enterprise admins can choose the default value for new workspaces if this attribute is omitted. | | `data.attributes.operations` | boolean | `true` | **DEPRECATED** Use `execution-mode` instead. Whether to use remote execution mode. When set to `false`, the workspace will be used for state storage only. This value must not be specified if `execution-mode` is specified. | | `data.attributes.queue-all-runs` | boolean | `false` | Whether runs should be queued immediately after workspace creation. When set to false, runs triggered by a VCS change will not be queued until at least one run is manually queued. | | `data.attributes.source-name` | string | none | A friendly name for the application or client creating this workspace. If set, this will be displayed on the workspace as "Created via `<SOURCE NAME>`". | | `data.attributes.source-url` | string | none | A URL for the application or client creating this workspace. This can be the URL of a related resource in another app, or a link to documentation or other info about the client. | | `data.attributes.speculative-enabled` | boolean | `true` | Whether this workspace allows automatic [speculative plans][]. Setting this to `false` prevents HCP Terraform from running plans on pull requests, which can improve security if the VCS repository is public or includes untrusted contributors. It doesn't prevent manual speculative plans via the CLI or the runs API. | | `data.attributes.terraform-version` | string | latest release | Specifies the version of Terraform to use for this workspace. You can specify an exact version or a [version constraint](/terraform/language/expressions/version-constraints) such as `~> 1.0.0`. If you specify a constraint, the workspace always uses the newest release that meets that constraint. If omitted when creating a workspace, this defaults to the latest released version. | | `data.attributes.trigger-patterns` | array | `[]` | List of glob patterns that describe the files HCP Terraform monitors for changes. Trigger patterns are always appended to the root directory of the repository. | | `data.attributes.trigger-prefixes` | array | `[]` | List of trigger prefixes that describe the paths HCP Terraform monitors for changes, in addition to the working directory. Trigger prefixes are always appended to the root directory of the repository. HCP Terraform starts a run when files are changed in any directory path matching the provided set of prefixes. | | `data.attributes.vcs-repo.branch` | string | repository's default branch | The repository branch that Terraform executes from. If omitted or submitted as an empty string, this defaults to the repository's default branch. | | `data.attributes.vcs-repo.identifier` | string | none | A reference to your VCS repository in the format :org/:repo where :org and :repo refer to the organization and repository in your VCS provider. The format for Azure DevOps is `:org/:project/_git/:repo`. | | `data.attributes.vcs-repo.ingress-submodules` | boolean | `false` | Whether submodules should be fetched when cloning the VCS repository. | | `data.attributes.vcs-repo.oauth-token-id` | string | none | Specifies the VCS OAuth connection and token. Call the [`oauth-tokens`](/terraform/cloud-docs/api-docs/oauth-tokens) endpoint to retrieve the OAuth ID. | | `data.attributes.vcs-repo.tags-regex` | string | none | A regular expression used to match Git tags. HCP Terraform triggers a run when this value is present and a VCS event occurs that contains a matching Git tag for the regular expression.| | `data.attributes.vcs-repo` | object | none | Settings for the workspace's VCS repository. If omitted, the workspace is created without a VCS repo. If included, you must specify at least the `oauth-token-id` and `identifier` keys. | | `data.attributes.working-directory` | string | (nothing) | A relative path that Terraform will execute within. This defaults to the root of your repository and is typically set to a subdirectory matching the environment when multiple environments exist within the same repository. | | `data.attributes.setting-overwrites` | object | none | The keys in this object are attributes that have organization-level defaults. Each attribute key stores a boolean value which is `true` by default. To overwrite the default inherited value, set an attribute's value to `false`. For example, to set `execution-mode` as the organization default, set `setting-overwrites.execution-mode` to `false`. | | `data.relationships` | object | none | Specifies a group of workspace associations. | | `data.relationships.project.data.id` | string | default project | The ID of the project to create the workspace in. If left blank, Terraform creates the workspace in the organization's default project. You must have permission to create workspaces in the project, either by organization-level permissions or team admin access to a specific project. | | `data.relationships.tag-bindings.data` | list of objects | none | Specifies a list of tags to attach to the workspace. | | `data.relationships.tag-bindings.data.type` | string | none | Must be `tag-bindings` for each object in the list. | | `data.relationships.tag-bindings.data.attributes.key` | string | none | Specifies the tag key for each object in the list. | | `data.relationships.tag-bindings.data.attributes.value` | string | none | Specifies the tag value for each object in the list. | ### Sample Payload _Without a VCS repository_ ```json { "data": { "attributes": { "name": "workspace-1" }, "type": "workspaces", "relationships": { "tag-bindings": [ { "data": { "type": "tag-binding", "attributes": { "key": "env", "value": "test"} } } ] } } } ``` _With a VCS repository_ ```json { "data": { "attributes": { "name": "workspace-2", "terraform_version": "0.11.1", "working-directory": "", "vcs-repo": { "identifier": "example/terraform-test-proj", "oauth-token-id": "ot-hmAyP66qk2AMVdbJ", "branch": "", "tags-regex": null } }, "type": "workspaces", "relationships": { "tag-bindings": [ { "data": { "type": "tag-binding", "attributes": { "key": "env", "value": "test"} } } ] } } } ``` _Using Git Tags_ HCP Terraform triggers a run when you push a Git tag that matches the regular expression (SemVer): `1.2.3`, `22.33.44`, etc. ```json { "data": { "attributes": { "name": "workspace-3", "terraform_version": "0.12.1", "file-triggers-enabled": false, "working-directory": "/networking", "vcs-repo": { "identifier": "example/terraform-test-proj-monorepo", "oauth-token-id": "ot-hmAyP66qk2AMVdbJ", "branch": "", "tags-regex": "\d+.\d+.\d+" } }, "type": "workspaces", "relationships": { "tag-bindings": [ { "data": { "type": "tag-binding", "attributes": { "key": "env", "value": "test"} } } ] } } } ``` _For a monorepo using trigger prefixes_ A run will be triggered in this workspace when changes are detected in any of the specified directories: `/networking`, `/modules`, or `/vendor`. ```json { "data": { "attributes": { "name": "workspace-3", "terraform_version": "0.12.1", "file-triggers-enabled": true, "trigger-prefixes": ["/modules", "/vendor"], "working-directory": "/networking", "vcs-repo": { "identifier": "example/terraform-test-proj-monorepo", "oauth-token-id": "ot-hmAyP66qk2AMVdbJ", "branch": "" }, "updated-at": "2017-11-29T19:18:09.976Z" }, "type": "workspaces", "relationships": { "tag-bindings": [ { "data": { "type": "tag-binding", "attributes": { "key": "env", "value": "test"} } } ] } } } ``` _For a monorepo using trigger patterns_ A run will be triggered in this workspace when HCP Terraform detects any of the following changes: - A file with the extension `tf` in any directory structure in which the last folder is named `networking` (e.g., `root/networking` and `root/module/networking`) - Any file changed in the folder `/base`, no subfolders are included - Any file changed in the folder `/submodule` and all of its subfolders ```json { "data": { "attributes": { "name": "workspace-4", "terraform_version": "1.2.2", "file-triggers-enabled": true, "trigger-patterns": ["/**/networking/*.tf", "/base/*", "/submodule/**/*"], "vcs-repo": { "identifier": "example/terraform-test-proj-monorepo", "oauth-token-id": "ot-hmAyP66qk2AMVdbJ", "branch": "" }, "updated-at": "2022-06-09T19:18:09.976Z" }, "type": "workspaces", "relationships": { "tag-bindings": [ { "data": { "type": "tag-binding", "attributes": { "key": "env", "value": "test"} } } ] } } } ``` _Using HCP Terraform agents_ [HCP Terraform agents](/terraform/cloud-docs/api-docs/agents) allow HCP Terraform to communicate with isolated, private, or on-premises infrastructure. ```json { "data": { "attributes": { "name":"workspace-1", "execution-mode": "agent", "agent-pool-id": "apool-ZjT6A7mVFm5WHT5a" } }, "type": "workspaces", "relationships": { "tag-bindings": [ { "data": { "type": "tag-binding", "attributes": { "key": "env", "value": "test"} } } ] } } ``` _Using an organization default execution mode_ ```json { "data": { "attributes": { "name":"workspace-with-default", "setting-overwrites": { "execution-mode": false } } }, "type": "workspaces", "relationships": { "tag-bindings": [ { "data": { "type": "tag-binding", "attributes": { "key": "env", "value": "test"} } } ] } } ``` _With a project_ ```json { "data": { "type": "workspaces", "attributes": { "name": "workspace-in-project" }, "relationships": { "project": { "data": { "type": "projects", "id": "prj-jT92VLSFpv8FwKtc" } }, "tag-bindings": [ { "data": { "type": "tag-binding", "attributes": { "key": "env", "value": "test"} } } ] } } } ``` _With key-value tags_ ```json { "data": { "type": "workspaces", "attributes": { "name": "workspace-in-project" }, "relationships": { "tag-bindings": { "data": { "key": "cost-center", "value": "engineering" } } } } } ``` ### Sample Request ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/organizations/my-organization/workspaces ``` ### Sample Response _Without a VCS repository_ **Note:** The `assessments-enabled` property is only accepted by or returned from HCP Terraform. @include 'api-code-blocks/workspace.mdx' _With a VCS repository_ @include 'api-code-blocks/workspace-with-vcs.mdx' _With a project_ ```json { "data": { "id": "ws-HRkJLSYWF97jucqQ", "type": "workspaces", "attributes": { "allow-destroy-plan": true, "auto-apply": false, "auto-apply-run-trigger": false, "auto-destroy-at": null, "auto-destroy-activity-duration": null, "created-at": "2022-12-05T20:57:13.829Z", "environment": "default", "locked": false, "locked-reason": "", "name": "workspace-in-project", "queue-all-runs": false, "speculative-enabled": true, "structured-run-output-enabled": true, "terraform-version": "1.3.5", "working-directory": null, "global-remote-state": true, "updated-at": "2022-12-05T20:57:13.829Z", "resource-count": 0, "apply-duration-average": null, "plan-duration-average": null, "policy-check-failures": null, "run-failures": null, "workspace-kpis-runs-count": null, "latest-change-at": "2022-12-05T20:57:13.829Z", "operations": true, "execution-mode": "remote", "vcs-repo": null, "vcs-repo-identifier": null, "permissions": { "can-update": true, "can-destroy": true, "can-queue-run": true, "can-read-variable": true, "can-update-variable": true, "can-read-state-versions": true, "can-read-state-outputs": true, "can-create-state-versions": true, "can-queue-apply": true, "can-lock": true, "can-unlock": true, "can-force-unlock": true, "can-read-settings": true, "can-manage-tags": true, "can-manage-run-tasks": false, "can-force-delete": true, "can-manage-assessments": true, "can-read-assessment-results": true, "can-queue-destroy": true }, "actions": { "is-destroyable": true }, "description": null, "file-triggers-enabled": true, "trigger-prefixes": [], "trigger-patterns": [], "assessments-enabled": false, "last-assessment-result-at": null, "source": "tfe-api", "source-name": null, "source-url": null, "tag-names": [], "setting-overwrites": { "execution-mode": false, "agent-pool": false } }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" } }, "current-run": { "data": null }, "effective-tag-bindings": { "links": { "related": "/api/v2/workspaces/ws-HRkJLSYWF97jucqQ/effective-tag-bindings" } }, "latest-run": { "data": null }, "outputs": { "data": [] }, "remote-state-consumers": { "links": { "related": "/api/v2/workspaces/ws-HRkJLSYWF97jucqQ/relationships/remote-state-consumers" } }, "current-state-version": { "data": null }, "current-configuration-version": { "data": null }, "agent-pool": { "data": null }, "readme": { "data": null }, "project": { "data": { "id": "prj-jT92VLSFpv8FwKtc", "type": "projects" } }, "current-assessment-result": { "data": null }, "tag-bindings": { "links": { "related": "/api/v2/workspaces/ws-HRkJLSYWF97jucqQ/tag-bindings" } "vars": { "data": [] }, }, "links": { "self": "/api/v2/organizations/my-organization/workspaces/workspace-in-project" } } } ``` ## Update a Workspace Use one of the following endpoint to update a workspace: - `PATCH /organizations/:organization_name/workspaces/:name` - `PATCH /workspaces/:workspace_id` | Parameter | Description | | --------------- | --------------------------------- | | `:workspace_id` | The ID of the workspace to update | | `:organization_name` | The name of the organization the workspace belongs to. | | `:name` | The name of the workspace to update. Workspace names are unique identifiers in the organization and can only include letters, numbers, `-`, and `_`. | ### Request Body These PATCH endpoints require a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | |-----------------------------------------------|----------------|------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `data.type` | string | | Must be `"workspaces"`. | | `data.attributes.name` | string | (previous value) | A new name for the workspace, which can only include letters, numbers, `-`, and `_`. This will be used as an identifier and must be unique in the organization. **Warning:** Changing a workspace's name changes its URL in the API and UI. | | `data.attributes.agent-pool-id` | string | (previous value) | Required when `execution-mode` is set to `agent`. The ID of the agent pool belonging to the workspace's organization. This value must not be specified if `execution-mode` is set to `remote` or `local` or if `operations` is set to `true`. | | `data.attributes.allow-destroy-plan` | boolean | (previous value) | Whether destroy plans can be queued on the workspace. | | `data.attributes.assessments-enabled` | boolean | `false` | (previously `drift-detection`) Whether or not HCP Terraform performs health assessments for the workspace. May be overridden by the organization setting `assessments-enforced`. Only available for Plus tier organizations, in workspaces running Terraform version 0.15.4+ and operating in [Remote execution mode](/terraform/cloud-docs/workspaces/settings#execution-mode). | | `data.attributes.auto-apply` | boolean | (previous value) | Whether to automatically apply changes when a Terraform plan is successful in runs initiated by VCS, UI or CLI, [with some exceptions](/terraform/cloud-docs/workspaces/settings#auto-apply-and-manual-apply). | | `data.attributes.auto-apply-run-trigger` | boolean | (previous value) | Whether to automatically apply changes when a Terraform plan is successful in runs initiated by run triggers. | | `data.attributes.auto-destroy-at` | string | (previous value) | Timestamp when the next scheduled destroy run will occur, refer to [Scheduled Destroy](/terraform/cloud-docs/workspaces/settings/deletion#automatically-destroy). | | `data.attributes.auto-destroy-activity-duration`| string | (previous value) | Value and units for [automatically scheduled destroy runs based on workspace activity](/terraform/cloud-docs/workspaces/settings/deletion#automatically-destroy). Valid values are greater than 0 and four digits or less. Valid units are `d` and `h`. For example, to queue destroy runs after fourteen days of inactivity set `auto-destroy-activity-duration: "14d"`. | | `data.attributes.description` | string | (previous value) | A description for the workspace. | | `data.attributes.execution-mode` | string | (previous value) | Which [execution mode](/terraform/cloud-docs/workspaces/settings#execution-mode) to use. Valid values are `remote`, `local`, and `agent`. When set to `local`, the workspace will be used for state storage only. This value _must not_ be specified if `operations` is specified, and _must_ be specified if `setting-overwrites.execution-mode` is set to `true`. | | `data.attributes.file-triggers-enabled` | boolean | (previous value) | Whether to filter runs based on the changed files in a VCS push. If enabled, it uses either `trigger-prefixes` in conjunction with `working_directory` or `trigger-patterns` to describe the set of changed files that will start a run. If disabled, any push will trigger a run. | | `data.attributes.global-remote-state` | boolean | (previous value) | Whether the workspace should allow all workspaces in the organization to [access its state data](/terraform/cloud-docs/workspaces/state) during runs. If `false`, then only specifically approved workspaces can access its state. Manage allowed workspaces using the [Remote State Consumers](/terraform/cloud-docs/api-docs/workspaces#get-remote-state-consumers) endpoints, documented later on this page. | | `data.attributes.operations` | boolean | (previous value) | **DEPRECATED** Use `execution-mode` instead. Whether to use remote execution mode. When set to `false`, the workspace will be used for state storage only. This value must not be specified if `execution-mode` is specified. | | `data.attributes.queue-all-runs` | boolean | (previous value) | Whether runs should be queued immediately after workspace creation. When set to false, runs triggered by a VCS change will not be queued until at least one run is manually queued. | | `data.attributes.speculative-enabled` | boolean | (previous value) | Whether this workspace allows automatic [speculative plans][]. Setting this to `false` prevents HCP Terraform from running plans on pull requests, which can improve security if the VCS repository is public or includes untrusted contributors. It doesn't prevent manual speculative plans via the CLI or the runs API. | | `data.attributes.terraform-version` | string | (previous value) | The version of Terraform to use for this workspace. This can be either an exact version or a [version constraint](/terraform/language/expressions/version-constraints) (like `~> 1.0.0`); if you specify a constraint, the workspace will always use the newest release that meets that constraint. | | `data.attributes.trigger-patterns` | array | (previous value) | List of glob patterns that describe the files HCP Terraform monitors for changes. Trigger patterns are always appended to the root directory of the repository. | | `data.attributes.trigger-prefixes` | array | (previous value) | List of trigger prefixes that describe the paths HCP Terraform monitors for changes, in addition to the working directory. Trigger prefixes are always appended to the root directory of the repository. HCP Terraform will start a run when files are changed in any directory path matching the provided set of prefixes. | | `data.attributes.vcs-repo.branch` | string | (previous value) | The repository branch that Terraform will execute from. | | `data.attributes.vcs-repo.identifier` | string | (previous value) | A reference to your VCS repository in the format :org/:repo where :org and :repo refer to the organization and repository in your VCS provider. The format for Azure DevOps is `:org/:project/_git/:repo`. | | `data.attributes.vcs-repo.ingress-submodules` | boolean | (previous value) | Whether submodules should be fetched when cloning the VCS repository. | | `data.attributes.vcs-repo.oauth-token-id` | string | | The VCS Connection (OAuth Connection + Token) to use as identified. Get this ID from the [oauth-tokens](/terraform/cloud-docs/api-docs/oauth-tokens) endpoint. You can not specify this value if `github-app-installation-id` is specified. | | `data.attributes.vcs-repo.github-app-installation-id` | string | | The VCS Connection GitHub App Installation to use. Find this ID on the account settings page. Requires previously authorizing the GitHub App and generating a user-to-server token. Manage the token from **Account Settings** within HCP Terraform. You can not specify this value if `oauth-token-id` is specified. | | `data.attributes.vcs-repo.tags-regex` | string | (previous value) | A regular expression used to match Git tags. HCP Terraform triggers a run when this value is present and a VCS event occurs that contains a matching Git tag for the regular expression. | | `data.attributes.vcs-repo` | object or null | (previous value) | To delete a workspace's existing VCS repo, specify `null` instead of an object. To modify a workspace's existing VCS repo, include whichever of the keys below you wish to modify. To add a new VCS repo to a workspace that didn't previously have one, include at least the `oauth-token-id` and `identifier` keys. | | `data.attributes.working-directory` | string | (previous value) | A relative path that Terraform will execute within. This defaults to the root of your repository and is typically set to a subdirectory matching the environment when multiple environments exist within the same repository. | | `data.attributes.setting-overwrites` | object | | The keys in this object are attributes that have organization-level defaults. Each attribute key stores a boolean value which is `true` by default. To overwrite the default inherited value, set an attribute's value to `false`. For example, to set `execution-mode` as the organization default, you set `setting-overwrites.execution-mode = false`. | | `data.relationships` | object | none | Specifies a group of workspace relationships. | | `data.relationships.project.data.id` | string | existing value | The ID of the project to move the workspace to. If left blank or unchanged, the workspace will not be moved. You must have admin permissions on both the source project and destination project in order to move a workspace between projects. | | `data.relationships.tag-bindings.data` | list of objects | none | Specifies a list of tags to attach to the workspace. | | `data.relationships.tag-bindings.data.type` | string | none | Must be `tag-bindings` for each object in the list. | | `data.relationships.tag-bindings.data.attributes.key` | string | none | Specifies the tag key for each object in the list. | | `data.relationships.tag-bindings.data.attributes.value` | string | none | Specifies the tag value for each object in the list. | ### Sample Payload ```json { "data": { "attributes": { "name": "workspace-2", "resource-count": 0, "terraform_version": "0.11.1", "working-directory": "", "vcs-repo": { "identifier": "example/terraform-test-proj", "branch": "", "ingress-submodules": false, "oauth-token-id": "ot-hmAyP66qk2AMVdbJ" }, "updated-at": "2017-11-29T19:18:09.976Z" }, "relationships": { "project": { "data": { "type": "projects", "id": "prj-7HWWPGY3fYxztELU" } }, "tag-bindings": { "data": [ { "type": "tag-bindings", "attributes": { "key": "environment", "value": "development" } }, ] } }, "type": "workspaces" } } ``` ### Sample Request ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request PATCH \ --data @payload.json \ https://app.terraform.io/api/v2/organizations/my-organization/workspaces/workspace-2 ``` ### Sample Response @include 'api-code-blocks/workspace-with-vcs.mdx' ## List workspaces This endpoint lists workspaces in the organization. `GET /organizations/:organization_name/workspaces` | Parameter | Description | | -------------------- | ------------------------------------------------------- | | `:organization_name` | The name of the organization to list the workspaces of. | ### Query Parameters This endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. | Parameter | Description | |-------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `page[number]` | **Optional.** If omitted, the endpoint will return the first page. | | `page[size]` | **Optional.** If omitted, the endpoint will return 20 workspaces per page. | | `search[name]` | **Optional.** If specified, restricts results to workspaces with a name that matches the search string using a fuzzy search. | | `search[tags]` | **Optional.** If specified, restricts results to workspaces with that tag. If multiple comma separated values are specified, results matching all of the tags are returned. | | `search[exclude-tags]` | **Optional.** If specified, results exclude workspaces with that tag. If multiple comma separated values are specified, workspaces with tags matching any of the tags are excluded. | | `search[wildcard-name]` | **Optional.** If specified, restricts results to workspaces with partial matching, using `*` on prefix, suffix, or both. For example, `search[wildcard-name]=*-prod` returns all workspaces ending in `-prod`, `search[wildcard-name]=prod-*` returns all workspaces beginning with `prod-`, and `search[wildcard-name]=*-prod-*` returns all workspaces with substring `-prod-` regardless of prefix and/or suffix. | | `sort` | **Optional.** Allows sorting the organization's workspaces by a provided value. You can sort by `"name"`, `"current-run.created-at"` (the time of the current run), and `"latest-change-at"` (the creation time of the latest state version or the workspace itself if no state version exists). Prepending a hyphen to the sort parameter reverses the order. For example, `"-name"` sorts by name in reverse alphabetical order. If omitted, the default sort order is arbitrary but stable. | | `filter[project][id]` | **Optional.** If specified, restricts results to workspaces in the specific project. | | `filter[current-run][status]` | **Optional.** If specified, restricts results to workspaces that match the status of a current run. | | `filter[tagged][i][key]` | **Optional.** If specified, restricts results to workspaces that are tagged with the provided key. Use a value of "0" for `i` if you are only using a single filter. For multiple tag filters, use an incrementing integer value for each filter. Multiple tag filters will be combined together with a logical AND when filtering results. | | `filter[tagged][i][value]` | **Optional.** If specified, restricts results to workspaces that are tagged with the provided value. This is useful when combined with a `key` filter for more specificity. Use a value of "0" for `i` if you are only using a single filter. For multiple tag filters, use an incrementing integer value for each filter. Multiple tag filters will be combined together with a logical AND when filtering results. | ### Sample Request ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/organizations/my-organization/workspaces ``` _With multiple tag filters_ ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/organizations/my-organization/workspaces?filter%5B%tagged5D%5B0%5D%5Bkey%5D=environment&filter%5B%tagged5D%5B0%5D%5Bvalue%5D=development&filter%5B%tagged5D%5B1%5D%5Bkey%5D=meets-compliance ``` ### Sample Response @include 'api-code-blocks/workspaces-list.mdx' ## Show workspace Details on a workspace can be retrieved from two endpoints, which behave identically. One refers to a workspace by its ID: `GET /workspaces/:workspace_id` | Parameter | Description | | --------------- | ---------------- | | `:workspace_id` | The workspace ID | The other refers to a workspace by its name and organization: `GET /organizations/:organization_name/workspaces/:name` | Parameter | Description | | -------------------- | ----------------------------------------------------------------------------------------------------- | | `:organization_name` | The name of the organization the workspace belongs to. | | `:name` | The name of the workspace to show details for, which can only include letters, numbers, `-`, and `_`. | ### Workspace performance attributes The following attributes are helpful in determining the overall health and performance of your workspace configuration. These metrics refer to the **past 30 runs that have either resulted in an error or successfully applied**. | Parameter | Type | Description | | ------------------------------------------ | ------ | --------------------------------------------------------------------------------------- | | `data.attributes.apply-duration-average` | number | This is the average time runs spend in the **apply** phase, represented in milliseconds | | `data.attributes.plan-duration-average` | number | This is the average time runs spend in the **plan** phase, represented in milliseconds | | `data.attributes.policy-check-failures` | number | Reports the number of run failures resulting from a policy check failure | | `data.attributes.run-failures` | number | Reports the number of failed runs | | `data.attributes.workspace-kpis-run-count` | number | Total number of runs taken into account by these metrics | ### Sample Request ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/organizations/my-organization/workspaces/workspace-1 ``` ### Sample Response @include 'api-code-blocks/workspace.mdx' ## Safe Delete a workspace When you delete an HCP Terraform workspace with resources, Terraform can no longer track or manage that infrastructure. During a safe delete, HCP Terraform only deletes the workspace if it is not managing resources. You can safe delete a workspace using two endpoints that behave identically. The first endpoint identifies a workspace with the workspace ID, and the other identifies the workspace by its name and organization. `POST /workspaces/:workspace_id/actions/safe-delete` | Parameter | Description | | --------------- | --------------------------------- | | `:workspace_id` | The ID of the workspace to delete. | `POST /organizations/:organization_name/workspaces/:name/actions/safe-delete` | Parameter | Description | | -------------------- | ------------------------------------------------------------------------------------------- | | `:organization_name` | The name of the workspace's organization. | | `:name` | The name of the workspace to delete, which can only include letters, numbers, `-`, and `_`. | | Status | Response | Reason(s) | | ------- | --------------------------| --------------------------------------------------------------------- | | [204][] | No Content | Successfully deleted the workspace | | [404][] | [JSON API error object][] | Workspace not found, or user unauthorized to perform workspace delete | | [409][] | [JSON API error object][] | Workspace is not safe to delete because it is managing resources | ## Force Delete a workspace During a force delete, HCP Terraform removes the specified workspace without checking whether it is managing resources. We recommend using the [safe delete endpoint](#safe-delete-a-workspace) instead, when possible. !> **Warning:** Terraform cannot track or manage the workspace's infrastructure after deletion. We recommend [destroying the workspace's infrastructure](/terraform/cloud-docs/run/modes-and-options#destroy-mode) before you delete it. By default, only organization owners can force delete workspaces. Organization owners can also update [organization's settings](/terraform/cloud-docs/users-teams organizations/organizations#general) to let workspace admins force delete their own workspaces. You can use two endpoints to force delete a workspace, which behave identically. One endpoint identifies the workspace with its workspace ID and the other endpoint identifies the workspace with its name and organization. `DELETE /workspaces/:workspace_id` | Parameter | Description | | --------------- | --------------------------------- | | `:workspace_id` | The ID of the workspace to delete | `DELETE /organizations/:organization_name/workspaces/:name` | Parameter | Description | | -------------------- | ------------------------------------------------------------------------------------------- | | `:organization_name` | The name of the organization the workspace belongs to. | | `:name` | The name of the workspace to delete, which can only include letters, numbers, `-`, and `_`. | | Status | Response | Reason(s) | | ------- | --------------------------| --------------------------------------------------------------------- | | [204][] | No Content | Successfully deleted the workspace | | [403][] | [JSON API error object][] | Not authorized to perform a force delete on the workspace | | [404][] | [JSON API error object][] | Workspace not found, or user unauthorized to perform workspace delete | ### Sample Request ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request DELETE \ https://app.terraform.io/api/v2/organizations/my-organization/workspaces/workspace-1 ``` ## Lock a workspace This endpoint locks a workspace. `POST /workspaces/:workspace_id/actions/lock` | Parameter | Description | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | `:workspace_id` | The workspace ID to lock. Obtain this from the [workspace settings](/terraform/cloud-docs/workspaces/settings) or the [Show Workspace](#show-workspace) endpoint. | | Status | Response | Reason(s) | | ------- | -------------------------------------------- | ----------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "workspaces"`) | Successfully locked the workspace | | [404][] | [JSON API error object][] | Workspace not found, or user unauthorized to perform action | | [409][] | [JSON API error object][] | Workspace already locked | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | -------- | ------ | ------- | ------------------------------------- | | `reason` | string | `""` | The reason for locking the workspace. | ### Sample Payload ```json { "reason": "Locking workspace-1" } ``` ### Sample Request ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/workspaces/ws-SihZTyXKfNXUWuUa/actions/lock ``` ### Sample Response @include 'api-code-blocks/workspace.mdx' ## Unlock a workspace This endpoint unlocks a workspace. Unlocking a workspace sets the current state version to the latest finalized intermediate state version. If intermediate state versions are available, but HCP Terraform has not yet finalized the latest intermediate state version, the unlock will fail with a 503 response. For this particular error, it's recommended to retry the unlock operation for a short period of time until the platform finalizes the state version. If you must force-unlock a workspace under these conditions, ensure that state was saved successfully by inspecting the latest state version using the [State Version List API](/terraform/cloud-docs/api-docs/state-versions#list-state-versions-for-a-workspace) `POST /workspaces/:workspace_id/actions/unlock` | Parameter | Description | | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | `:workspace_id` | The workspace ID to unlock. Obtain this from the [workspace settings](/terraform/cloud-docs/workspaces/settings) or the [Show Workspace](#show-workspace) endpoint. | | Status | Response | Reason(s) | | ------- | -------------------------------------------- | ----------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "workspaces"`) | Successfully unlocked the workspace | | [404][] | [JSON API error object][] | Workspace not found, or user unauthorized to perform action | | [409][] | [JSON API error object][] | Workspace already unlocked, or locked by a different user | ### Sample Request ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ https://app.terraform.io/api/v2/workspaces/ws-SihZTyXKfNXUWuUa/actions/unlock ``` ### Sample Response @include 'api-code-blocks/workspace.mdx' ## Force Unlock a workspace This endpoint force unlocks a workspace. Only users with admin access are authorized to force unlock a workspace. `POST /workspaces/:workspace_id/actions/force-unlock` | Parameter | Description | | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `:workspace_id` | The workspace ID to force unlock. Obtain this from the [workspace settings](/terraform/cloud-docs/workspaces/settings) or the [Show Workspace](#show-workspace) endpoint. | | Status | Response | Reason(s) | | ------- | -------------------------------------------- | ----------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "workspaces"`) | Successfully force unlocked the workspace | | [404][] | [JSON API error object][] | Workspace not found, or user unauthorized to perform action | | [409][] | [JSON API error object][] | Workspace already unlocked | ### Sample Request ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ https://app.terraform.io/api/v2/workspaces/ws-SihZTyXKfNXUWuUa/actions/force-unlock ``` ### Sample Response @include 'api-code-blocks/workspace-with-vcs.mdx' ## Assign an SSH key to a workspace This endpoint assigns an SSH key to a workspace. `PATCH /workspaces/:workspace_id/relationships/ssh-key` | Parameter | Description | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `:workspace_id` | The workspace ID to assign the SSH key to. Obtain this from the [workspace settings](/terraform/cloud-docs/workspaces/settings) or the [Show Workspace](#show-workspace) endpoint. | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | -------------------- | ------ | ------- | -------------------------------------------------------------------------------------------------- | | `data.type` | string | | Must be `"workspaces"`. | | `data.attributes.id` | string | | The SSH key ID to assign. Obtain this from the [ssh-keys](/terraform/cloud-docs/api-docs/ssh-keys) endpoint. | #### Sample Payload ```json { "data": { "attributes": { "id": "sshkey-GxrePWre1Ezug7aM" }, "type": "workspaces" } } ``` ### Sample Request ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request PATCH \ --data @payload.json \ https://app.terraform.io/api/v2/workspaces/ws-SihZTyXKfNXUWuUa/relationships/ssh-key ``` ### Sample Response @include 'api-code-blocks/workspace-with-vcs.mdx' ## Unassign an SSH key from a workspace This endpoint unassigns the currently assigned SSH key from a workspace. `PATCH /workspaces/:workspace_id/relationships/ssh-key` | Parameter | Description | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `:workspace_id` | The workspace ID to assign the SSH key to. Obtain this from the [workspace settings](/terraform/cloud-docs/workspaces/settings) or the [Show Workspace](#show-workspace) endpoint. | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | -------------------- | ------ | ------- | ----------------------- | | `data.type` | string | | Must be `"workspaces"`. | | `data.attributes.id` | string | | Must be `null`. | ### Sample Payload ```json { "data": { "attributes": { "id": null }, "type": "workspaces" } } ``` ### Sample Request ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request PATCH \ --data @payload.json \ https://app.terraform.io/api/v2/workspaces/ws-SihZTyXKfNXUWuUa/relationships/ssh-key ``` ### Sample Response @include 'api-code-blocks/workspace-with-vcs.mdx' ## Get Remote State Consumers `GET /workspaces/:workspace_id/relationships/remote-state-consumers` | Parameter | Description | | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `:workspace_id` | The workspace ID to get remote state consumers for. Obtain this from the [workspace settings](/terraform/cloud-docs/workspaces/settings) or the [Show Workspace](#show-workspace) endpoint. | This endpoint retrieves the list of other workspaces that are allowed to access the given workspace's state during runs. * If `global-remote-state` is set to false for the workspace, this will return the list of other workspaces that are specifically authorized to access the workspace's state. * If `global-remote-state` is set to true, this will return a list of every workspace in the organization except for the subject workspace. The list returned by this endpoint is subject to the caller's normal workspace permissions; it will not include workspaces that the provided API token is unable to read. ### Query Parameters This endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. | Parameter | Description | | -------------- | -------------------------------------------------------------------------- | | `page[number]` | **Optional.** If omitted, the endpoint will return the first page. | | `page[size]` | **Optional.** If omitted, the endpoint will return 20 workspaces per page. | ### Sample Request ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/workspaces/ws-SihZTyXKfNXUWuUa/relationships/remote-state-consumers ``` ### Sample Response @include 'api-code-blocks/workspaces-list.mdx' ## Replace Remote State Consumers `PATCH /workspaces/:workspace_id/relationships/remote-state-consumers` | Parameter | Description | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `:workspace_id` | The workspace ID to replace remote state consumers for. Obtain this from the [workspace settings](/terraform/cloud-docs/workspaces/settings) or the [Show Workspace](#show-workspace) endpoint. | This endpoint updates the workspace's remote state consumers to be _exactly_ the list of workspaces specified in the payload. It can only be used for workspaces where `global-remote-state` is false. This endpoint can only be used by teams with permission to manage workspaces for the entire organization — only those who can _view_ the entire list of consumers can _replace_ the entire list. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) Teams with admin permissions on specific workspaces can still modify remote state consumers for those workspaces, but must use the add (POST) and remove (DELETE) endpoints listed below instead of this PATCH endpoint. [permissions-citation]: #intentionally-unused---keep-for-maintainers | Status | Response | Reason(s) | | ------- | ------------------------- | --------------------------------------------------------------------- | | [204][] | No Content | Successfully updated remote state consumers | | [404][] | [JSON API error object][] | Workspace not found, or user unauthorized to perform action | | [422][] | [JSON API error object][] | Problem with payload or request; details provided in the error object | ### Request Body This PATCH endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | ------------- | ------ | ------- | ----------------------------------------------------------- | | `data[].type` | string | | Must be `"workspaces"`. | | `data[].id` | string | | The ID of a workspace to be set as a remote state consumer. | ### Sample Payload ```json { "data": [ { "id": "ws-7aiqKYf6ejMFdtWS", "type": "workspaces" } ] } ``` ### Sample Request ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request PATCH \ --data @payload.json \ https://app.terraform.io/api/v2/workspaces/ws-UYv6RYM8fVhzeGG5/relationships/remote-state-consumers ``` ### Response No response body. Status code `204`. ## Add Remote State Consumers `POST /workspaces/:workspace_id/relationships/remote-state-consumers` | Parameter | Description | | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `:workspace_id` | The workspace ID to add remote state consumers for. Obtain this from the [workspace settings](/terraform/cloud-docs/workspaces/settings) or the [Show Workspace](#show-workspace) endpoint. | This endpoint adds one or more remote state consumers to the workspace. It can only be used for workspaces where `global-remote-state` is false. * The workspaces specified as consumers must be readable to the API token that makes the request. * A workspace cannot be added as a consumer of itself. (A workspace can always read its own state, regardless of access settings.) * You can safely add a consumer workspace that is already present; it will be ignored, and the rest of the consumers in the request will be processed normally. | Status | Response | Reason(s) | | ------- | ------------------------- | --------------------------------------------------------------------- | | [204][] | No Content | Successfully updated remote state consumers | | [404][] | [JSON API error object][] | Workspace not found, or user unauthorized to perform action | | [422][] | [JSON API error object][] | Problem with payload or request; details provided in the error object | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | ------------- | ------ | ------- | ----------------------------------------------------------- | | `data[].type` | string | | Must be `"workspaces"`. | | `data[].id` | string | | The ID of a workspace to be set as a remote state consumer. | ### Sample Payload ```json { "data": [ { "id": "ws-7aiqKYf6ejMFdtWS", "type": "workspaces" } ] } ``` ### Sample Request ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/workspaces/ws-UYv6RYM8fVhzeGG5/relationships/remote-state-consumers ``` ### Response No response body. Status code `204`. ## Delete Remote State Consumers `DELETE /workspaces/:workspace_id/relationships/remote-state-consumers` | Parameter | Description | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `:workspace_id` | The workspace ID to remove remote state consumers for. Obtain this from the [workspace settings](/terraform/cloud-docs/workspaces/settings) or the [Show Workspace](#show-workspace) endpoint. | This endpoint removes one or more remote state consumers from a workspace, according to the contents of the payload. It can only be used for workspaces where `global-remote-state` is false. * The workspaces specified as consumers must be readable to the API token that makes the request. * You can safely remove a consumer workspace that is already absent; it will be ignored, and the rest of the consumers in the request will be processed normally. | Status | Response | Reason(s) | | ------- | ------------------------- | --------------------------------------------------------------------- | | [204][] | No Content | Successfully updated remote state consumers | | [404][] | [JSON API error object][] | Workspace not found, or user unauthorized to perform action | | [422][] | [JSON API error object][] | Problem with payload or request; details provided in the error object | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | ------------- | ------ | ------- | ---------------------------------------------------------------- | | `data[].type` | string | | Must be `"workspaces"`. | | `data[].id` | string | | The ID of a workspace to remove from the remote state consumers. | ### Sample Payload ```json { "data": [ { "id": "ws-7aiqKYf6ejMFdtWS", "type": "workspaces" } ] } ``` ### Sample Request ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request DELETE \ --data @payload.json \ https://app.terraform.io/api/v2/workspaces/ws-UYv6RYM8fVhzeGG5/relationships/remote-state-consumers ``` ### Response No response body. Status code `204`. ## Get tags Call the following endpoints to list the tags attached to a workspace: - `GET /workspaces/:workspace_id/relationships/tags`: Lists flat string tags attached to the workspace. - `GET /workspaces/:workspace_id/tag-bindings`: Lists key-value tags directly bound to the workspace. - `GET /workspaces/:workspace_id/effective-tag-bindings`: Lists all key-value tags bound to the workspace, including those inherited from the parent project. ### Path parameters | Parameter | Description | | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `:workspace_id` | The workspace ID to fetch tags for. Obtain this from the [workspace settings](/terraform/cloud-docs/workspaces/settings) or the [Show Workspace](#show-workspace) endpoint. | ### Query Parameters The flat string tags endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. | Parameter | Description | | -------------- | -------------------------------------------------------------------------- | | `page[number]` | **Optional.** If omitted, the endpoint will return the first page. | | `page[size]` | **Optional.** If omitted, the endpoint will return 20 workspaces per page. | ### Sample Requests <CodeBlockConfig hideClipboard heading="List flat string tags attached to the workspace"> ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/workspaces/workspace-2/relationships/tags ``` </CodeBlockConfig> <CodeBlockConfig hideClipboard heading="List key-value tags bound directly to the workspace"> ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/workspaces/workspace-2/tag-bindings ``` </CodeBlockConfig> <CodeBlockConfig hideClipboard heading="List all key-value tags bound to the workspace, including those inherited from the parent project"> ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/workspaces/workspace-2/effective-tag-bindings ``` </CodeBlockConfig> ### Sample Responses <CodeBlockConfig hideClipboard heading="List flat string tags attached to the workspace"> ```json { "data": [ { "id": "tag-1", "type": "tags", "attributes": { "name": "tag1", "created-at": "2022-03-09T06:04:39.585Z", "instance-count": 1 }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" } } } }, { "id": "tag-2", "type": "tags", "attributes": { "name": "tag2", "created-at": "2022-03-09T06:04:39.585Z", "instance-count": 2 }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" } } } } ] } ``` </CodeBlockConfig> <CodeBlockConfig hideClipboard heading="List key-value tags bound directly to the workspace"> ```json { "data": [ { "id": "tb-RKs9JSC2lInns32K", "type": "tag-bindings", "attributes": { "key": "ws1-key", "value": "ws1-value" } } ] } ``` </CodeBlockConfig> <CodeBlockConfig hideClipboard heading="List all key-value tags bound to the workspace, including those inherited from the parent project"> ```json { "data": [ { "type": "effective-tag-bindings", "attributes": { "key": "ws1-key", "value": "ws1-value" } }, { "type": "effective-tag-bindings", "attributes": { "key": "key1", "value": "value1" } }, { "type": "effective-tag-bindings", "attributes": { "key": "key2", "value": "value2" } } ] } ``` </CodeBlockConfig> ## Add flat string tags to a workspace `POST /workspaces/:workspace_id/relationships/tags` To add key-value tags to an existing workspace, call the `PATCH /workspaces/:workspace_id` and provide workspace tag bindings in the JSON payload. Refer to [Update a workspace](#update-a-workspace) for additional information. You can also bind key-value tags when creating a workspace. Refer to [Create a workspace](#create-a-workspace) for additional information. Refer to [Define project tags](/terraform/cloud-docs/projects/manage#define-project-tags) for information about supported tag values. | Parameter | Description | | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `:workspace_id` | The workspace ID to add tags to. Obtain this from the [workspace settings](/terraform/cloud-docs/workspaces/settings) or the [Show Workspace](#show-workspace) endpoint. | | Status | Response | Reason(s) | | ------- | ------------------------- | ----------------------------------------------------------- | | [204][] | No Content | Successfully added tags to workspace | | [404][] | [JSON API error object][] | Workspace not found, or user unauthorized to perform action | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. It is important to note that `type`, as well as one of `id` _or_ `attributes.name` is required. | Key path | Type | Default | Description | | ------------------------ | ------ | ------- | --------------------------- | | `data[].type` | string | | Must be `"tags"`. | | `data[].id` | string | | The ID of the tag to add. | | `data[].attributes.name` | string | | The name of the tag to add. | ### Sample Payload ```json { "data": [ { "type": "tags", "attributes": { "name": "foo" } }, { "type": "tags", "attributes": { "name": "bar" } } ] } ``` ### Sample Request ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/workspaces/workspace-2/relationships/tags ``` ### Sample Response No response body. Status code `204`. ## Remove tags from workspace This endpoint removes one or more tags from a workspace. The workspace must already exist, and tag element that supplies an `id` attribute must exist. If the `name` attribute is used, and no matching organization tag is found, no action will occur for that entry. Tags removed from all workspaces will be removed from the organization-wide list. To remove key-value tags to an existing workspace, call the `PATCH /workspaces/:workspace_id` and provide workspace tag bindings in the JSON payload. Refer to [Update a workspace](#update-a-workspace) for additional information. `DELETE /workspaces/:workspace_id/relationships/tags` | Parameter | Description | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `:workspace_id` | The workspace ID to remove tags from. Obtain this from the [workspace settings](/terraform/cloud-docs/workspaces/settings) or the [Show Workspace](#show-workspace) endpoint. | | Status | Response | Reason(s) | | ------- | ------------------------- | ----------------------------------------------------------- | | [204][] | No Content | Successfully removed tags to workspace | | [404][] | [JSON API error object][] | Workspace not found, or user unauthorized to perform action | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. It is important to note that `type`, as well as one of `id` _or_ `attributes.name` is required. | Key path | Type | Default | Description | | ------------------------ | ------ | ------- | ------------------------------ | | `data[].type` | string | | Must be `"tags"`. | | `data[].id` | string | | The ID of the tag to remove. | | `data[].attributes.name` | string | | The name of the tag to remove. | ### Sample Payload ```json { "data": [ { "type": "tags", "id": "tag-Yfha4YpPievQ8wJw" } ] } ``` ### Sample Request ```shell-session $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request DELETE \ --data @payload.json \ https://app.terraform.io/api/v2/workspaces/workspace-2/relationships/tags ``` ### Sample Response No response body. Status code `204`. ## Show data retention policy <EnterpriseAlert> This endpoint is exclusive to Terraform Enterprise and is not available in HCP Terraform. </EnterpriseAlert> `GET /workspaces/:workspace_id/relationships/data-retention-policy` | Parameter | Description | | ---------------------| --------------------------------------------------------------------| | `:workspace_id` | The ID of the workspace to show the data retention policy for. Obtain this from the [workspace settings](/terraform/enterprise/workspaces/settings) or by sending a `GET` request to the [`/workspaces`](#show-workspace) endpoint. | This endpoint shows the data retention policy set explicitly on the workspace. When no data retention policy is set for the workspace, the endpoint returns the default policy configured for the organization. Refer to [Data Retention Policies](/terraform/enterprise/workspaces/settings/deletion#data-retention-policies) for instructions on configuring data retention policies for workspaces. Refer to [Data Retention Policy API](/terraform/enterprise/api-docs/data-retention-policies#show-data-retention-policy) in the Terraform Enterprise documentation for details. ## Create or update data retention policy <EnterpriseAlert> This endpoint is exclusive to Terraform Enterprise and is not available in HCP Terraform. </EnterpriseAlert> `POST /workspaces/:workspace_id/relationships/data-retention-policy` | Parameter | Description | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `:workspace_id` | The workspace ID to update the data retention policy for. Obtain this from the [workspace settings](/terraform/enterprise/workspaces/settings) or by sending a `GET` request to the [`/workspaces`](#show-workspace) endpoint. | This endpoint creates a data retention policy for a workspace or updates the existing policy. Refer to [Data Retention Policies](/terraform/enterprise/workspaces/settings/deletion#data-retention-policies) for additional information. Refer to [Data Retention Policy API](/terraform/enterprise/api-docs/data-retention-policies#create-or-update-data-retention-policy) in the Terraform Enterprise documentation for details. ## Remove data retention policy <EnterpriseAlert> This endpoint is exclusive to Terraform Enterprise and is not available in HCP Terraform. </EnterpriseAlert> `DELETE /workspaces/:workspace_id/relationships/data-retention-policy` | Parameter | Description | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `:workspace_id` | The workspace ID to remove the data retenetion policy for. Obtain this from the [workspace settings](/terraform/enterprise/workspaces/settings) or by sending a `GET` request to the [`/workspaces`](#show-workspace) endpoint. | This endpoint removes the data retention policy explicitly set on a workspace. When no data retention policy is set for the workspace, the endpoint returns the default policy configured for the organization. Refer to [Data Retention Policies](/terraform/enterprise/users-teams-organizations/organizations#destruction-and-deletion) for instructions on configuring data retention policies for organizations. Read more about [workspace data retention policies](/terraform/enterprise/workspaces/settings/deletion#data-retention-policies). Refer to [Data Retention Policy API](/terraform/enterprise/api-docs/data-retention-policies#remove-data-retention-policy) in the Terraform Enterprise documentation for details. ## Available Related Resources The GET endpoints above can optionally return related resources, if requested with [the `include` query parameter](/terraform/cloud-docs/api-docs#inclusion-of-related-resources). The following resource types are available: * `current_configuration_version` - The last configuration this workspace received, excluding plan-only configurations. Terraform uses this configuration for new runs, unless you provide a different one. * `current_configuration_version.ingress_attributes` - The commit information for the current configuration version. * `current_run` - Additional information about the current run. * `current_run.configuration_version` - The configuration used in the current run. * `current_run.configuration_version.ingress_attributes` - The commit information used in the current run. * `current_run.plan` - The plan used in the current run. * `locked_by` - The user, team, or run responsible for locking the workspace, if the workspace is currently locked. * `organization` - The full organization record. * `outputs` - The outputs for the most recently applied run. * `project` - The full project record. * `readme` - The most recent workspace README.md.
terraform
page title Workspaces API Docs HCP Terraform description Use the workspaces endpoint to interact with workspaces List show create update lock unlock and delete a workspace and manage SSH keys remote state consumers and tags using the HTTP API 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects speculative plans terraform cloud docs run remote operations speculative plans Workspaces API This topic provides reference information about the workspaces AP Workspaces represent running infrastructure managed by Terraform Overview The scope of the API includes the following endpoints Method Path Action POST organizations organization name workspaces Call this endpoint to create a workspace create a workspace You can apply tags stored as key value pairs when creating the workspace POST organizations organization name workspaces name actions safe delete Call this endpoint to safely delete a workspace safe delete a workspace by querying the organization and workspace names POST workspaces workspace id actions safe delete Call this endpoint safely delete a workspace safe delete a workspace by querying the workspace ID POST workspaces workspace id actions lock Call this endpoint to lock a workspace lock a workspace POST workspaces workspace id actions unlock Call this endpoint to unlock a workspace unlock a workspace POST workspaces workspace id actions force unlock Call this endpoint to force a workspace to unlock force unlock a workspace POST workspaces workspace id relationships remote state consumers Call this endpoint to add remote state consumers get remote state consumers POST workspaces workspace id relationships tags Call this endpoint to bind flat string tags to an existing workspace add tags to a workspace POST workspaces workspace id relationships data retention policy Call this endpoint to show the workspace data retention policy show data retention policy GET organizations organization name workspaces Call this endpoint to list existing workspaces list workspaces Each project in the response contains a link to effective tag bindings and tag bindings collections You can filter the response by tag keys and values using a query string parameter GET organizations organization name workspaces name Call this endpoint to show workspace details show workspace by querying the organization and workspace names GET workspaces workspace id Call this endpoint to show workspace details show workspace GET workspaces workspace id relationships remote state consumers Call this endpoint to list remote state consumers get remote state consumers GET workspaces workspace id relationships tags Call this endpoint to list flat string workspace tags get tags GET workspaces workspace id tag bindings Call this endpoint to list workspace key value tags get tags bound directly to this workspace GET workspaces workspace id effective tag bindings Call this endpoint to list all workspace key value tags get tags including both those bound directly to the workspace as well as those inherited from the parent project GET workspaces workspace id relationships data retention policy Call this endpoint to show the workspace data retention policy show data retention policy alert enterprise PATCH workspaces workspace id relationships ssh key Call this endpoint to manage SSH key assignments for workspaces Refer to Assign an SSH key to a workspace assign an ssh key to a workspace and Unassign an SSH key from a workspace unassign an ssh key from a workspace for instructions PATCH workspaces workspace id Call this endpoint to update a workspace update a workspace You can apply tags stored as key value pairs when updating the workspace PATCH organizations organization name workspaces name Call this endpoint to update a workspace update a workspace by querying the organization and workspace names PATCH workspaces workspace id relationships remote state consumers Call this endpoint to replace remote state consumers replace remote state consumers DELETE workspaces workspace id relationships remote state consumers Call this endpoint to delete remote state consumers delete remote state consumers DELETE workspaces workspace id relationships tags Call this endpoint to delete flat string workspace tags remove tags from workspace from the workspace DELETE workspaces workspace id relationships data retention policy Call this endpoint to remove a workspace data retention policy remove data retention policy DELETE workspaces workspace id Call this endpoint to force delete a workspace force delete a workspace which deletes the workspace without first checking for managed resources DELETE organizations organization name workspaces name Call this endpoint to force delete a workspace force delete a workspace which deletes the workspace without first checking for managed resources by querying the organization and workspace names Requirements You must be a member of a team with the Read permission enabled for Terraform runs to view workspaces You must be a member of a team with the Admin permissions enabled on the workspace to change settings and force unlock it You must be a member of a team with the Lock unlock permission enabled to lock and unlock the workspace You must meet one of the following requirements to create a workspace Be the team owner Be on a team with the Manage all workspaces permission enabled Present an organization API token terraform cloud docs users teams organizations api tokens organization api tokens when calling the API Refer to Workspace Permissions terraform cloud docs users teams organizations permissions workspace permissions for additional information permissions citation intentionally unused keep for maintainers Create a Workspace Use the following endpoint to create a new workspace POST organizations organization name workspaces Parameter Description organization name The name of the organization to create the workspace in The organization must already exist in the system and the user must have permissions to create new workspaces Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required By supplying the necessary attributes under a vcs repository object you can create a workspace that is configured against a VCS Repository Key path Type Default Description data type string none Must be workspaces data attributes name string none The name of the workspace Workspace names can only include letters numbers and The name a unique identifier n the organization data attributes agent pool id string none Required when execution mode is set to agent The ID of the agent pool belonging to the workspace s organization This value must not be specified if execution mode is set to remote or local or if operations is set to true data attributes allow destroy plan boolean true Whether destroy plans can be queued on the workspace data attributes assessments enabled boolean false previously drift detection Whether or not HCP Terraform performs health assessments for the workspace May be overridden by the organization setting assessments enforced Only available for Plus tier organizations in workspaces running Terraform version 0 15 4 and operating in Remote execution mode terraform cloud docs workspaces settings execution mode data attributes auto apply boolean false Whether to automatically apply changes when a Terraform plan is successful in runs initiated by VCS UI or CLI with some exceptions terraform cloud docs workspaces settings auto apply and manual apply data attributes auto apply run trigger boolean false Whether to automatically apply changes when a Terraform plan is successful in runs initiated by run triggers data attributes auto destroy at string nothing Timestamp when the next scheduled destroy run will occur refer to Scheduled Destroy terraform cloud docs workspaces settings deletion automatically destroy data attributes auto destroy activity duration string nothing Value and units for automatically scheduled destroy runs based on workspace activity terraform cloud docs workspaces settings deletion automatically destroy Valid values are greater than 0 and four digits or less Valid units are d and h For example to queue destroy runs after fourteen days of inactivity set auto destroy activity duration 14d data attributes description string nothing A description for the workspace data attributes execution mode string nothing Which execution mode terraform cloud docs workspaces settings execution mode to use Valid values are remote local and agent When set to local the workspace will be used for state storage only This value must not be specified if operations is specified and must be specified if setting overwrites execution mode is set to true data attributes file triggers enabled boolean true Whether to filter runs based on the changed files in a VCS push If enabled it uses either trigger prefixes in conjunction with working directory or trigger patterns to describe the set of changed files that will start a run If disabled any push triggers a run data attributes global remote state boolean false Whether the workspace should allow all workspaces in the organization to access its state data terraform cloud docs workspaces state during runs If false then only specifically approved workspaces can access its state Manage allowed workspaces using the Remote State Consumers terraform cloud docs api docs workspaces get remote state consumers endpoints documented later on this page Terraform Enterprise admins can choose the default value for new workspaces if this attribute is omitted data attributes operations boolean true DEPRECATED Use execution mode instead Whether to use remote execution mode When set to false the workspace will be used for state storage only This value must not be specified if execution mode is specified data attributes queue all runs boolean false Whether runs should be queued immediately after workspace creation When set to false runs triggered by a VCS change will not be queued until at least one run is manually queued data attributes source name string none A friendly name for the application or client creating this workspace If set this will be displayed on the workspace as Created via SOURCE NAME data attributes source url string none A URL for the application or client creating this workspace This can be the URL of a related resource in another app or a link to documentation or other info about the client data attributes speculative enabled boolean true Whether this workspace allows automatic speculative plans Setting this to false prevents HCP Terraform from running plans on pull requests which can improve security if the VCS repository is public or includes untrusted contributors It doesn t prevent manual speculative plans via the CLI or the runs API data attributes terraform version string latest release Specifies the version of Terraform to use for this workspace You can specify an exact version or a version constraint terraform language expressions version constraints such as 1 0 0 If you specify a constraint the workspace always uses the newest release that meets that constraint If omitted when creating a workspace this defaults to the latest released version data attributes trigger patterns array List of glob patterns that describe the files HCP Terraform monitors for changes Trigger patterns are always appended to the root directory of the repository data attributes trigger prefixes array List of trigger prefixes that describe the paths HCP Terraform monitors for changes in addition to the working directory Trigger prefixes are always appended to the root directory of the repository HCP Terraform starts a run when files are changed in any directory path matching the provided set of prefixes data attributes vcs repo branch string repository s default branch The repository branch that Terraform executes from If omitted or submitted as an empty string this defaults to the repository s default branch data attributes vcs repo identifier string none A reference to your VCS repository in the format org repo where org and repo refer to the organization and repository in your VCS provider The format for Azure DevOps is org project git repo data attributes vcs repo ingress submodules boolean false Whether submodules should be fetched when cloning the VCS repository data attributes vcs repo oauth token id string none Specifies the VCS OAuth connection and token Call the oauth tokens terraform cloud docs api docs oauth tokens endpoint to retrieve the OAuth ID data attributes vcs repo tags regex string none A regular expression used to match Git tags HCP Terraform triggers a run when this value is present and a VCS event occurs that contains a matching Git tag for the regular expression data attributes vcs repo object none Settings for the workspace s VCS repository If omitted the workspace is created without a VCS repo If included you must specify at least the oauth token id and identifier keys data attributes working directory string nothing A relative path that Terraform will execute within This defaults to the root of your repository and is typically set to a subdirectory matching the environment when multiple environments exist within the same repository data attributes setting overwrites object none The keys in this object are attributes that have organization level defaults Each attribute key stores a boolean value which is true by default To overwrite the default inherited value set an attribute s value to false For example to set execution mode as the organization default set setting overwrites execution mode to false data relationships object none Specifies a group of workspace associations data relationships project data id string default project The ID of the project to create the workspace in If left blank Terraform creates the workspace in the organization s default project You must have permission to create workspaces in the project either by organization level permissions or team admin access to a specific project data relationships tag bindings data list of objects none Specifies a list of tags to attach to the workspace data relationships tag bindings data type string none Must be tag bindings for each object in the list data relationships tag bindings data attributes key string none Specifies the tag key for each object in the list data relationships tag bindings data attributes value string none Specifies the tag value for each object in the list Sample Payload Without a VCS repository json data attributes name workspace 1 type workspaces relationships tag bindings data type tag binding attributes key env value test With a VCS repository json data attributes name workspace 2 terraform version 0 11 1 working directory vcs repo identifier example terraform test proj oauth token id ot hmAyP66qk2AMVdbJ branch tags regex null type workspaces relationships tag bindings data type tag binding attributes key env value test Using Git Tags HCP Terraform triggers a run when you push a Git tag that matches the regular expression SemVer 1 2 3 22 33 44 etc json data attributes name workspace 3 terraform version 0 12 1 file triggers enabled false working directory networking vcs repo identifier example terraform test proj monorepo oauth token id ot hmAyP66qk2AMVdbJ branch tags regex d d d type workspaces relationships tag bindings data type tag binding attributes key env value test For a monorepo using trigger prefixes A run will be triggered in this workspace when changes are detected in any of the specified directories networking modules or vendor json data attributes name workspace 3 terraform version 0 12 1 file triggers enabled true trigger prefixes modules vendor working directory networking vcs repo identifier example terraform test proj monorepo oauth token id ot hmAyP66qk2AMVdbJ branch updated at 2017 11 29T19 18 09 976Z type workspaces relationships tag bindings data type tag binding attributes key env value test For a monorepo using trigger patterns A run will be triggered in this workspace when HCP Terraform detects any of the following changes A file with the extension tf in any directory structure in which the last folder is named networking e g root networking and root module networking Any file changed in the folder base no subfolders are included Any file changed in the folder submodule and all of its subfolders json data attributes name workspace 4 terraform version 1 2 2 file triggers enabled true trigger patterns networking tf base submodule vcs repo identifier example terraform test proj monorepo oauth token id ot hmAyP66qk2AMVdbJ branch updated at 2022 06 09T19 18 09 976Z type workspaces relationships tag bindings data type tag binding attributes key env value test Using HCP Terraform agents HCP Terraform agents terraform cloud docs api docs agents allow HCP Terraform to communicate with isolated private or on premises infrastructure json data attributes name workspace 1 execution mode agent agent pool id apool ZjT6A7mVFm5WHT5a type workspaces relationships tag bindings data type tag binding attributes key env value test Using an organization default execution mode json data attributes name workspace with default setting overwrites execution mode false type workspaces relationships tag bindings data type tag binding attributes key env value test With a project json data type workspaces attributes name workspace in project relationships project data type projects id prj jT92VLSFpv8FwKtc tag bindings data type tag binding attributes key env value test With key value tags json data type workspaces attributes name workspace in project relationships tag bindings data key cost center value engineering Sample Request shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 organizations my organization workspaces Sample Response Without a VCS repository Note The assessments enabled property is only accepted by or returned from HCP Terraform include api code blocks workspace mdx With a VCS repository include api code blocks workspace with vcs mdx With a project json data id ws HRkJLSYWF97jucqQ type workspaces attributes allow destroy plan true auto apply false auto apply run trigger false auto destroy at null auto destroy activity duration null created at 2022 12 05T20 57 13 829Z environment default locked false locked reason name workspace in project queue all runs false speculative enabled true structured run output enabled true terraform version 1 3 5 working directory null global remote state true updated at 2022 12 05T20 57 13 829Z resource count 0 apply duration average null plan duration average null policy check failures null run failures null workspace kpis runs count null latest change at 2022 12 05T20 57 13 829Z operations true execution mode remote vcs repo null vcs repo identifier null permissions can update true can destroy true can queue run true can read variable true can update variable true can read state versions true can read state outputs true can create state versions true can queue apply true can lock true can unlock true can force unlock true can read settings true can manage tags true can manage run tasks false can force delete true can manage assessments true can read assessment results true can queue destroy true actions is destroyable true description null file triggers enabled true trigger prefixes trigger patterns assessments enabled false last assessment result at null source tfe api source name null source url null tag names setting overwrites execution mode false agent pool false relationships organization data id my organization type organizations current run data null effective tag bindings links related api v2 workspaces ws HRkJLSYWF97jucqQ effective tag bindings latest run data null outputs data remote state consumers links related api v2 workspaces ws HRkJLSYWF97jucqQ relationships remote state consumers current state version data null current configuration version data null agent pool data null readme data null project data id prj jT92VLSFpv8FwKtc type projects current assessment result data null tag bindings links related api v2 workspaces ws HRkJLSYWF97jucqQ tag bindings vars data links self api v2 organizations my organization workspaces workspace in project Update a Workspace Use one of the following endpoint to update a workspace PATCH organizations organization name workspaces name PATCH workspaces workspace id Parameter Description workspace id The ID of the workspace to update organization name The name of the organization the workspace belongs to name The name of the workspace to update Workspace names are unique identifiers in the organization and can only include letters numbers and Request Body These PATCH endpoints require a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string Must be workspaces data attributes name string previous value A new name for the workspace which can only include letters numbers and This will be used as an identifier and must be unique in the organization Warning Changing a workspace s name changes its URL in the API and UI data attributes agent pool id string previous value Required when execution mode is set to agent The ID of the agent pool belonging to the workspace s organization This value must not be specified if execution mode is set to remote or local or if operations is set to true data attributes allow destroy plan boolean previous value Whether destroy plans can be queued on the workspace data attributes assessments enabled boolean false previously drift detection Whether or not HCP Terraform performs health assessments for the workspace May be overridden by the organization setting assessments enforced Only available for Plus tier organizations in workspaces running Terraform version 0 15 4 and operating in Remote execution mode terraform cloud docs workspaces settings execution mode data attributes auto apply boolean previous value Whether to automatically apply changes when a Terraform plan is successful in runs initiated by VCS UI or CLI with some exceptions terraform cloud docs workspaces settings auto apply and manual apply data attributes auto apply run trigger boolean previous value Whether to automatically apply changes when a Terraform plan is successful in runs initiated by run triggers data attributes auto destroy at string previous value Timestamp when the next scheduled destroy run will occur refer to Scheduled Destroy terraform cloud docs workspaces settings deletion automatically destroy data attributes auto destroy activity duration string previous value Value and units for automatically scheduled destroy runs based on workspace activity terraform cloud docs workspaces settings deletion automatically destroy Valid values are greater than 0 and four digits or less Valid units are d and h For example to queue destroy runs after fourteen days of inactivity set auto destroy activity duration 14d data attributes description string previous value A description for the workspace data attributes execution mode string previous value Which execution mode terraform cloud docs workspaces settings execution mode to use Valid values are remote local and agent When set to local the workspace will be used for state storage only This value must not be specified if operations is specified and must be specified if setting overwrites execution mode is set to true data attributes file triggers enabled boolean previous value Whether to filter runs based on the changed files in a VCS push If enabled it uses either trigger prefixes in conjunction with working directory or trigger patterns to describe the set of changed files that will start a run If disabled any push will trigger a run data attributes global remote state boolean previous value Whether the workspace should allow all workspaces in the organization to access its state data terraform cloud docs workspaces state during runs If false then only specifically approved workspaces can access its state Manage allowed workspaces using the Remote State Consumers terraform cloud docs api docs workspaces get remote state consumers endpoints documented later on this page data attributes operations boolean previous value DEPRECATED Use execution mode instead Whether to use remote execution mode When set to false the workspace will be used for state storage only This value must not be specified if execution mode is specified data attributes queue all runs boolean previous value Whether runs should be queued immediately after workspace creation When set to false runs triggered by a VCS change will not be queued until at least one run is manually queued data attributes speculative enabled boolean previous value Whether this workspace allows automatic speculative plans Setting this to false prevents HCP Terraform from running plans on pull requests which can improve security if the VCS repository is public or includes untrusted contributors It doesn t prevent manual speculative plans via the CLI or the runs API data attributes terraform version string previous value The version of Terraform to use for this workspace This can be either an exact version or a version constraint terraform language expressions version constraints like 1 0 0 if you specify a constraint the workspace will always use the newest release that meets that constraint data attributes trigger patterns array previous value List of glob patterns that describe the files HCP Terraform monitors for changes Trigger patterns are always appended to the root directory of the repository data attributes trigger prefixes array previous value List of trigger prefixes that describe the paths HCP Terraform monitors for changes in addition to the working directory Trigger prefixes are always appended to the root directory of the repository HCP Terraform will start a run when files are changed in any directory path matching the provided set of prefixes data attributes vcs repo branch string previous value The repository branch that Terraform will execute from data attributes vcs repo identifier string previous value A reference to your VCS repository in the format org repo where org and repo refer to the organization and repository in your VCS provider The format for Azure DevOps is org project git repo data attributes vcs repo ingress submodules boolean previous value Whether submodules should be fetched when cloning the VCS repository data attributes vcs repo oauth token id string The VCS Connection OAuth Connection Token to use as identified Get this ID from the oauth tokens terraform cloud docs api docs oauth tokens endpoint You can not specify this value if github app installation id is specified data attributes vcs repo github app installation id string The VCS Connection GitHub App Installation to use Find this ID on the account settings page Requires previously authorizing the GitHub App and generating a user to server token Manage the token from Account Settings within HCP Terraform You can not specify this value if oauth token id is specified data attributes vcs repo tags regex string previous value A regular expression used to match Git tags HCP Terraform triggers a run when this value is present and a VCS event occurs that contains a matching Git tag for the regular expression data attributes vcs repo object or null previous value To delete a workspace s existing VCS repo specify null instead of an object To modify a workspace s existing VCS repo include whichever of the keys below you wish to modify To add a new VCS repo to a workspace that didn t previously have one include at least the oauth token id and identifier keys data attributes working directory string previous value A relative path that Terraform will execute within This defaults to the root of your repository and is typically set to a subdirectory matching the environment when multiple environments exist within the same repository data attributes setting overwrites object The keys in this object are attributes that have organization level defaults Each attribute key stores a boolean value which is true by default To overwrite the default inherited value set an attribute s value to false For example to set execution mode as the organization default you set setting overwrites execution mode false data relationships object none Specifies a group of workspace relationships data relationships project data id string existing value The ID of the project to move the workspace to If left blank or unchanged the workspace will not be moved You must have admin permissions on both the source project and destination project in order to move a workspace between projects data relationships tag bindings data list of objects none Specifies a list of tags to attach to the workspace data relationships tag bindings data type string none Must be tag bindings for each object in the list data relationships tag bindings data attributes key string none Specifies the tag key for each object in the list data relationships tag bindings data attributes value string none Specifies the tag value for each object in the list Sample Payload json data attributes name workspace 2 resource count 0 terraform version 0 11 1 working directory vcs repo identifier example terraform test proj branch ingress submodules false oauth token id ot hmAyP66qk2AMVdbJ updated at 2017 11 29T19 18 09 976Z relationships project data type projects id prj 7HWWPGY3fYxztELU tag bindings data type tag bindings attributes key environment value development type workspaces Sample Request shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json request PATCH data payload json https app terraform io api v2 organizations my organization workspaces workspace 2 Sample Response include api code blocks workspace with vcs mdx List workspaces This endpoint lists workspaces in the organization GET organizations organization name workspaces Parameter Description organization name The name of the organization to list the workspaces of Query Parameters This endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters Remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs Parameter Description page number Optional If omitted the endpoint will return the first page page size Optional If omitted the endpoint will return 20 workspaces per page search name Optional If specified restricts results to workspaces with a name that matches the search string using a fuzzy search search tags Optional If specified restricts results to workspaces with that tag If multiple comma separated values are specified results matching all of the tags are returned search exclude tags Optional If specified results exclude workspaces with that tag If multiple comma separated values are specified workspaces with tags matching any of the tags are excluded search wildcard name Optional If specified restricts results to workspaces with partial matching using on prefix suffix or both For example search wildcard name prod returns all workspaces ending in prod search wildcard name prod returns all workspaces beginning with prod and search wildcard name prod returns all workspaces with substring prod regardless of prefix and or suffix sort Optional Allows sorting the organization s workspaces by a provided value You can sort by name current run created at the time of the current run and latest change at the creation time of the latest state version or the workspace itself if no state version exists Prepending a hyphen to the sort parameter reverses the order For example name sorts by name in reverse alphabetical order If omitted the default sort order is arbitrary but stable filter project id Optional If specified restricts results to workspaces in the specific project filter current run status Optional If specified restricts results to workspaces that match the status of a current run filter tagged i key Optional If specified restricts results to workspaces that are tagged with the provided key Use a value of 0 for i if you are only using a single filter For multiple tag filters use an incrementing integer value for each filter Multiple tag filters will be combined together with a logical AND when filtering results filter tagged i value Optional If specified restricts results to workspaces that are tagged with the provided value This is useful when combined with a key filter for more specificity Use a value of 0 for i if you are only using a single filter For multiple tag filters use an incrementing integer value for each filter Multiple tag filters will be combined together with a logical AND when filtering results Sample Request shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 organizations my organization workspaces With multiple tag filters shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 organizations my organization workspaces filter 5B tagged5D 5B0 5D 5Bkey 5D environment filter 5B tagged5D 5B0 5D 5Bvalue 5D development filter 5B tagged5D 5B1 5D 5Bkey 5D meets compliance Sample Response include api code blocks workspaces list mdx Show workspace Details on a workspace can be retrieved from two endpoints which behave identically One refers to a workspace by its ID GET workspaces workspace id Parameter Description workspace id The workspace ID The other refers to a workspace by its name and organization GET organizations organization name workspaces name Parameter Description organization name The name of the organization the workspace belongs to name The name of the workspace to show details for which can only include letters numbers and Workspace performance attributes The following attributes are helpful in determining the overall health and performance of your workspace configuration These metrics refer to the past 30 runs that have either resulted in an error or successfully applied Parameter Type Description data attributes apply duration average number This is the average time runs spend in the apply phase represented in milliseconds data attributes plan duration average number This is the average time runs spend in the plan phase represented in milliseconds data attributes policy check failures number Reports the number of run failures resulting from a policy check failure data attributes run failures number Reports the number of failed runs data attributes workspace kpis run count number Total number of runs taken into account by these metrics Sample Request shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 organizations my organization workspaces workspace 1 Sample Response include api code blocks workspace mdx Safe Delete a workspace When you delete an HCP Terraform workspace with resources Terraform can no longer track or manage that infrastructure During a safe delete HCP Terraform only deletes the workspace if it is not managing resources You can safe delete a workspace using two endpoints that behave identically The first endpoint identifies a workspace with the workspace ID and the other identifies the workspace by its name and organization POST workspaces workspace id actions safe delete Parameter Description workspace id The ID of the workspace to delete POST organizations organization name workspaces name actions safe delete Parameter Description organization name The name of the workspace s organization name The name of the workspace to delete which can only include letters numbers and Status Response Reason s 204 No Content Successfully deleted the workspace 404 JSON API error object Workspace not found or user unauthorized to perform workspace delete 409 JSON API error object Workspace is not safe to delete because it is managing resources Force Delete a workspace During a force delete HCP Terraform removes the specified workspace without checking whether it is managing resources We recommend using the safe delete endpoint safe delete a workspace instead when possible Warning Terraform cannot track or manage the workspace s infrastructure after deletion We recommend destroying the workspace s infrastructure terraform cloud docs run modes and options destroy mode before you delete it By default only organization owners can force delete workspaces Organization owners can also update organization s settings terraform cloud docs users teams organizations organizations general to let workspace admins force delete their own workspaces You can use two endpoints to force delete a workspace which behave identically One endpoint identifies the workspace with its workspace ID and the other endpoint identifies the workspace with its name and organization DELETE workspaces workspace id Parameter Description workspace id The ID of the workspace to delete DELETE organizations organization name workspaces name Parameter Description organization name The name of the organization the workspace belongs to name The name of the workspace to delete which can only include letters numbers and Status Response Reason s 204 No Content Successfully deleted the workspace 403 JSON API error object Not authorized to perform a force delete on the workspace 404 JSON API error object Workspace not found or user unauthorized to perform workspace delete Sample Request shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json request DELETE https app terraform io api v2 organizations my organization workspaces workspace 1 Lock a workspace This endpoint locks a workspace POST workspaces workspace id actions lock Parameter Description workspace id The workspace ID to lock Obtain this from the workspace settings terraform cloud docs workspaces settings or the Show Workspace show workspace endpoint Status Response Reason s 200 JSON API document type workspaces Successfully locked the workspace 404 JSON API error object Workspace not found or user unauthorized to perform action 409 JSON API error object Workspace already locked Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description reason string The reason for locking the workspace Sample Payload json reason Locking workspace 1 Sample Request shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 workspaces ws SihZTyXKfNXUWuUa actions lock Sample Response include api code blocks workspace mdx Unlock a workspace This endpoint unlocks a workspace Unlocking a workspace sets the current state version to the latest finalized intermediate state version If intermediate state versions are available but HCP Terraform has not yet finalized the latest intermediate state version the unlock will fail with a 503 response For this particular error it s recommended to retry the unlock operation for a short period of time until the platform finalizes the state version If you must force unlock a workspace under these conditions ensure that state was saved successfully by inspecting the latest state version using the State Version List API terraform cloud docs api docs state versions list state versions for a workspace POST workspaces workspace id actions unlock Parameter Description workspace id The workspace ID to unlock Obtain this from the workspace settings terraform cloud docs workspaces settings or the Show Workspace show workspace endpoint Status Response Reason s 200 JSON API document type workspaces Successfully unlocked the workspace 404 JSON API error object Workspace not found or user unauthorized to perform action 409 JSON API error object Workspace already unlocked or locked by a different user Sample Request shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST https app terraform io api v2 workspaces ws SihZTyXKfNXUWuUa actions unlock Sample Response include api code blocks workspace mdx Force Unlock a workspace This endpoint force unlocks a workspace Only users with admin access are authorized to force unlock a workspace POST workspaces workspace id actions force unlock Parameter Description workspace id The workspace ID to force unlock Obtain this from the workspace settings terraform cloud docs workspaces settings or the Show Workspace show workspace endpoint Status Response Reason s 200 JSON API document type workspaces Successfully force unlocked the workspace 404 JSON API error object Workspace not found or user unauthorized to perform action 409 JSON API error object Workspace already unlocked Sample Request shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST https app terraform io api v2 workspaces ws SihZTyXKfNXUWuUa actions force unlock Sample Response include api code blocks workspace with vcs mdx Assign an SSH key to a workspace This endpoint assigns an SSH key to a workspace PATCH workspaces workspace id relationships ssh key Parameter Description workspace id The workspace ID to assign the SSH key to Obtain this from the workspace settings terraform cloud docs workspaces settings or the Show Workspace show workspace endpoint Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string Must be workspaces data attributes id string The SSH key ID to assign Obtain this from the ssh keys terraform cloud docs api docs ssh keys endpoint Sample Payload json data attributes id sshkey GxrePWre1Ezug7aM type workspaces Sample Request shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json request PATCH data payload json https app terraform io api v2 workspaces ws SihZTyXKfNXUWuUa relationships ssh key Sample Response include api code blocks workspace with vcs mdx Unassign an SSH key from a workspace This endpoint unassigns the currently assigned SSH key from a workspace PATCH workspaces workspace id relationships ssh key Parameter Description workspace id The workspace ID to assign the SSH key to Obtain this from the workspace settings terraform cloud docs workspaces settings or the Show Workspace show workspace endpoint Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string Must be workspaces data attributes id string Must be null Sample Payload json data attributes id null type workspaces Sample Request shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json request PATCH data payload json https app terraform io api v2 workspaces ws SihZTyXKfNXUWuUa relationships ssh key Sample Response include api code blocks workspace with vcs mdx Get Remote State Consumers GET workspaces workspace id relationships remote state consumers Parameter Description workspace id The workspace ID to get remote state consumers for Obtain this from the workspace settings terraform cloud docs workspaces settings or the Show Workspace show workspace endpoint This endpoint retrieves the list of other workspaces that are allowed to access the given workspace s state during runs If global remote state is set to false for the workspace this will return the list of other workspaces that are specifically authorized to access the workspace s state If global remote state is set to true this will return a list of every workspace in the organization except for the subject workspace The list returned by this endpoint is subject to the caller s normal workspace permissions it will not include workspaces that the provided API token is unable to read Query Parameters This endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters Remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs Parameter Description page number Optional If omitted the endpoint will return the first page page size Optional If omitted the endpoint will return 20 workspaces per page Sample Request shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 workspaces ws SihZTyXKfNXUWuUa relationships remote state consumers Sample Response include api code blocks workspaces list mdx Replace Remote State Consumers PATCH workspaces workspace id relationships remote state consumers Parameter Description workspace id The workspace ID to replace remote state consumers for Obtain this from the workspace settings terraform cloud docs workspaces settings or the Show Workspace show workspace endpoint This endpoint updates the workspace s remote state consumers to be exactly the list of workspaces specified in the payload It can only be used for workspaces where global remote state is false This endpoint can only be used by teams with permission to manage workspaces for the entire organization only those who can view the entire list of consumers can replace the entire list More about permissions terraform cloud docs users teams organizations permissions Teams with admin permissions on specific workspaces can still modify remote state consumers for those workspaces but must use the add POST and remove DELETE endpoints listed below instead of this PATCH endpoint permissions citation intentionally unused keep for maintainers Status Response Reason s 204 No Content Successfully updated remote state consumers 404 JSON API error object Workspace not found or user unauthorized to perform action 422 JSON API error object Problem with payload or request details provided in the error object Request Body This PATCH endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string Must be workspaces data id string The ID of a workspace to be set as a remote state consumer Sample Payload json data id ws 7aiqKYf6ejMFdtWS type workspaces Sample Request shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json request PATCH data payload json https app terraform io api v2 workspaces ws UYv6RYM8fVhzeGG5 relationships remote state consumers Response No response body Status code 204 Add Remote State Consumers POST workspaces workspace id relationships remote state consumers Parameter Description workspace id The workspace ID to add remote state consumers for Obtain this from the workspace settings terraform cloud docs workspaces settings or the Show Workspace show workspace endpoint This endpoint adds one or more remote state consumers to the workspace It can only be used for workspaces where global remote state is false The workspaces specified as consumers must be readable to the API token that makes the request A workspace cannot be added as a consumer of itself A workspace can always read its own state regardless of access settings You can safely add a consumer workspace that is already present it will be ignored and the rest of the consumers in the request will be processed normally Status Response Reason s 204 No Content Successfully updated remote state consumers 404 JSON API error object Workspace not found or user unauthorized to perform action 422 JSON API error object Problem with payload or request details provided in the error object Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string Must be workspaces data id string The ID of a workspace to be set as a remote state consumer Sample Payload json data id ws 7aiqKYf6ejMFdtWS type workspaces Sample Request shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 workspaces ws UYv6RYM8fVhzeGG5 relationships remote state consumers Response No response body Status code 204 Delete Remote State Consumers DELETE workspaces workspace id relationships remote state consumers Parameter Description workspace id The workspace ID to remove remote state consumers for Obtain this from the workspace settings terraform cloud docs workspaces settings or the Show Workspace show workspace endpoint This endpoint removes one or more remote state consumers from a workspace according to the contents of the payload It can only be used for workspaces where global remote state is false The workspaces specified as consumers must be readable to the API token that makes the request You can safely remove a consumer workspace that is already absent it will be ignored and the rest of the consumers in the request will be processed normally Status Response Reason s 204 No Content Successfully updated remote state consumers 404 JSON API error object Workspace not found or user unauthorized to perform action 422 JSON API error object Problem with payload or request details provided in the error object Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string Must be workspaces data id string The ID of a workspace to remove from the remote state consumers Sample Payload json data id ws 7aiqKYf6ejMFdtWS type workspaces Sample Request shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json request DELETE data payload json https app terraform io api v2 workspaces ws UYv6RYM8fVhzeGG5 relationships remote state consumers Response No response body Status code 204 Get tags Call the following endpoints to list the tags attached to a workspace GET workspaces workspace id relationships tags Lists flat string tags attached to the workspace GET workspaces workspace id tag bindings Lists key value tags directly bound to the workspace GET workspaces workspace id effective tag bindings Lists all key value tags bound to the workspace including those inherited from the parent project Path parameters Parameter Description workspace id The workspace ID to fetch tags for Obtain this from the workspace settings terraform cloud docs workspaces settings or the Show Workspace show workspace endpoint Query Parameters The flat string tags endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters Remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs Parameter Description page number Optional If omitted the endpoint will return the first page page size Optional If omitted the endpoint will return 20 workspaces per page Sample Requests CodeBlockConfig hideClipboard heading List flat string tags attached to the workspace shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 workspaces workspace 2 relationships tags CodeBlockConfig CodeBlockConfig hideClipboard heading List key value tags bound directly to the workspace shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 workspaces workspace 2 tag bindings CodeBlockConfig CodeBlockConfig hideClipboard heading List all key value tags bound to the workspace including those inherited from the parent project shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 workspaces workspace 2 effective tag bindings CodeBlockConfig Sample Responses CodeBlockConfig hideClipboard heading List flat string tags attached to the workspace json data id tag 1 type tags attributes name tag1 created at 2022 03 09T06 04 39 585Z instance count 1 relationships organization data id my organization type organizations id tag 2 type tags attributes name tag2 created at 2022 03 09T06 04 39 585Z instance count 2 relationships organization data id my organization type organizations CodeBlockConfig CodeBlockConfig hideClipboard heading List key value tags bound directly to the workspace json data id tb RKs9JSC2lInns32K type tag bindings attributes key ws1 key value ws1 value CodeBlockConfig CodeBlockConfig hideClipboard heading List all key value tags bound to the workspace including those inherited from the parent project json data type effective tag bindings attributes key ws1 key value ws1 value type effective tag bindings attributes key key1 value value1 type effective tag bindings attributes key key2 value value2 CodeBlockConfig Add flat string tags to a workspace POST workspaces workspace id relationships tags To add key value tags to an existing workspace call the PATCH workspaces workspace id and provide workspace tag bindings in the JSON payload Refer to Update a workspace update a workspace for additional information You can also bind key value tags when creating a workspace Refer to Create a workspace create a workspace for additional information Refer to Define project tags terraform cloud docs projects manage define project tags for information about supported tag values Parameter Description workspace id The workspace ID to add tags to Obtain this from the workspace settings terraform cloud docs workspaces settings or the Show Workspace show workspace endpoint Status Response Reason s 204 No Content Successfully added tags to workspace 404 JSON API error object Workspace not found or user unauthorized to perform action Request Body This POST endpoint requires a JSON object with the following properties as a request payload It is important to note that type as well as one of id or attributes name is required Key path Type Default Description data type string Must be tags data id string The ID of the tag to add data attributes name string The name of the tag to add Sample Payload json data type tags attributes name foo type tags attributes name bar Sample Request shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 workspaces workspace 2 relationships tags Sample Response No response body Status code 204 Remove tags from workspace This endpoint removes one or more tags from a workspace The workspace must already exist and tag element that supplies an id attribute must exist If the name attribute is used and no matching organization tag is found no action will occur for that entry Tags removed from all workspaces will be removed from the organization wide list To remove key value tags to an existing workspace call the PATCH workspaces workspace id and provide workspace tag bindings in the JSON payload Refer to Update a workspace update a workspace for additional information DELETE workspaces workspace id relationships tags Parameter Description workspace id The workspace ID to remove tags from Obtain this from the workspace settings terraform cloud docs workspaces settings or the Show Workspace show workspace endpoint Status Response Reason s 204 No Content Successfully removed tags to workspace 404 JSON API error object Workspace not found or user unauthorized to perform action Request Body This POST endpoint requires a JSON object with the following properties as a request payload It is important to note that type as well as one of id or attributes name is required Key path Type Default Description data type string Must be tags data id string The ID of the tag to remove data attributes name string The name of the tag to remove Sample Payload json data type tags id tag Yfha4YpPievQ8wJw Sample Request shell session curl header Authorization Bearer TOKEN header Content Type application vnd api json request DELETE data payload json https app terraform io api v2 workspaces workspace 2 relationships tags Sample Response No response body Status code 204 Show data retention policy EnterpriseAlert This endpoint is exclusive to Terraform Enterprise and is not available in HCP Terraform EnterpriseAlert GET workspaces workspace id relationships data retention policy Parameter Description workspace id The ID of the workspace to show the data retention policy for Obtain this from the workspace settings terraform enterprise workspaces settings or by sending a GET request to the workspaces show workspace endpoint This endpoint shows the data retention policy set explicitly on the workspace When no data retention policy is set for the workspace the endpoint returns the default policy configured for the organization Refer to Data Retention Policies terraform enterprise workspaces settings deletion data retention policies for instructions on configuring data retention policies for workspaces Refer to Data Retention Policy API terraform enterprise api docs data retention policies show data retention policy in the Terraform Enterprise documentation for details Create or update data retention policy EnterpriseAlert This endpoint is exclusive to Terraform Enterprise and is not available in HCP Terraform EnterpriseAlert POST workspaces workspace id relationships data retention policy Parameter Description workspace id The workspace ID to update the data retention policy for Obtain this from the workspace settings terraform enterprise workspaces settings or by sending a GET request to the workspaces show workspace endpoint This endpoint creates a data retention policy for a workspace or updates the existing policy Refer to Data Retention Policies terraform enterprise workspaces settings deletion data retention policies for additional information Refer to Data Retention Policy API terraform enterprise api docs data retention policies create or update data retention policy in the Terraform Enterprise documentation for details Remove data retention policy EnterpriseAlert This endpoint is exclusive to Terraform Enterprise and is not available in HCP Terraform EnterpriseAlert DELETE workspaces workspace id relationships data retention policy Parameter Description workspace id The workspace ID to remove the data retenetion policy for Obtain this from the workspace settings terraform enterprise workspaces settings or by sending a GET request to the workspaces show workspace endpoint This endpoint removes the data retention policy explicitly set on a workspace When no data retention policy is set for the workspace the endpoint returns the default policy configured for the organization Refer to Data Retention Policies terraform enterprise users teams organizations organizations destruction and deletion for instructions on configuring data retention policies for organizations Read more about workspace data retention policies terraform enterprise workspaces settings deletion data retention policies Refer to Data Retention Policy API terraform enterprise api docs data retention policies remove data retention policy in the Terraform Enterprise documentation for details Available Related Resources The GET endpoints above can optionally return related resources if requested with the include query parameter terraform cloud docs api docs inclusion of related resources The following resource types are available current configuration version The last configuration this workspace received excluding plan only configurations Terraform uses this configuration for new runs unless you provide a different one current configuration version ingress attributes The commit information for the current configuration version current run Additional information about the current run current run configuration version The configuration used in the current run current run configuration version ingress attributes The commit information used in the current run current run plan The plan used in the current run locked by The user team or run responsible for locking the workspace if the workspace is currently locked organization The full organization record outputs The outputs for the most recently applied run project The full project record readme The most recent workspace README md
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 page title Audit Trail Tokens API Docs HCP Terraform 201 https developer mozilla org en US docs Web HTTP Status 201 Use the authentication token endpoint with the token query param to manage audit trails API tokens Generate and delete audit trail tokens using the HTTP API tfc only true
--- page_title: Audit Trail Tokens - API Docs - HCP Terraform description: >- Use the `/authentication-token` endpoint with the `token` query param to manage audit trails API tokens. Generate and delete audit trail tokens using the HTTP API. tfc_only: true --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # Audit Trail Tokens API Audit trail tokens are used to authenticate integrations pulling audit trail data, for example, using the [HCP Terraform for Splunk](/terraform/cloud-docs/integrations/splunk) app. ## Generate a new token `POST /organizations/:organization_name/authentication-token?token=audit-trails` | Parameter | Description | | -------------------- | ----------------------------------------------------- | | `:organization_name` | The name of the organization to generate a token for. | Generates a new [audit trails token](/terraform/cloud-docs/users-teams-organizations/api-tokens#audit-trails-tokens), replacing any existing token. Only members of the owners team, the owners [team API token](/terraform/cloud-docs/users-teams-organizations/api-tokens#team-api-tokens), and the [organization API token](/terraform/cloud-docs/users-teams-organizations/api-tokens#organization-api-tokens) can access this endpoint. This endpoint returns the secret text of the new authentication token. You can only access this token when you create it and can not recover it later. [permissions-citation]: #intentionally-unused---keep-for-maintainers | Status | Response | Reason | | ------- | ------------------------------------------------------- | ------------------- | | [201][] | [JSON API document][] (`type: "authentication-tokens"`) | Success | | [404][] | [JSON API error object][] | User not authorized | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. | Key path | Type | Default | Description | | ----------------------------- | ------ | ------- | ----------------------------------------------------------------------------------------------------------------------- | | `data.type` | string | | Must be `"authentication-token"`. | | `data.attributes.expired-at` | string | `null` | The UTC date and time that the audit trails token expires, in ISO 8601 format. If omitted or set to `null` the token will never expire. | ### Sample Payload ```json { "data": { "type": "authentication-token", "attributes": { "expired-at": "2023-04-06T12:00:00.000Z" } } } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/organizations/my-organization/authentication-token?token=audit-trails ``` ### Sample Response ```json { "data": { "id": "4111756", "type": "authentication-tokens", "attributes": { "created-at": "2017-11-29T19:11:28.075Z", "last-used-at": null, "description": null, "token": "ZgqYdzuvlv8Iyg.atlasv1.6nV7t1OyFls341jo1xdZTP72fN0uu9VL55ozqzekfmToGFbhoFvvygIRy2mwVAXomOE", "expired-at": "2023-04-06T12:00:00.000Z" }, "relationships": { "created-by": { "data": { "id": "user-62goNpx1ThQf689e", "type": "users" } } } } } ``` ## Delete a token `DELETE /organizations/:organization/authentication-token?token=audit-trails` | Parameter | Description | | -------------------- | --------------------------------------------- | | `:organization_name` | Which organization's token should be deleted. | Only members of the owners team, the owners [team API token](/terraform/cloud-docs/users-teams-organizations/api-tokens#team-api-tokens), and the [organization API token](/terraform/cloud-docs/users-teams-organizations/api-tokens#organization-api-tokens) can access this endpoint. [permissions-citation]: #intentionally-unused---keep-for-maintainers | Status | Response | Reason | | ------- | ------------------------- | ------------------- | | [204][] | No Content | Success | | [404][] | [JSON API error object][] | User not authorized | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request DELETE \ https://app.terraform.io/api/v2/organizations/my-organization/authentication-token?token=audit-trails ```
terraform
page title Audit Trail Tokens API Docs HCP Terraform description Use the authentication token endpoint with the token query param to manage audit trails API tokens Generate and delete audit trail tokens using the HTTP API tfc only true 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects Audit Trail Tokens API Audit trail tokens are used to authenticate integrations pulling audit trail data for example using the HCP Terraform for Splunk terraform cloud docs integrations splunk app Generate a new token POST organizations organization name authentication token token audit trails Parameter Description organization name The name of the organization to generate a token for Generates a new audit trails token terraform cloud docs users teams organizations api tokens audit trails tokens replacing any existing token Only members of the owners team the owners team API token terraform cloud docs users teams organizations api tokens team api tokens and the organization API token terraform cloud docs users teams organizations api tokens organization api tokens can access this endpoint This endpoint returns the secret text of the new authentication token You can only access this token when you create it and can not recover it later permissions citation intentionally unused keep for maintainers Status Response Reason 201 JSON API document type authentication tokens Success 404 JSON API error object User not authorized Request Body This POST endpoint requires a JSON object with the following properties as a request payload Key path Type Default Description data type string Must be authentication token data attributes expired at string null The UTC date and time that the audit trails token expires in ISO 8601 format If omitted or set to null the token will never expire Sample Payload json data type authentication token attributes expired at 2023 04 06T12 00 00 000Z Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 organizations my organization authentication token token audit trails Sample Response json data id 4111756 type authentication tokens attributes created at 2017 11 29T19 11 28 075Z last used at null description null token ZgqYdzuvlv8Iyg atlasv1 6nV7t1OyFls341jo1xdZTP72fN0uu9VL55ozqzekfmToGFbhoFvvygIRy2mwVAXomOE expired at 2023 04 06T12 00 00 000Z relationships created by data id user 62goNpx1ThQf689e type users Delete a token DELETE organizations organization authentication token token audit trails Parameter Description organization name Which organization s token should be deleted Only members of the owners team the owners team API token terraform cloud docs users teams organizations api tokens team api tokens and the organization API token terraform cloud docs users teams organizations api tokens organization api tokens can access this endpoint permissions citation intentionally unused keep for maintainers Status Response Reason 204 No Content Success 404 JSON API error object User not authorized Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request DELETE https app terraform io api v2 organizations my organization authentication token token audit trails
terraform 307 https developer mozilla org en US docs Web HTTP Status 307 200 https developer mozilla org en US docs Web HTTP Status 200 page title Applies API Docs HCP Terraform Use the applies endpoint to show the results of a Terraform apply using the HTTP API
--- page_title: Applies - API Docs - HCP Terraform description: >- Use the `/applies` endpoint to show the results of a Terraform apply using the HTTP API. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [307]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/307 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # Applies API An apply represents the results of applying a Terraform Run's execution plan. ## Attributes ### Apply States You'll find the apply state in `data.attributes.status`, as one of the following values. | State | Description | | ------------------------- | ------------------------------------------------------------------------------ | | `pending` | The initial status of a apply once it has been created. | | `managed_queued`/`queued` | The apply has been queued, awaiting backend service capacity to run terraform. | | `running` | The apply is running. | | `errored` | The apply has errored. This is a final state. | | `canceled` | The apply has been canceled. This is a final state. | | `finished` | The apply has completed successfully. This is a final state. | | `unreachable` | The apply will not run. This is a final state. | ## Show an apply `GET /applies/:id` | Parameter | Description | | --------- | ---------------------------- | | `id` | The ID of the apply to show. | There is no endpoint to list applies. You can find the ID for an apply in the `relationships.apply` property of a run object. | Status | Response | Reason | | ------- | ----------------------------------------- | ------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "applies"`) | The request was successful | | [404][] | [JSON API error object][] | Apply not found, or user unauthorized to perform action | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/applies/apply-47MBvjwzBG8YKc2v ``` ### Sample Response ```json { "data": { "id": "apply-47MBvjwzBG8YKc2v", "type": "applies", "attributes": { "execution-details": { "mode": "remote", }, "status": "finished", "status-timestamps": { "queued-at": "2018-10-17T18:58:27+00:00", "started-at": "2018-10-17T18:58:29+00:00", "finished-at": "2018-10-17T18:58:37+00:00" }, "log-read-url": "https://archivist.terraform.io/v1/object/dmF1bHQ6djE6OFA1eEdlSFVHRSs4YUcwaW83a1dRRDA0U2E3T3FiWk1HM2NyQlNtcS9JS1hHN3dmTXJmaFhEYTlHdTF1ZlgxZ2wzVC9kVTlNcjRPOEJkK050VFI3U3dvS2ZuaUhFSGpVenJVUFYzSFVZQ1VZYno3T3UyYjdDRVRPRE5pbWJDVTIrNllQTENyTndYd1Y0ak1DL1dPVlN1VlNxKzYzbWlIcnJPa2dRRkJZZGtFeTNiaU84YlZ4QWs2QzlLY3VJb3lmWlIrajF4a1hYZTlsWnFYemRkL2pNOG9Zc0ZDakdVMCtURUE3dDNMODRsRnY4cWl1dUN5dUVuUzdnZzFwL3BNeHlwbXNXZWRrUDhXdzhGNnF4c3dqaXlZS29oL3FKakI5dm9uYU5ZKzAybnloREdnQ3J2Rk5WMlBJemZQTg", "resource-additions": 1, "resource-changes": 0, "resource-destructions": 0, "resource-imports": 0 }, "relationships": { "state-versions": { "data": [ { "id": "sv-TpnsuD3iewwsfeRD", "type": "state-versions" }, { "id": "sv-Fu1n6a3TgJ1Typq9", "type": "state-versions" } ] } }, "links": { "self": "/api/v2/applies/apply-47MBvjwzBG8YKc2v" } } } ``` _Using HCP Terraform agents_ [HCP Terraform agents](/terraform/cloud-docs/api-docs/agents) allow HCP Terraform to communicate with isolated, private, or on-premises infrastructure. When a workspace is set to use the agent execution mode, the apply response will include additional details about the agent pool and agent used. ```json { "data": { "id": "apply-47MBvjwzBG8YKc2v", "type": "applies", "attributes": { "execution-details": { "agent-id": "agent-S1Y7tcKxXPJDQAvq", "agent-name": "agent_01", "agent-pool-id": "apool-Zigq2VGreKq7nwph", "agent-pool-name": "first-pool", "mode": "agent", }, "status": "finished", "status-timestamps": { "queued-at": "2018-10-17T18:58:27+00:00", "started-at": "2018-10-17T18:58:29+00:00", "finished-at": "2018-10-17T18:58:37+00:00" }, "log-read-url": "https://archivist.terraform.io/v1/object/dmF1bHQ6djE6OFA1eEdlSFVHRSs4YUcwaW83a1dRRDA0U2E3T3FiWk1HM2NyQlNtcS9JS1hHN3dmTXJmaFhEYTlHdTF1ZlgxZ2wzVC9kVTlNcjRPOEJkK050VFI3U3dvS2ZuaUhFSGpVenJVUFYzSFVZQ1VZYno3T3UyYjdDRVRPRE5pbWJDVTIrNllQTENyTndYd1Y0ak1DL1dPVlN1VlNxKzYzbWlIcnJPa2dRRkJZZGtFeTNiaU84YlZ4QWs2QzlLY3VJb3lmWlIrajF4a1hYZTlsWnFYemRkL2pNOG9Zc0ZDakdVMCtURUE3dDNMODRsRnY4cWl1dUN5dUVuUzdnZzFwL3BNeHlwbXNXZWRrUDhXdzhGNnF4c3dqaXlZS29oL3FKakI5dm9uYU5ZKzAybnloREdnQ3J2Rk5WMlBJemZQTg", "resource-additions": 1, "resource-changes": 0, "resource-destructions": 0, "resource-imports": 0 }, "relationships": { "state-versions": { "data": [ { "id": "sv-TpnsuD3iewwsfeRD", "type": "state-versions" }, { "id": "sv-Fu1n6a3TgJ1Typq9", "type": "state-versions" } ] } }, "links": { "self": "/api/v2/applies/apply-47MBvjwzBG8YKc2v" } } } ``` ## Recover a failed state upload after applying `GET /applies/:id/errored-state` | Parameter | Description | | --------- | ----------------------------------------- | | `id` | The ID of the apply to recover state for. | It is possible that during the course of a Run, Terraform may fail to upload a state file. This can happen for a variety of reasons, but should be an exceptionally rare occurrence. HCP Terraform agent versions greater than 1.12.0 include a fallback mechanism which attempts to upload the state directly to HCP Terraform's backend storage system in these cases. This endpoint then makes the raw data from these failed uploads available to users who are authorized to read the state contents. | Status | Response | Reason | | ------- | -------------------------------------------- | ----------------------------------------------------------------------------------- | | [307][] | HTTP temporary redirect to state storage URL | Errored state available and user is authorized to read it | | [404][] | [JSON API error object][] | Apply not found, errored state not uploaded, or user unauthorized to perform action | When a 307 redirect is returned, the storage URL to the raw state file will be present in the `Location` header of the response. The URL in the `Location` header will expire after one minute. It is recommended for the API client to follow the redirect immediately. Each successful request to the errored-state endpoint will generate a new, unique storage URL with the same one minute expiration window. ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ https://app.terraform.io/api/v2/applies/apply-47MBvjwzBG8YKc2v/errored-state ``` ### Sample Response ``` HTTP/1.1 307 Temporary Redirect Content-Length: 22 Content-Type: text/plain Location: https://archivist.terraform.io/v1/object/dmF1bHQ6djE6OFA1eEdlSFVHRSs4YUcwaW83a1dRRDA0U2E3T3FiWk1HM2NyQlNtcS9JS1hHN3dmTXJmaFhEYTlHdTF1ZlgxZ2wzVC9kVTlNcjRPOEJkK050VFI3U3dvS2ZuaUhFSGpVenJVUFYzSFVZQ1VZYno3T3UyYjdDRVRPRE5pbWJDVTIrNllQTENyTndYd1Y0ak1DL1dPVlN1VlNxKzYzbWlIcnJPa2dRRkJZZGtFeTNiaU84YlZ4QWs2QzlLY3VJb3lmWlIrajF4a1hYZTlsWnFYemRkL2pNOG9Zc0ZDakdVMCtURUE3dDNMODRsRnY4cWl1dUN5dUVuUzdnZzFwL3BNeHlwbXNXZWRrUDhXdzhGNnF4c3dqaXlZS29oL3FKakI5dm9uYU5ZKzAybnloREdnQ3J2Rk5WMlBJemZQTg 307 Temporary Redirect ```
terraform
page title Applies API Docs HCP Terraform description Use the applies endpoint to show the results of a Terraform apply using the HTTP API 200 https developer mozilla org en US docs Web HTTP Status 200 307 https developer mozilla org en US docs Web HTTP Status 307 404 https developer mozilla org en US docs Web HTTP Status 404 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects Applies API An apply represents the results of applying a Terraform Run s execution plan Attributes Apply States You ll find the apply state in data attributes status as one of the following values State Description pending The initial status of a apply once it has been created managed queued queued The apply has been queued awaiting backend service capacity to run terraform running The apply is running errored The apply has errored This is a final state canceled The apply has been canceled This is a final state finished The apply has completed successfully This is a final state unreachable The apply will not run This is a final state Show an apply GET applies id Parameter Description id The ID of the apply to show There is no endpoint to list applies You can find the ID for an apply in the relationships apply property of a run object Status Response Reason 200 JSON API document type applies The request was successful 404 JSON API error object Apply not found or user unauthorized to perform action Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 applies apply 47MBvjwzBG8YKc2v Sample Response json data id apply 47MBvjwzBG8YKc2v type applies attributes execution details mode remote status finished status timestamps queued at 2018 10 17T18 58 27 00 00 started at 2018 10 17T18 58 29 00 00 finished at 2018 10 17T18 58 37 00 00 log read url https archivist terraform io v1 object dmF1bHQ6djE6OFA1eEdlSFVHRSs4YUcwaW83a1dRRDA0U2E3T3FiWk1HM2NyQlNtcS9JS1hHN3dmTXJmaFhEYTlHdTF1ZlgxZ2wzVC9kVTlNcjRPOEJkK050VFI3U3dvS2ZuaUhFSGpVenJVUFYzSFVZQ1VZYno3T3UyYjdDRVRPRE5pbWJDVTIrNllQTENyTndYd1Y0ak1DL1dPVlN1VlNxKzYzbWlIcnJPa2dRRkJZZGtFeTNiaU84YlZ4QWs2QzlLY3VJb3lmWlIrajF4a1hYZTlsWnFYemRkL2pNOG9Zc0ZDakdVMCtURUE3dDNMODRsRnY4cWl1dUN5dUVuUzdnZzFwL3BNeHlwbXNXZWRrUDhXdzhGNnF4c3dqaXlZS29oL3FKakI5dm9uYU5ZKzAybnloREdnQ3J2Rk5WMlBJemZQTg resource additions 1 resource changes 0 resource destructions 0 resource imports 0 relationships state versions data id sv TpnsuD3iewwsfeRD type state versions id sv Fu1n6a3TgJ1Typq9 type state versions links self api v2 applies apply 47MBvjwzBG8YKc2v Using HCP Terraform agents HCP Terraform agents terraform cloud docs api docs agents allow HCP Terraform to communicate with isolated private or on premises infrastructure When a workspace is set to use the agent execution mode the apply response will include additional details about the agent pool and agent used json data id apply 47MBvjwzBG8YKc2v type applies attributes execution details agent id agent S1Y7tcKxXPJDQAvq agent name agent 01 agent pool id apool Zigq2VGreKq7nwph agent pool name first pool mode agent status finished status timestamps queued at 2018 10 17T18 58 27 00 00 started at 2018 10 17T18 58 29 00 00 finished at 2018 10 17T18 58 37 00 00 log read url https archivist terraform io v1 object dmF1bHQ6djE6OFA1eEdlSFVHRSs4YUcwaW83a1dRRDA0U2E3T3FiWk1HM2NyQlNtcS9JS1hHN3dmTXJmaFhEYTlHdTF1ZlgxZ2wzVC9kVTlNcjRPOEJkK050VFI3U3dvS2ZuaUhFSGpVenJVUFYzSFVZQ1VZYno3T3UyYjdDRVRPRE5pbWJDVTIrNllQTENyTndYd1Y0ak1DL1dPVlN1VlNxKzYzbWlIcnJPa2dRRkJZZGtFeTNiaU84YlZ4QWs2QzlLY3VJb3lmWlIrajF4a1hYZTlsWnFYemRkL2pNOG9Zc0ZDakdVMCtURUE3dDNMODRsRnY4cWl1dUN5dUVuUzdnZzFwL3BNeHlwbXNXZWRrUDhXdzhGNnF4c3dqaXlZS29oL3FKakI5dm9uYU5ZKzAybnloREdnQ3J2Rk5WMlBJemZQTg resource additions 1 resource changes 0 resource destructions 0 resource imports 0 relationships state versions data id sv TpnsuD3iewwsfeRD type state versions id sv Fu1n6a3TgJ1Typq9 type state versions links self api v2 applies apply 47MBvjwzBG8YKc2v Recover a failed state upload after applying GET applies id errored state Parameter Description id The ID of the apply to recover state for It is possible that during the course of a Run Terraform may fail to upload a state file This can happen for a variety of reasons but should be an exceptionally rare occurrence HCP Terraform agent versions greater than 1 12 0 include a fallback mechanism which attempts to upload the state directly to HCP Terraform s backend storage system in these cases This endpoint then makes the raw data from these failed uploads available to users who are authorized to read the state contents Status Response Reason 307 HTTP temporary redirect to state storage URL Errored state available and user is authorized to read it 404 JSON API error object Apply not found errored state not uploaded or user unauthorized to perform action When a 307 redirect is returned the storage URL to the raw state file will be present in the Location header of the response The URL in the Location header will expire after one minute It is recommended for the API client to follow the redirect immediately Each successful request to the errored state endpoint will generate a new unique storage URL with the same one minute expiration window Sample Request shell curl header Authorization Bearer TOKEN https app terraform io api v2 applies apply 47MBvjwzBG8YKc2v errored state Sample Response HTTP 1 1 307 Temporary Redirect Content Length 22 Content Type text plain Location https archivist terraform io v1 object dmF1bHQ6djE6OFA1eEdlSFVHRSs4YUcwaW83a1dRRDA0U2E3T3FiWk1HM2NyQlNtcS9JS1hHN3dmTXJmaFhEYTlHdTF1ZlgxZ2wzVC9kVTlNcjRPOEJkK050VFI3U3dvS2ZuaUhFSGpVenJVUFYzSFVZQ1VZYno3T3UyYjdDRVRPRE5pbWJDVTIrNllQTENyTndYd1Y0ak1DL1dPVlN1VlNxKzYzbWlIcnJPa2dRRkJZZGtFeTNiaU84YlZ4QWs2QzlLY3VJb3lmWlIrajF4a1hYZTlsWnFYemRkL2pNOG9Zc0ZDakdVMCtURUE3dDNMODRsRnY4cWl1dUN5dUVuUzdnZzFwL3BNeHlwbXNXZWRrUDhXdzhGNnF4c3dqaXlZS29oL3FKakI5dm9uYU5ZKzAybnloREdnQ3J2Rk5WMlBJemZQTg 307 Temporary Redirect
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 page title Change Requests API Docs HCP Terraform Use the change requests endpoint to view and archive change requests on given workspace
--- page_title: Change Requests - API Docs - HCP Terraform description: >- Use the `/change_requests` endpoint to view and archive change requests on given workspace. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # Change requests API -> **Note**: Change requests are in public beta. All APIs and workflows are subject to change. You can use change requests to keep track of workspace to-dos directly on that workspace. Change requests are a backlog of the changes that a workspace requires, often to ensure that workspace keeps up with compliance and best practices of your company. Change requests can also trigger [team notifications](/terraform/cloud-docs/users-teams-organizations/teams/notifications) to directly notify team members whenever someone creates a new change request. @include 'tfc-package-callouts/change-requests.mdx' ## List change requests Use this endpoint to list a workspace's change requests. `GET api/v2/workspaces/:workspace_name/change-requests` | Parameter | Description | | ----------------------- | ------------------------ | | `:workspace_name` | The name of workspace you want to list the change requests of. | ### Query parameters This endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. | Parameter | Description | | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `page[number]` | **Optional.** If omitted, the endpoint will return the first page. | | `page[size]` | **Optional.** If omitted, the endpoint will return 20 teams per page. | ### Sample request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/workspaces/:workspace_name/change-requests ``` ### Sample response ```json { "data": [{ "type": "workspace_change_requests", "id": "wscr-yjLcKUMFTs6kr9iC" "attributes": { "subject": "[Action Required] Github Actions Pinning (SEC-090)", "message": "Some long description here", "archived-by": null, "archived-at": null, "created-at": "2024-06-12T21:45:11.594Z", "updated-at": "2024-06-12T21:45:11.594Z" }, "relationships": { "workspace" : { "data": { "id": "ws-FTs6kr9iCwweku", "type": "workspaces" } } } }, { "type": "workspace_change_requests", "id": "wscr-jXQMBkPAFGD6eyFs", "attributes": { "subject": "[Action Required] Github Actions Pinning (SEC-100)", "message": "Some long description here", "archived-by": null, "archived-at": null, "created-at": "2024-06-12T21:45:11.594Z", "updated-at": "2024-06-12T21:45:11.594Z" }, "relationships": { "workspace" : { "data": { "id": "ws-FTs6kr9iCwweku", "type": "workspaces" } } } }], "links": { "self": "https://localhost/api/v2/workspaces/example-workspace-name/change-requests?page%5Bnumber%5D=1\u0026page%5Bsize%5D=20", "first": "https://localhost/api/v2/workspaces/example-workspace-name/change-requests?page%5Bnumber%5D=1\u0026page%5Bsize%5D=20", "prev": null, "next": null, "last": "https://localhost/api/v2/workspaces/example-workspace-name/change-requests?page%5Bnumber%5D=1\u0026page%5Bsize%5D=20" }, "meta": { "pagination": { "current-page": 1, "page-size": 20, "prev-page": null, "next-page": null, "total-pages": 1, "total-count": 1 } } } ``` ## Show a change request Use this endpoint to list the details of a specific change request. `GET api/v2/workspaces/change-requests/:change_request_id` | Parameter | Description | | ----------------------- | ------------------------ | | `:change_request_id` | The change request ID | ### Sample request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/change-requests/wscr-jXQMBkPAFGD6eyFs ``` ### Sample response ```json { "data": { "type": "workspace_change_requests", "id": "wscr-jXQMBkPAFGD6eyFs", "attributes": { "subject": "[Action Required] Github Actions Pinning (SEC-100)", "message": "Some long description here", "archived-by": null, "archived-at": null, "created-at": "2024-06-12T21:45:11.594Z", "updated-at": "2024-06-12T21:45:11.594Z" }, "relationships": { "workspace" : { "data": { "id": "ws-FTs6kr9iCwweku", "type": "workspaces" } } } } } ``` ## Archive change request If someone completes a change request, they can archive it to reflect the request's completion. You can still view archived change requests, however they are be sorted separated and marked as `"archived"`. `POST api/v2/workspaces/change-requests/:change_request_id` | Parameter | Description | | ----------------------- | ------------------------ | | `:change_request_id` | The ID of the change request to archive. | ### Sample request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request PATCH \ https://app.terraform.io/api/v2/workspaces/change-requests/wscr-jXQMBkPAFGD6eyFs` ``` ### Sample response ```json { "data": { "type": "workspace_change_requests", "id": "wscr-jXQMBkPAFGD6eyFs", "attributes": { "subject": "[Action Required] Github Actions Pinning (SEC-100)", "message": "Some long description here", "archived-by": "user-2n4yj45149kf", "archived-at": "2024-08-12T10:12:44.745Z", "created-at": "2024-06-12T21:45:11.594Z", "updated-at": "2024-06-12T21:45:11.594Z" }, "relationships": { "workspace" : { "data": { "id": "ws-FTs6kr9iCwweku", "type": "workspaces" } } } } } ``` ## Create new change request You can make change requests through the [explorer's](/terraform/cloud-docs/api-docs/explorer) experimental `"bulk actions"` endpoint. `POST /api/v2/organizations/:organization_name/explorer/bulk-actions` | Parameter | Description | | ----------------------- | ------------------------ | | `:organization_id` | The ID of the organization you want to create a change request in. | You must specify the following fields in your payload when creating a new change request. | Key path | Type | Required | Description | |------------|------|---------|-------------| | `data.action_type` | string | Required | The action to take. To create a change request, specify `"change_request"`. | | `data.action_inputs` | object | Required | Arguments for the bulk action. | | `data.action_inputs.subject` | string | Required | The change request's subject line. | `data.action_inputs.message` | string | Required | The change request's message, which HCP Terraform treats as markdown. | | `data.target_ids` | array | Optional | The IDs of the workspace you want to associate with this change request. You do not need to specify this field if you provide `data.query`. | | `data.query` | object | Optional | An [explorer query](/terraform/cloud-docs/api-docs/explorer#execute-a-query) with workspace data. You do not need to specify this field if you provide `data.target_ids`. | ### Sample Payload ```json { "data": { "type": "bulk_actions", "attributes": { "action_type": "change_requests", "action_inputs": { "subject": "[Action Required] Github Actions Pinning (SEC-090)", "message": "Some long description here", }, "query": { "type": "workspaces", "filter": [ "field": "workspace_name", "operator": "contains", "value": ["dev"] ] } }, } ``` ### Sample request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/organizations/:organization_name/explorer/bulk-actions ``` ### Sample response ```json { "data": { "id": "eba-3jk34n5k2bs", "attributes": { "organization_id": "org-9mvjfwpq098", "action_type": "change_requests", "action_inputs": { "subject": "[Action Required] Github Actions Pinning (SEC-090)", "message": "Some long description here", }, "created_by": { "id": "user-n86dcbcrwtw9", "type": "users" } }, "type": "explorer_bulk_actions", } } ```
terraform
page title Change Requests API Docs HCP Terraform description Use the change requests endpoint to view and archive change requests on given workspace 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects Change requests API Note Change requests are in public beta All APIs and workflows are subject to change You can use change requests to keep track of workspace to dos directly on that workspace Change requests are a backlog of the changes that a workspace requires often to ensure that workspace keeps up with compliance and best practices of your company Change requests can also trigger team notifications terraform cloud docs users teams organizations teams notifications to directly notify team members whenever someone creates a new change request include tfc package callouts change requests mdx List change requests Use this endpoint to list a workspace s change requests GET api v2 workspaces workspace name change requests Parameter Description workspace name The name of workspace you want to list the change requests of Query parameters This endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters Remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs Parameter Description page number Optional If omitted the endpoint will return the first page page size Optional If omitted the endpoint will return 20 teams per page Sample request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 workspaces workspace name change requests Sample response json data type workspace change requests id wscr yjLcKUMFTs6kr9iC attributes subject Action Required Github Actions Pinning SEC 090 message Some long description here archived by null archived at null created at 2024 06 12T21 45 11 594Z updated at 2024 06 12T21 45 11 594Z relationships workspace data id ws FTs6kr9iCwweku type workspaces type workspace change requests id wscr jXQMBkPAFGD6eyFs attributes subject Action Required Github Actions Pinning SEC 100 message Some long description here archived by null archived at null created at 2024 06 12T21 45 11 594Z updated at 2024 06 12T21 45 11 594Z relationships workspace data id ws FTs6kr9iCwweku type workspaces links self https localhost api v2 workspaces example workspace name change requests page 5Bnumber 5D 1 u0026page 5Bsize 5D 20 first https localhost api v2 workspaces example workspace name change requests page 5Bnumber 5D 1 u0026page 5Bsize 5D 20 prev null next null last https localhost api v2 workspaces example workspace name change requests page 5Bnumber 5D 1 u0026page 5Bsize 5D 20 meta pagination current page 1 page size 20 prev page null next page null total pages 1 total count 1 Show a change request Use this endpoint to list the details of a specific change request GET api v2 workspaces change requests change request id Parameter Description change request id The change request ID Sample request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 change requests wscr jXQMBkPAFGD6eyFs Sample response json data type workspace change requests id wscr jXQMBkPAFGD6eyFs attributes subject Action Required Github Actions Pinning SEC 100 message Some long description here archived by null archived at null created at 2024 06 12T21 45 11 594Z updated at 2024 06 12T21 45 11 594Z relationships workspace data id ws FTs6kr9iCwweku type workspaces Archive change request If someone completes a change request they can archive it to reflect the request s completion You can still view archived change requests however they are be sorted separated and marked as archived POST api v2 workspaces change requests change request id Parameter Description change request id The ID of the change request to archive Sample request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request PATCH https app terraform io api v2 workspaces change requests wscr jXQMBkPAFGD6eyFs Sample response json data type workspace change requests id wscr jXQMBkPAFGD6eyFs attributes subject Action Required Github Actions Pinning SEC 100 message Some long description here archived by user 2n4yj45149kf archived at 2024 08 12T10 12 44 745Z created at 2024 06 12T21 45 11 594Z updated at 2024 06 12T21 45 11 594Z relationships workspace data id ws FTs6kr9iCwweku type workspaces Create new change request You can make change requests through the explorer s terraform cloud docs api docs explorer experimental bulk actions endpoint POST api v2 organizations organization name explorer bulk actions Parameter Description organization id The ID of the organization you want to create a change request in You must specify the following fields in your payload when creating a new change request Key path Type Required Description data action type string Required The action to take To create a change request specify change request data action inputs object Required Arguments for the bulk action data action inputs subject string Required The change request s subject line data action inputs message string Required The change request s message which HCP Terraform treats as markdown data target ids array Optional The IDs of the workspace you want to associate with this change request You do not need to specify this field if you provide data query data query object Optional An explorer query terraform cloud docs api docs explorer execute a query with workspace data You do not need to specify this field if you provide data target ids Sample Payload json data type bulk actions attributes action type change requests action inputs subject Action Required Github Actions Pinning SEC 090 message Some long description here query type workspaces filter field workspace name operator contains value dev Sample request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 organizations organization name explorer bulk actions Sample response json data id eba 3jk34n5k2bs attributes organization id org 9mvjfwpq098 action type change requests action inputs subject Action Required Github Actions Pinning SEC 090 message Some long description here created by id user n86dcbcrwtw9 type users type explorer bulk actions
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 page title Policy Sets API Docs HCP Terraform Use the policy sets endpoint to manage groups of Sentinel and OPA policies List show create and update policy sets and policy set versions Attach detach and exclude policies from workspaces or attach and detach policies to projects
--- page_title: Policy Sets - API Docs - HCP Terraform description: >- Use the `/policy-sets` endpoint to manage groups of Sentinel and OPA policies. List, show, create, and update policy sets and policy set versions. Attach, detach, and exclude policies from workspaces, or attach and detach policies to projects. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # Policy sets API [Policy Enforcement](/terraform/cloud-docs/policy-enforcement) lets you use the policy-as-code frameworks Sentinel and Open Policy Agent (OPA) to apply policy checks to HCP Terraform workspaces. [Policy sets](/terraform/cloud-docs/policy-enforcement/manage-policy-sets) are collections of policies that you can apply globally or to specific [projects](/terraform/cloud-docs/projects/manage) and workspaces. For each run in the selected workspaces, HCP Terraform checks the Terraform plan against the policy set. <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/policies.mdx' <!-- END: TFC:only name:pnp-callout --> This API provides endpoints to create, read, update, and delete policy sets in an HCP Terraform organization. To view and manage individual policies, use the [Policies API](/terraform/cloud-docs/api-docs/policies). Many of these endpoints let you create policy sets from a designated repository in a Version Control System (VCS). For more information about how to configure a policy set VCS repository, refer to [Sentinel Policy Set VCS Repositories](/terraform/cloud-docs/policy-enforcement/sentinel/vcs) and [OPA Policy Set VCS Repositories](/terraform/cloud-docs/policy-enforcement/opa/vcs). Instead of connecting HCP Terraform to a VCS repository, you can use the the [Policy Set Versions endpoint](#create-a-policy-set-version) to create an entire policy set from a `tar.gz` file. Interacting with policy sets requires permission to manage policies. ([More about permissions](/terraform/cloud-docs/users-teams-organizations/permissions).) [permissions-citation]: #intentionally-unused---keep-for-maintainers ## Create a policy set `POST /organizations/:organization_name/policy-sets` | Parameter | Description | | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `:organization_name` | The organization to create the policy set in. The organization must already exist in the system, and the token authenticating the API request must have permission to manage policies. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) | [permissions-citation]: #intentionally-unused---keep-for-maintainers | Status | Response | Reason | | ------- | --------------------------------------------- | -------------------------------------------------------------- | | [201][] | [JSON API document][] (`type: "policy-sets"`) | Successfully created a policy set | | [404][] | [JSON API error object][] | Organization not found, or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (missing attributes, wrong types, etc.) | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | ----------------------------------------------------- | -------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data.type` | string | | Must be `"policy-sets"`. | | `data.attributes.name` | string | | The name of the policy set. Can include letters, numbers, `-`, and `_`. | | `data.attributes.description` | string | `null` | Text describing the policy set's purpose. This field supports Markdown and appears in the HCP Terraform UI. | | `data.attributes.global` | boolean | `false` | Whether HCP Terraform should automatically apply this policy set to all of an organization's workspaces. | | `data.attributes.kind` | string | `sentinel` | The policy-as-code framework associated with the policy. Valid values are `sentinel` and `opa`. | | `data.attributes.overridable` | boolean | `false` | Whether or not users can override this policy when it fails during a run. Valid for sentinel policies only if `agent-enabled` is set to `true`. | | `data.attributes.vcs-repo` | object | `null` | VCS repository information. When present, HCP Terraform sources the policies and configuration from the specified VCS repository. This attribute and `policies` relationships are mutually exclusive, and you cannot use them simultaneously. | | `data.attributes.vcs-repo.branch` | string | `null` | The branch of the VCS repository where HCP Terraform should retrieve the policy set. If empty, HCP Terraform uses the default branch. | | `data.attributes.vcs-repo.identifier` | string | | The VCS repository identifier in the format `<namespace>/<repo>`. For example, `hashicorp/my-policy-set`. The format for Azure DevOps is `<org>/<project>/_git/<repo>`. | | `data.attributes.vcs-repo.oauth-token-id` | string | | The OAuth Token ID HCP Terraform should use to connect to the VCS host. This value must not be specified if `github-app-installation-id` is specified. | | `data.attributes.vcs-repo.github-app-installation-id` | string | | The VCS Connection GitHub App Installation to use. Find this ID on the account settings page. Requires previously authorizing the GitHub App and generating a user-to-server token. Manage the token from **Account Settings** within HCP Terraform. You can not specify this value if `oauth-token-id` is specified. | | `data.attributes.vcs-repo.ingress-submodules` | boolean | `false` | Whether HCP Terraform should instantiate repository submodules when retrieving the policy set. | | `data.attributes.policies-path` | string | `null` | The VCS repository subdirectory that contains the policies for this policy set. HCP Terraform ignores files and directories outside of this sub-path and does not update the policy set when those files change. This attribute is only valid when you specify a VCS repository for the policy set. | | `data.relationships.projects.data[]` | array\[object] | `[]` | A list of resource identifier objects that defines which projects are associated with the policy set. These objects must contain `id` and `type` properties, and the `type` property must be `projects`. For example, `{ "id": "prj-AwfuCJTkdai4xj9w", "type": "projects" }`. You can only specify this attribute when `data.attributes.global` is `false`. | | `data.relationships.workspaces.data[]` | array\[object] | `[]` | A list of resource identifier objects that defines which workspaces are associated with the policy set. These objects must contain `id` and `type` properties, and the `type` property must be `workspaces`. For example, `{ "id": "ws-2HRvNs49EWPjDqT1", "type": "workspaces" }`. Obtain workspace IDs from the [workspace's settings page](/terraform/enterprise/workspaces/settings) or the [Show Workspace endpoint](/terraform/enterprise/api-docs/workspaces#show-workspace). You can only specify this attribute when `data.attributes.global` is `false`.| | `data.relationships.workspace-exclusions.data[]` | array\[object] | `[]` | A list of resource identifier objects specifying which workspaces HCP Terraform excludes from a policy set's enforcement. These objects must contain `id` and `type` properties, and the `type` property must be `workspaces`. For example, `{ "id": "ws-FVVvzCDaykN1oHiw", "type": "workspaces" }`. | | `data.relationships.policies.data[]` | array\[object] | `[]` | A list of resource identifier objects that defines which policies are members of the policy set. These objects must contain `id` and `type` properties, and the `type` property must be `policies`. For example, `{ "id": "pol-u3S5p2Uwk21keu1s", "type": "policies" }`. | | `data.attributes.agent-enabled` **(beta)** | boolean | `false` | Only valid for `sentinel` policy sets. Whether this policy set should run as a policy evaluation in the HCP Terraform agent. | | `data.attributes.policy-tool-version` **(beta)** | string | `latest` | The version of the tool that HCP Terraform uses to evaluate policies. You can only set a policy tool version for 'sentinel' policy sets if `agent-enabled` is `true`. | ### Sample Payload ```json { "data": { "type": "policy-sets", "attributes": { "name": "production", "description": "This set contains policies that should be checked on all production infrastructure workspaces.", "global": false, "kind": "sentinel", "agent-enabled": true, "policy-tool-version": "0.23.0", "overridable": true, "policies-path": "/policy-sets/foo", "vcs-repo": { "branch": "main", "identifier": "hashicorp/my-policy-sets", "ingress-submodules": false, "oauth-token-id": "ot-7Fr9d83jWsi8u23A" } }, "relationships": { "projects": { "data": [ { "id": "prj-AwfuCJTkdai4xj9w", "type": "projects" } ] }, "workspaces": { "data": [ { "id": "ws-2HRvNs49EWPjDqT1", "type": "workspaces" } ] }, "workspace-exclusions": { "data": [ { "id": "ws-FVVvzCDaykN1oHiw", "type": "workspaces" } ] } } } } ``` ### Sample payload with individual policy relationships ```json { "data": { "type": "policy-sets", "attributes": { "name": "production", "description": "This set contains policies that should be checked on all production infrastructure workspaces.", "kind": "sentinel", "global": false, "agent-enabled": true, "policy-tool-version": "0.23.0", "overridable": true }, "relationships": { "policies": { "data": [ { "id": "pol-u3S5p2Uwk21keu1s", "type": "policies" } ] }, "workspaces": { "data": [ { "id": "ws-2HRvNs49EWPjDqT1", "type": "workspaces" } ] } } } } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/organizations/my-organization/policy-sets ``` ### Sample Response ```json { "data": { "id":"polset-3yVQZvHzf5j3WRJ1", "type":"policy-sets", "attributes": { "name": "production", "description": "This set contains policies that should be checked on all production infrastructure workspaces.", "kind": "sentinel", "global": false, "agent-enabled": true, "policy-tool-version": "0.23.0", "overridable": true, "workspace-count": 1, "policies-path": "/policy-sets/foo", "versioned": true, "vcs-repo": { "branch": "main", "identifier": "hashicorp/my-policy-sets", "ingress-submodules": false, "oauth-token-id": "ot-7Fr9d83jWsi8u23A" }, "created-at": "2018-09-11T18:21:21.784Z", "updated-at": "2018-09-11T18:21:21.784Z" }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" } }, "projects": { "data": [ { "id": "prj-AwfuCJTkdai4xj9w", "type": "projects" } ] }, "workspaces": { "data": [ { "id": "ws-2HRvNs49EWPjDqT1", "type": "workspaces" } ] }, "workspace-exclusions": { "data": [ { "id": "ws-FVVvzCDaykN1oHiw", "type": "workspaces" } ] }, }, "links": { "self":"/api/v2/policy-sets/polset-3yVQZvHzf5j3WRJ1" } } } ``` ### Sample response with individual policy relationships ```json { "data": { "id":"polset-3yVQZvHzf5j3WRJ1", "type":"policy-sets", "attributes": { "name": "production", "description": "This set contains policies that should be checked on all production infrastructure workspaces.", "kind": "sentinel", "global": false, "agent-enabled": true, "policy-tool-version": "0.23.0", "overridable": true, "policy-count": 1, "workspace-count": 1, "versioned": false, "created-at": "2018-09-11T18:21:21.784Z", "updated-at": "2018-09-11T18:21:21.784Z" }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" } }, "policies": { "data": [ { "id": "pol-u3S5p2Uwk21keu1s", "type": "policies" } ] }, "workspaces": { "data": [ { "id": "ws-2HRvNs49EWPjDqT1", "type": "workspaces" } ] } }, "links": { "self":"/api/v2/policy-sets/polset-3yVQZvHzf5j3WRJ1" } } } ``` ## List policy sets `GET /organizations/:organization_name/policy-sets` | Parameter | Description | | -------------------- | ----------------------------------------- | | `:organization_name` | The organization to list policy sets for. | | Status | Response | Reason | | ------- | --------------------------------------------- | -------------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "policy-sets"`) | Request was successful | | [404][] | [JSON API error object][] | Organization not found, or user unauthorized to perform action | ### Query Parameters This endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters); remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. | Parameter | Description | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `filter[versioned]` | **Optional.** Allows filtering policy sets based on whether they are versioned (VCS-managed or API-managed), or use individual policy relationships. Accepts a boolean true/false value. A `true` value returns versioned sets, and a `false` value returns sets with individual policy relationships. If omitted, all policy sets are returned. | | `filter[kind]` | **Optional.** If specified, restricts results to those with the matching policy kind value. Valid values are `sentinel` and `opa`. | | `include` | **Optional.** Enables you to include related resource data. Value must be a comma-separated list containing one or more of `projects`, `workspaces`, `workspace-exclusions`, `policies`, `newest_version`, or `current_version`. See the [relationships section](#relationships) for details. | | `page[number]` | **Optional.** If omitted, the endpoint will return the first page. | | `page[size]` | **Optional.** If omitted, the endpoint will return 20 policy sets per page. | | `search[name]` | **Optional.** Allows searching the organization's policy sets by name. | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ https://app.terraform.io/api/v2/organizations/my-organization/policy-sets ``` ### Sample Response ```json { "data": [ { "id":"polset-3yVQZvHzf5j3WRJ1", "type":"policy-sets", "attributes": { "name": "production", "description": "This set contains policies that should be checked on all production infrastructure workspaces.", "kind": "sentinel", "global": false, "agent-enabled": true, "policy-tool-version": "0.23.0", "overridable": true, "workspace-count": 1, "policies-path": "/policy-sets/foo", "versioned": true, "vcs-repo": { "branch": "main", "identifier": "hashicorp/my-policy-sets", "ingress-submodules": false, "oauth-token-id": "ot-7Fr9d83jWsi8u23A" }, "created-at": "2018-09-11T18:21:21.784Z", "updated-at": "2018-09-11T18:21:21.784Z" }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" } }, "projects": { "data": [ { "id": "prj-AwfuCJTkdai4xj9w", "type": "projects" } ] }, "workspaces": { "data": [ { "id": "ws-2HRvNs49EWPjDqT1", "type": "workspaces" } ] }, "workspace-exclusions": { "data": [ { "id": "ws-FVVvzCDaykN1oHiw", "type": "workspaces" } ] }, }, "links": { "self":"/api/v2/policy-sets/polset-3yVQZvHzf5j3WRJ1" } } ] } ``` ### Sample response with individual policy relationships ```json { "data": [ { "id":"polset-3yVQZvHzf5j3WRJ1", "type":"policy-sets", "attributes": { "name": "production", "description": "This set contains policies that should be checked on all production infrastructure workspaces.", "kind": "sentinel", "global": false, "agent-enabled": true, "policy-tool-version": "0.23.0", "overridable": true, "policy-count": 1, "workspace-count": 1, "versioned": false, "created-at": "2018-09-11T18:21:21.784Z", "updated-at": "2018-09-11T18:21:21.784Z" }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" } }, "policies": { "data": [ { "id": "pol-u3S5p2Uwk21keu1s", "type": "policies" } ] }, "workspaces": { "data": [ { "id": "ws-2HRvNs49EWPjDqT1", "type": "workspaces" } ] } }, "links": { "self":"/api/v2/policy-sets/polset-3yVQZvHzf5j3WRJ1" } }, ] } ``` ## Show a policy set `GET /policy-sets/:id` | Parameter | Description | | --------- | ---------------------------------------------------------------------------------- | | `:id` | The ID of the policy set to show. Refer to [List Policy Sets](#list-policy-sets) for reference information about finding IDs. | | Status | Response | Reason | | ------- | --------------------------------------------- | ----------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "policy-sets"`) | The request was successful | | [404][] | [JSON API error object][] | Policy set not found or user unauthorized to perform action | | Parameter | Description | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `include` | **Optional.** Enables you to include related resource data. Value must be a comma-separated list containing one or more of `projects`, `workspaces`, `workspace-exclusions`, `policies`, `newest_version`, or `current_version`. See the [relationships section](#relationships) for details. | ### Sample Request ```shell curl --request GET \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/policy-sets/polset-3yVQZvHzf5j3WRJ1?include=current_version ``` ### Sample Response ```json { "data": { "id":"polset-3yVQZvHzf5j3WRJ1", "type":"policy-sets", "attributes": { "name": "production", "description": "This set contains policies that should be checked on all production infrastructure workspaces.", "kind": "sentinel", "global": false, "agent-enabled": true, "policy-tool-version": "0.23.0", "overridable": true, "policy-count": 0, "workspace-count": 1, "policies-path": "/policy-sets/foo", "versioned": true, "vcs-repo": { "branch": "main", "identifier": "hashicorp/my-policy-sets", "ingress-submodules": false, "oauth-token-id": "ot-7Fr9d83jWsi8u23A" }, "created-at": "2018-09-11T18:21:21.784Z", "updated-at": "2018-09-11T18:21:21.784Z" }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" } }, "current-version": { "data": { "id": "polsetver-m4yhbUBCgyDVpDL4", "type": "policy-set-versions" } }, "projects": { "data": [ { "id": "prj-AwfuCJTkdai4xj9w", "type": "projects" } ] }, "workspaces": { "data": [ { "id": "ws-2HRvNs49EWPjDqT1", "type": "workspaces" } ] }, "workspace-exclusions": { "data": [ { "id": "ws-FVVvzCDaykN1oHiw", "type": "workspaces" } ] }, }, "links": { "self":"/api/v2/policy-sets/polset-3yVQZvHzf5j3WRJ1" } }, "included": [ { "id": "polsetver-m4yhbUBCgyDVpDL4", "type": "policy-set-versions", "attributes": { "source": "github", "status": "ready", "status-timestamps": { "ready-at": "2019-06-21T21:29:48+00:00", "ingressing-at": "2019-06-21T21:29:47+00:00" }, "error": null, "ingress-attributes": { "commit-sha": "8766a423cb902887deb0f7da4d9beaed432984bb", "commit-url": "https://github.com/hashicorp/my-policy-sets/commit/8766a423cb902887deb0f7da4d9beaed432984bb", "identifier": "hashicorp/my-policy-sets" }, "created-at": "2019-06-21T21:29:47.792Z", "updated-at": "2019-06-21T21:29:48.887Z" }, "relationships": { "policy-set": { "data": { "id": "polset-a2mJwtmKygrA11dh", "type": "policy-sets" } } }, "links": { "self": "/api/v2/policy-set-versions/polsetver-E4S7jz8HMjBienLS" } } ] } ``` ### Sample response with individual policy relationships ```json { "data": { "id":"polset-3yVQZvHzf5j3WRJ1", "type":"policy-sets", "attributes": { "name": "production", "description": "This set contains policies that should be checked on all production infrastructure workspaces.", "kind": "sentinel", "global": false, "agent-enabled": true, "policy-tool-version": "0.23.0", "overridable": true, "policy-count": 1, "workspace-count": 1, "versioned": false, "created-at": "2018-09-11T18:21:21.784Z", "updated-at": "2018-09-11T18:21:21.784Z", }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" } }, "policies": { "data": [ { "id": "pol-u3S5p2Uwk21keu1s", "type": "policies" } ] }, "workspaces": { "data": [ { "id": "ws-2HRvNs49EWPjDqT1", "type": "workspaces" } ] } }, "links": { "self":"/api/v2/policy-sets/polset-3yVQZvHzf5j3WRJ1" } } } ``` -> **Note:** The `data.relationships.projects` and `data.relationships.workspaces` refer to the projects and workspaces attached to the policy set. HCP Terraform omits these keys for policy sets marked as global, which are implicitly related to all of the organization's workspaces. ## Update a policy set `PATCH /policy-sets/:id` | Parameter | Description | | --------- | ------------------------------------------------------------------------------------ | | `:id` | The ID of the policy set to update. Refer to [List Policy Sets](#list-policy-sets) for reference information about finding IDs. | | Status | Response | Reason | | ------- | --------------------------------------------- | -------------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "policy-sets"`) | The request was successful | | [404][] | [JSON API error object][] | Policy set not found or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (missing attributes, wrong types, etc.) | ### Request Body This PATCH endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | ---------------------------------------------------- | -------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `data.type` | string | | Must be `"policy-sets"`. | | `data.attributes.name` | string | (previous value) | The name of the policy set. Can include letters, numbers, `-`, and `_`. | | `data.attributes.description` | string | (previous value) | A description of the set's purpose. This field supports markdown and appears in the HCP Terraform UI. | | `data.attributes.global` | boolean | (previous value) | Whether or not the policies in this set should be checked in all of the organization's workspaces or only in workspaces directly attached to the set. | | `data.attributes.vcs-repo` | object | (previous value) | VCS repository information. When present, HCP Terraform sources the policies and configuration from the specified VCS repository instead of using definitions from HCP Terraform. Note that this option and `policies` relationships are mutually exclusive and may not be used simultaneously. | | `data.attributes.vcs-repo.branch` | string | (previous value) | The branch of the VCS repo. When empty, HCP Terraform uses the VCS provider's default branch value. | | `data.attributes.vcs-repo.identifier` | string | (previous value) | The VCS repository identifier in the the following format: `<namespace>/<repo>`. An example identifier in GitHub is `hashicorp/my-policy-set`. The format for Azure DevOps is `<org>/<project>/_git/<repo>`. | | `data.attributes.vcs-repo.oauth-token-id` | string | (previous value) | The OAuth token ID to use to connect to the VCS host. | | `data.attributes.vcs-repo.ingress-submodules` | boolean | (previous value) | Determines whether HCP Terraform instantiates repository submodules during the clone operation. | | `data.attributes.policies-path` | boolean | (previous value) | The subdirectory of the attached VCS repository that contains the policies for this policy set. HCP Terraform ignores files and directories outside of the sub-path. Changes to the unrelated files do not update the policy set. You can only enable this option when a VCS repository is present. | | `data.relationships.projects` | array\[object] | (previous value) | An array of references to projects that the policy set should be assigned to. Sending an empty array clears all project assignments. You can only specify this attribute when `data.attributes.global` is `false`. | | `data.relationships.workspaces` | array\[object] | (previous value) | An array of references to workspaces that the policy set should be assigned to. Sending an empty array clears all workspace assignments. You can only specify this attribute when `data.attributes.global` is `false`. | | `data.relationships.workspace-exclusions` | array\[object] | (previous value) | An array of references to excluded workspaces that HCP Terraform will not enforce this policy set upon. Sending an empty array clears all exclusions assignments. | | `data.attributes.agent-enabled` **(beta)** | boolean | `false` | Only valid for `sentinel` policy sets. Whether this policy set should run as a policy evaluation in the HCP Terraform agent. | |`data.attributes.policy-tool-version` **(beta)** | string | `latest` | The version of the tool that HCP Terraform uses to evaluate policies. You can only set a policy tool version for 'sentinel' policy sets if `agent-enabled` is `true`. | ### Sample Payload ```json { "data": { "type": "policy-sets", "attributes": { "name": "workspace-scoped-policy-set", "description": "Policies added to this policy set will be enforced on specified workspaces", "global": false, "agent-enabled": true, "policy-tool-version": "0.23.0" }, "relationships": { "projects": { "data": [ { "id": "prj-AwfuCJTkdai4xj9w", "type": "projects" } ] }, "workspaces": { "data": [ { "id": "ws-2HRvNs49EWPjDqT1", "type": "workspaces" } ] }, "workspace-exclusions": { "data": [ { "id": "ws-FVVvzCDaykN1oHiw", "type": "workspaces" } ] } } } } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request PATCH \ --data @payload.json \ https://app.terraform.io/api/v2/policy-sets/polset-3yVQZvHzf5j3WRJ1 ``` ### Sample Response ```json { "data": { "id":"polset-3yVQZvHzf5j3WRJ1", "type":"policy-sets", "attributes": { "name": "workspace-scoped-policy-set", "description": "Policies added to this policy set will be enforced on specified workspaces", "global": false, "kind": "sentinel", "agent-enabled": true, "policy-tool-version": "0.23.0", "overridable": true, "policy-count": 1, "workspace-count": 1, "versioned": false, "created-at": "2018-09-11T18:21:21.784Z", "updated-at": "2018-09-11T18:21:21.784Z" }, "relationships": { "organization": { "data": { "id": "my-organization", "type": "organizations" } }, "policies": { "data": [ { "id": "pol-u3S5p2Uwk21keu1s", "type": "policies" } ] }, "projects": { "data": [ { "id": "prj-AwfuCJTkdai4xj9w", "type": "projects" } ] }, "workspaces": { "data": [ { "id": "ws-2HRvNs49EWPjDqT1", "type": "workspaces" } ] }, "workspace-exclusions": { "data": [ { "id": "ws-FVVvzCDaykN1oHiw", "type": "workspaces" } ] } }, "links": { "self":"/api/v2/policy-sets/polset-3yVQZvHzf5j3WRJ1" } } } ``` ## Add policies to the policy set `POST /policy-sets/:id/relationships/policies` | Parameter | Description | | --------- | --------------------------------------------------------------------------------------------- | | `:id` | The ID of the policy set to add policies to. Refer to [List Policy Sets](#list-policy-sets) for reference information about finding IDs. | | Status | Response | Reason | | ------- | ------------------------- | -------------------------------------------------------------------------- | | [204][] | No Content | The request was successful | | [404][] | [JSON API error object][] | Policy set not found or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (one or more policies not found, wrong types, etc.) | ~> **Note:** This endpoint may only be used when there is no VCS repository associated with the policy set. ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | -------- | -------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `data[]` | array\[object] | | A list of resource identifier objects that defines which policies will be added to the set. These objects must contain `id` and `type` properties, and the `type` property must be `policies` (e.g. `{ "id": "pol-u3S5p2Uwk21keu1s", "type": "policies" }`). | ### Sample Payload ```json { "data": [ { "id": "pol-u3S5p2Uwk21keu1s", "type": "policies" }, { "id": "pol-2HRvNs49EWPjDqT1", "type": "policies" } ] } ``` ### Sample Request ```shell curl \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/policy-sets/polset-3yVQZvHzf5j3WRJ1/relationships/policies ``` ## Attach a policy set to projects `POST /policy-sets/:id/relationships/projects` | Parameter | Description | | --------- | ------------------------------------------------------------------------------------------------ | | `:id` | The ID of the policy set to attach to projects. Refer to [List Policy Sets](#list-policy-sets) for reference information about finding IDs. | -> **Note:** You can not attach global policy sets to individual projects. | Status | Response | Reason | | ------- | ------------------------- | -------------------------------------------------------------------------- | | [204][] | Nothing | The request was successful | | [404][] | [JSON API error object][] | Policy set not found or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (one or more projects not found, wrong types, etc.) | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | -------- | -------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data[]` | array\[object] | | A list of resource identifier objects that defines which projects to attach the policy set to. These objects must contain `id` and `type` properties, and the `type` property must be `projects` (e.g. `{ "id": "prj-AwfuCJTkdai4xj9w", "type": "projects" }`). | ### Sample Payload ```json { "data": [ { "id": "prj-AwfuCJTkdai4xj9w", "type": "projects" }, { "id": "prj-2HRvNs49EWPjDqT1", "type": "projects" } ] } ``` ### Sample Request ```shell curl \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/policy-sets/polset-3yVQZvHzf5j3WRJ1/relationships/projects ``` ## Attach a policy set to workspaces `POST /policy-sets/:id/relationships/workspaces` | Parameter | Description | | --------- | -------------------------------------------------------------------------------------------------- | | `:id` | The ID of the policy set to attach to workspaces. Refer to [List Policy Sets](#list-policy-sets) for reference information about finding IDs. | -> **Note:** Policy sets marked as global cannot be attached to individual workspaces. | Status | Response | Reason | | ------- | ------------------------- | ---------------------------------------------------------------------------- | | [204][] | No Content | The request was successful | | [404][] | [JSON API error object][] | Policy set not found or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (one or more workspaces not found, wrong types, etc.) | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | -------- | -------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data[]` | array\[object] | | A list of resource identifier objects that defines the workspaces the policy set will be attached to. These objects must contain `id` and `type` properties, and the `type` property must be `workspaces` (e.g. `{ "id": "ws-2HRvNs49EWPjDqT1", "type": "workspaces" }`). | ### Sample Payload ```json { "data": [ { "id": "ws-u3S5p2Uwk21keu1s", "type": "workspaces" }, { "id": "ws-2HRvNs49EWPjDqT1", "type": "workspaces" } ] } ``` ### Sample Request ```shell curl \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/policy-sets/polset-3yVQZvHzf5j3WRJ1/relationships/workspaces ``` ## Exclude a workspace from a policy set `POST /policy-sets/:id/relationships/workspace-exclusions` | Parameter | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `:id` | The ID of a policy set that you want HCP Terraform to exclude from the workspaces you specify. Refer to [List Policy Sets](#list-policy-sets) for reference information about finding IDs. | | Status | Response | Reason | | ------- | ------------------------- | ------------------------------------------------------------------------------------- | | [204][] | No Content | The request was successful | | [404][] | [JSON API error object][] | Policy set not found or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (one or more excluded workspaces not found, wrong types, etc.) | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | -------- | -------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data[]` | array\[object] | | A list of resource identifier objects that defines the excluded workspaces the policy set will be attached to. These objects must contain `id` and `type` properties, and the `type` property must be `workspaces` (e.g. `{ "id": "ws-2HRvNs49EWPjDqT1", "type": "workspaces" }`). | ### Sample Payload ```json { "data": [ { "id": "ws-u3S5p2Uwk21keu1s", "type": "workspaces" }, { "id": "ws-2HRvNs49EWPjDqT1", "type": "workspaces" } ] } ``` ### Sample Request ```shell curl \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/policy-sets/polset-3yVQZvHzf5j3WRJ1/relationships/workspace-exclusions ``` ## Remove policies from the policy set `DELETE /policy-sets/:id/relationships/policies` | Parameter | Description | | --------- | -------------------------------------------------------------------------------------------------- | | `:id` | The ID of the policy set to remove policies from. Refer to [List Policy Sets](#list-policy-sets) for reference information about finding IDs. | | Status | Response | Reason | | ------- | ------------------------- | ----------------------------------------------------------- | | [204][] | No Content | The request was successful | | [404][] | [JSON API error object][] | Policy set not found or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (wrong types, etc.) | ~> **Note:** This endpoint may only be used when there is no VCS repository associated with the policy set. ### Request Body This DELETE endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | -------- | -------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data[]` | array\[object] | | A list of resource identifier objects that defines which policies will be removed from the set. These objects must contain `id` and `type` properties, and the `type` property must be `policies` (e.g. `{ "id": "pol-u3S5p2Uwk21keu1s", "type": "policies" }`). | ### Sample Payload ```json { "data": [ { "id": "pol-u3S5p2Uwk21keu1s", "type": "policies" }, { "id": "pol-2HRvNs49EWPjDqT1", "type": "policies" } ] } ``` ### Sample Request ```shell curl \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/vnd.api+json" \ --request DELETE \ --data @payload.json \ https://app.terraform.io/api/v2/policy-sets/polset-3yVQZvHzf5j3WRJ1/relationships/policies ``` ## Detach a policy set from projects `DELETE /policy-sets/:id/relationships/projects` | Parameter | Description | | --------- | -------------------------------------------------------------------------------------------------- | | `:id` | The ID of the policy set you want to detach from the specified projects. Refer to [List Policy Sets](#list-policy-sets) for reference information about finding IDs. | -> **Note:** You can not attach global policy sets to individual projects. | Status | Response | Reason | | ------- | ------------------------- | -------------------------------------------------------------------------- | | [204][] | Nothing | The request was successful | | [404][] | [JSON API error object][] | Policy set not found or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (one or more projects not found, wrong types, etc.) | ### Request Body This DELETE endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | -------- | -------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data[]` | array\[object] | | A list of resource identifier objects that defines the projects the policy set will be detached from. These objects must contain `id` and `type` properties, and the `type` property must be `projects`. For example, `{ "id": "prj-AwfuCJTkdai4xj9w", "type": "projects" }`. | ### Sample Payload ```json { "data": [ { "id": "prj-AwfuCJTkdai4xj9w", "type": "projects" }, { "id": "prj-2HRvNs49EWPjDqT1", "type": "projects" } ] } ``` ### Sample Request ```shell curl \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/vnd.api+json" \ --request DELETE \ --data @payload.json \ https://app.terraform.io/api/v2/policy-sets/polset-3yVQZvHzf5j3WRJ1/relationships/projects ``` ## Detach the policy set from workspaces `DELETE /policy-sets/:id/relationships/workspaces` | Parameter | Description | | --------- | ---------------------------------------------------------------------------------------------------- | | `:id` | The ID of the policy set to detach from workspaces. Refer to [List Policy Sets](#list-policy-sets) for reference information about finding IDs. | -> **Note:** Policy sets marked as global cannot be detached from individual workspaces. | Status | Response | Reason | | ------- | ------------------------- | ----------------------------------------------------------- | | [204][] | No Content | The request was successful | | [404][] | [JSON API error object][] | Policy set not found or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (wrong types, etc.) | ### Request Body This DELETE endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | -------- | -------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data[]` | array\[object] | | A list of resource identifier objects that defines which workspaces the policy set will be detached from. These objects must contain `id` and `type` properties, and the `type` property must be `workspaces` (e.g. `{ "id": "ws-2HRvNs49EWPjDqT1", "type": "workspaces" }`). Obtain workspace IDs from the [workspace settings](/terraform/cloud-docs/workspaces/settings) or the [Show Workspace](/terraform/cloud-docs/api-docs/workspaces#show-workspace) endpoint. | ### Sample Payload ```json { "data": [ { "id": "ws-u3S5p2Uwk21keu1s", "type": "workspaces" }, { "id": "ws-2HRvNs49EWPjDqT1", "type": "workspaces" } ] } ``` ### Sample Request ```shell curl \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/vnd.api+json" \ --request DELETE \ --data @payload.json \ https://app.terraform.io/api/v2/policy-sets/polset-3yVQZvHzf5j3WRJ1/relationships/workspaces ``` ## Reinclude a workspace to a policy set `DELETE /policy-sets/:id/relationships/workspace-exclusions` | Parameter | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `:id` | The ID of the policy set HCP Terraform should reinclude (enforce) on the specified workspaces. Refer to [List Policy Sets](#list-policy-sets) for reference information about finding IDs. | | Status | Response | Reason | | ------- | ------------------------- | ----------------------------------------------------------- | | [204][] | No Content | The request was successful | | [404][] | [JSON API error object][] | Policy set not found or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (wrong types, etc.) | ### Request Body This DELETE endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | -------- | -------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `data[]` | array\[object] | | A list of resource identifier objects that defines which workspaces HCP Terraform should reinclude (enforce) this policy set on. These objects must contain `id` and `type` properties, and the `type` property must be `workspaces` (e.g. `{ "id": "ws-2HRvNs49EWPjDqT1", "type": "workspaces" }`). Obtain workspace IDs from the [workspace settings](/terraform/cloud-docs/workspaces/settings) or the [Show Workspace](/terraform/cloud-docs/api-docs/workspaces#show-workspace) endpoint. | ### Sample Payload ```json { "data": [ { "id": "ws-u3S5p2Uwk21keu1s", "type": "workspaces" }, { "id": "ws-2HRvNs49EWPjDqT1", "type": "workspaces" } ] } ``` ### Sample Request ```shell curl \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/vnd.api+json" \ --request DELETE \ --data @payload.json \ https://app.terraform.io/api/v2/policy-sets/polset-3yVQZvHzf5j3WRJ1/relationships/workspace-exclusions ``` ## Delete a policy set `DELETE /policy-sets/:id` | Parameter | Description | | --------- | ------------------------------------------------------------------------------------ | | `:id` | The ID of the policy set to delete. Refer to [List Policy Sets](#list-policy-sets) for reference information about finding IDs. | | Status | Response | Reason | | ------- | ------------------------- | ------------------------------------------------------------ | | [204][] | No Content | Successfully deleted the policy set | | [404][] | [JSON API error object][] | Policy set not found, or user unauthorized to perform action | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request DELETE \ https://app.terraform.io/api/v2/policy-sets/polset-3yVQZvHzf5j3WRJ1 ``` ## Create a policy set version For versioned policy sets which have no VCS repository attached, versions of policy code may be uploaded directly to the API by creating a new policy set version and, in a subsequent request, uploading a tarball (tar.gz) of data to it. `POST /policy-sets/:id/versions` | Parameter | Description | | --------- | ----------------------------------------------------- | | `:id` | The ID of the policy set to create a new version for. | | Status | Response | Reason | | ------- | ----------------------------------------------------- | ----------------------------------------------------------- | | [201][] | [JSON API document][] (`type: "policy-set-versions"`) | The request was successful. | | [404][] | [JSON API error object][] | Policy set not found or user unauthorized to perform action | | [422][] | [JSON API error object][] | The policy set does not support uploading versions. | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ https://app.terraform.io/api/v2/policy-sets/polset-3yVQZvHzf5j3WRJ1/versions ``` ### Sample Response ```json { "data": { "id": "polsetver-cXciu9nQwmk9Cfrn", "type": "policy-set-versions", "attributes": { "source": "tfe-api", "status": "pending", "status-timestamps": {}, "error": null, "created-at": "2019-06-28T23:53:15.875Z", "updated-at": "2019-06-28T23:53:15.875Z" }, "relationships": { "policy-set": { "data": { "id": "polset-ws1CZBzm2h5K6ZT5", "type": "policy-sets" } } }, "links": { "self": "/api/v2/policy-set-versions/polsetver-cXciu9nQwmk9Cfrn", "upload": "https://archivist.terraform.io/v1/object/dmF1bHQ6djE6NWJPbHQ4QjV4R1ox..." } } } ``` The `upload` link URL in the above response is valid for one hour after creation. Make a `PUT` request to this URL directly, sending the policy set contents in `tar.gz` format as the request body. Once uploaded successfully, you can request the [Show Policy Set](#show-a-policy-set) endpoint again to verify that the status has changed from `pending` to `ready`. ## Upload policy set versions `PUT https://archivist.terraform.io/v1/object/<UNIQUE OBJECT ID>` The URL is provided in the `upload` attribute in the `policy-set-versions` resource. ### Sample Request In the example below, `policy-set.tar.gz` is the local filename of the policy set version file to upload. ```shell curl \ --header "Content-Type: application/octet-stream" \ --request PUT \ --data-binary @policy-set.tar.gz \ https://archivist.terraform.io/v1/object/dmF1bHQ6djE6NWJPbHQ4QjV4R1ox... ``` ## Show a policy set version `GET /policy-set-versions/:id` | Parameter | Description | | --------- | ----------------------------------------- | | `:id` | The ID of the policy set version to show. | | Status | Response | Reason | | ------- | ----------------------------------------------------- | ------------------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "policy-set-versions"`) | The request was successful. | | [404][] | [JSON API error object][] | Policy set version not found or user unauthorized to perform action | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --request GET \ https://app.terraform.io/api/v2/policy-set-versions/polsetver-cXciu9nQwmk9Cfrn ``` ### Sample Response ```json { "data": { "id": "polsetver-cXciu9nQwmk9Cfrn", "type": "policy-set-versions", "attributes": { "source": "tfe-api", "status": "pending", "status-timestamps": {}, "error": null, "created-at": "2019-06-28T23:53:15.875Z", "updated-at": "2019-06-28T23:53:15.875Z" }, "relationships": { "policy-set": { "data": { "id": "polset-ws1CZBzm2h5K6ZT5", "type": "policy-sets" } } }, "links": { "self": "/api/v2/policy-set-versions/polsetver-cXciu9nQwmk9Cfrn", "upload": "https://archivist.terraform.io/v1/object/dmF1bHQ6djE6NWJPbHQ4QjV4R1ox..." } } } ``` The `upload` link URL in the above response is valid for one hour after the `created_at` timestamp of the policy set version. Make a `PUT` request to this URL directly, sending the policy set contents in `tar.gz` format as the request body. Once uploaded successfully, you can request the [Show Policy Set Version](#show-a-policy-set-version) endpoint again to verify that the status has changed from `pending` to `ready`. ## Available related resources The GET endpoints above can optionally return related resources for policy sets, if requested with [the `include` query parameter](/terraform/cloud-docs/api-docs#inclusion-of-related-resources). The following resource types are available: | Resource Name | Description | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `current_version` | The most recent **successful** policy set version. | | `newest_version` | The most recently created policy set version, regardless of status. Note that this relationship may include an errored and unusable version, and is intended to allow checking for VCS errors. | | `policies` | Individually managed policies which are associated with the policy set. | | `projects` | The projects this policy set applies to. | | `workspaces` | The workspaces this policy set applies to. | | `workspace-exclusions` | The workspaces excluded from this policy set's enforcement. | The following resource types may be included for policy set versions: | Resource Name | Description | | ------------- | ---------------------------------------------------------------- | | `policy_set` | The policy set associated with the specified policy set version. | ## Relationships The following relationships may be present in various responses for policy sets: | Resource Name | Description | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `current-version` | The most recent **successful** policy set version. | | `newest-version` | The most recently created policy set version, regardless of status. Note that this relationship may include an errored and unusable version, and is intended to allow checking for VCS errors. | | `organization` | The organization associated with the specified policy set. | | `policies` | Individually managed policies which are associated with the policy set. | | `projects` | The projects this policy set applies to. | | `workspaces` | The workspaces this policy set applies to. | | `workspace-exclusions` | The workspaces excluded from this policy set's enforcement. | The following relationships may be present in various responses for policy set versions: | Resource Name | Description | | ------------- | ---------------------------------------------------------------- | | `policy-set` | The policy set associated with the specified policy set version. |
terraform
page title Policy Sets API Docs HCP Terraform description Use the policy sets endpoint to manage groups of Sentinel and OPA policies List show create and update policy sets and policy set versions Attach detach and exclude policies from workspaces or attach and detach policies to projects 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects Policy sets API Policy Enforcement terraform cloud docs policy enforcement lets you use the policy as code frameworks Sentinel and Open Policy Agent OPA to apply policy checks to HCP Terraform workspaces Policy sets terraform cloud docs policy enforcement manage policy sets are collections of policies that you can apply globally or to specific projects terraform cloud docs projects manage and workspaces For each run in the selected workspaces HCP Terraform checks the Terraform plan against the policy set BEGIN TFC only name pnp callout include tfc package callouts policies mdx END TFC only name pnp callout This API provides endpoints to create read update and delete policy sets in an HCP Terraform organization To view and manage individual policies use the Policies API terraform cloud docs api docs policies Many of these endpoints let you create policy sets from a designated repository in a Version Control System VCS For more information about how to configure a policy set VCS repository refer to Sentinel Policy Set VCS Repositories terraform cloud docs policy enforcement sentinel vcs and OPA Policy Set VCS Repositories terraform cloud docs policy enforcement opa vcs Instead of connecting HCP Terraform to a VCS repository you can use the the Policy Set Versions endpoint create a policy set version to create an entire policy set from a tar gz file Interacting with policy sets requires permission to manage policies More about permissions terraform cloud docs users teams organizations permissions permissions citation intentionally unused keep for maintainers Create a policy set POST organizations organization name policy sets Parameter Description organization name The organization to create the policy set in The organization must already exist in the system and the token authenticating the API request must have permission to manage policies More about permissions terraform cloud docs users teams organizations permissions permissions citation intentionally unused keep for maintainers Status Response Reason 201 JSON API document type policy sets Successfully created a policy set 404 JSON API error object Organization not found or user unauthorized to perform action 422 JSON API error object Malformed request body missing attributes wrong types etc Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string Must be policy sets data attributes name string The name of the policy set Can include letters numbers and data attributes description string null Text describing the policy set s purpose This field supports Markdown and appears in the HCP Terraform UI data attributes global boolean false Whether HCP Terraform should automatically apply this policy set to all of an organization s workspaces data attributes kind string sentinel The policy as code framework associated with the policy Valid values are sentinel and opa data attributes overridable boolean false Whether or not users can override this policy when it fails during a run Valid for sentinel policies only if agent enabled is set to true data attributes vcs repo object null VCS repository information When present HCP Terraform sources the policies and configuration from the specified VCS repository This attribute and policies relationships are mutually exclusive and you cannot use them simultaneously data attributes vcs repo branch string null The branch of the VCS repository where HCP Terraform should retrieve the policy set If empty HCP Terraform uses the default branch data attributes vcs repo identifier string The VCS repository identifier in the format namespace repo For example hashicorp my policy set The format for Azure DevOps is org project git repo data attributes vcs repo oauth token id string The OAuth Token ID HCP Terraform should use to connect to the VCS host This value must not be specified if github app installation id is specified data attributes vcs repo github app installation id string The VCS Connection GitHub App Installation to use Find this ID on the account settings page Requires previously authorizing the GitHub App and generating a user to server token Manage the token from Account Settings within HCP Terraform You can not specify this value if oauth token id is specified data attributes vcs repo ingress submodules boolean false Whether HCP Terraform should instantiate repository submodules when retrieving the policy set data attributes policies path string null The VCS repository subdirectory that contains the policies for this policy set HCP Terraform ignores files and directories outside of this sub path and does not update the policy set when those files change This attribute is only valid when you specify a VCS repository for the policy set data relationships projects data array object A list of resource identifier objects that defines which projects are associated with the policy set These objects must contain id and type properties and the type property must be projects For example id prj AwfuCJTkdai4xj9w type projects You can only specify this attribute when data attributes global is false data relationships workspaces data array object A list of resource identifier objects that defines which workspaces are associated with the policy set These objects must contain id and type properties and the type property must be workspaces For example id ws 2HRvNs49EWPjDqT1 type workspaces Obtain workspace IDs from the workspace s settings page terraform enterprise workspaces settings or the Show Workspace endpoint terraform enterprise api docs workspaces show workspace You can only specify this attribute when data attributes global is false data relationships workspace exclusions data array object A list of resource identifier objects specifying which workspaces HCP Terraform excludes from a policy set s enforcement These objects must contain id and type properties and the type property must be workspaces For example id ws FVVvzCDaykN1oHiw type workspaces data relationships policies data array object A list of resource identifier objects that defines which policies are members of the policy set These objects must contain id and type properties and the type property must be policies For example id pol u3S5p2Uwk21keu1s type policies data attributes agent enabled beta boolean false Only valid for sentinel policy sets Whether this policy set should run as a policy evaluation in the HCP Terraform agent data attributes policy tool version beta string latest The version of the tool that HCP Terraform uses to evaluate policies You can only set a policy tool version for sentinel policy sets if agent enabled is true Sample Payload json data type policy sets attributes name production description This set contains policies that should be checked on all production infrastructure workspaces global false kind sentinel agent enabled true policy tool version 0 23 0 overridable true policies path policy sets foo vcs repo branch main identifier hashicorp my policy sets ingress submodules false oauth token id ot 7Fr9d83jWsi8u23A relationships projects data id prj AwfuCJTkdai4xj9w type projects workspaces data id ws 2HRvNs49EWPjDqT1 type workspaces workspace exclusions data id ws FVVvzCDaykN1oHiw type workspaces Sample payload with individual policy relationships json data type policy sets attributes name production description This set contains policies that should be checked on all production infrastructure workspaces kind sentinel global false agent enabled true policy tool version 0 23 0 overridable true relationships policies data id pol u3S5p2Uwk21keu1s type policies workspaces data id ws 2HRvNs49EWPjDqT1 type workspaces Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 organizations my organization policy sets Sample Response json data id polset 3yVQZvHzf5j3WRJ1 type policy sets attributes name production description This set contains policies that should be checked on all production infrastructure workspaces kind sentinel global false agent enabled true policy tool version 0 23 0 overridable true workspace count 1 policies path policy sets foo versioned true vcs repo branch main identifier hashicorp my policy sets ingress submodules false oauth token id ot 7Fr9d83jWsi8u23A created at 2018 09 11T18 21 21 784Z updated at 2018 09 11T18 21 21 784Z relationships organization data id my organization type organizations projects data id prj AwfuCJTkdai4xj9w type projects workspaces data id ws 2HRvNs49EWPjDqT1 type workspaces workspace exclusions data id ws FVVvzCDaykN1oHiw type workspaces links self api v2 policy sets polset 3yVQZvHzf5j3WRJ1 Sample response with individual policy relationships json data id polset 3yVQZvHzf5j3WRJ1 type policy sets attributes name production description This set contains policies that should be checked on all production infrastructure workspaces kind sentinel global false agent enabled true policy tool version 0 23 0 overridable true policy count 1 workspace count 1 versioned false created at 2018 09 11T18 21 21 784Z updated at 2018 09 11T18 21 21 784Z relationships organization data id my organization type organizations policies data id pol u3S5p2Uwk21keu1s type policies workspaces data id ws 2HRvNs49EWPjDqT1 type workspaces links self api v2 policy sets polset 3yVQZvHzf5j3WRJ1 List policy sets GET organizations organization name policy sets Parameter Description organization name The organization to list policy sets for Status Response Reason 200 JSON API document type policy sets Request was successful 404 JSON API error object Organization not found or user unauthorized to perform action Query Parameters This endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs Parameter Description filter versioned Optional Allows filtering policy sets based on whether they are versioned VCS managed or API managed or use individual policy relationships Accepts a boolean true false value A true value returns versioned sets and a false value returns sets with individual policy relationships If omitted all policy sets are returned filter kind Optional If specified restricts results to those with the matching policy kind value Valid values are sentinel and opa include Optional Enables you to include related resource data Value must be a comma separated list containing one or more of projects workspaces workspace exclusions policies newest version or current version See the relationships section relationships for details page number Optional If omitted the endpoint will return the first page page size Optional If omitted the endpoint will return 20 policy sets per page search name Optional Allows searching the organization s policy sets by name Sample Request shell curl header Authorization Bearer TOKEN https app terraform io api v2 organizations my organization policy sets Sample Response json data id polset 3yVQZvHzf5j3WRJ1 type policy sets attributes name production description This set contains policies that should be checked on all production infrastructure workspaces kind sentinel global false agent enabled true policy tool version 0 23 0 overridable true workspace count 1 policies path policy sets foo versioned true vcs repo branch main identifier hashicorp my policy sets ingress submodules false oauth token id ot 7Fr9d83jWsi8u23A created at 2018 09 11T18 21 21 784Z updated at 2018 09 11T18 21 21 784Z relationships organization data id my organization type organizations projects data id prj AwfuCJTkdai4xj9w type projects workspaces data id ws 2HRvNs49EWPjDqT1 type workspaces workspace exclusions data id ws FVVvzCDaykN1oHiw type workspaces links self api v2 policy sets polset 3yVQZvHzf5j3WRJ1 Sample response with individual policy relationships json data id polset 3yVQZvHzf5j3WRJ1 type policy sets attributes name production description This set contains policies that should be checked on all production infrastructure workspaces kind sentinel global false agent enabled true policy tool version 0 23 0 overridable true policy count 1 workspace count 1 versioned false created at 2018 09 11T18 21 21 784Z updated at 2018 09 11T18 21 21 784Z relationships organization data id my organization type organizations policies data id pol u3S5p2Uwk21keu1s type policies workspaces data id ws 2HRvNs49EWPjDqT1 type workspaces links self api v2 policy sets polset 3yVQZvHzf5j3WRJ1 Show a policy set GET policy sets id Parameter Description id The ID of the policy set to show Refer to List Policy Sets list policy sets for reference information about finding IDs Status Response Reason 200 JSON API document type policy sets The request was successful 404 JSON API error object Policy set not found or user unauthorized to perform action Parameter Description include Optional Enables you to include related resource data Value must be a comma separated list containing one or more of projects workspaces workspace exclusions policies newest version or current version See the relationships section relationships for details Sample Request shell curl request GET H Authorization Bearer TOKEN H Content Type application vnd api json https app terraform io api v2 policy sets polset 3yVQZvHzf5j3WRJ1 include current version Sample Response json data id polset 3yVQZvHzf5j3WRJ1 type policy sets attributes name production description This set contains policies that should be checked on all production infrastructure workspaces kind sentinel global false agent enabled true policy tool version 0 23 0 overridable true policy count 0 workspace count 1 policies path policy sets foo versioned true vcs repo branch main identifier hashicorp my policy sets ingress submodules false oauth token id ot 7Fr9d83jWsi8u23A created at 2018 09 11T18 21 21 784Z updated at 2018 09 11T18 21 21 784Z relationships organization data id my organization type organizations current version data id polsetver m4yhbUBCgyDVpDL4 type policy set versions projects data id prj AwfuCJTkdai4xj9w type projects workspaces data id ws 2HRvNs49EWPjDqT1 type workspaces workspace exclusions data id ws FVVvzCDaykN1oHiw type workspaces links self api v2 policy sets polset 3yVQZvHzf5j3WRJ1 included id polsetver m4yhbUBCgyDVpDL4 type policy set versions attributes source github status ready status timestamps ready at 2019 06 21T21 29 48 00 00 ingressing at 2019 06 21T21 29 47 00 00 error null ingress attributes commit sha 8766a423cb902887deb0f7da4d9beaed432984bb commit url https github com hashicorp my policy sets commit 8766a423cb902887deb0f7da4d9beaed432984bb identifier hashicorp my policy sets created at 2019 06 21T21 29 47 792Z updated at 2019 06 21T21 29 48 887Z relationships policy set data id polset a2mJwtmKygrA11dh type policy sets links self api v2 policy set versions polsetver E4S7jz8HMjBienLS Sample response with individual policy relationships json data id polset 3yVQZvHzf5j3WRJ1 type policy sets attributes name production description This set contains policies that should be checked on all production infrastructure workspaces kind sentinel global false agent enabled true policy tool version 0 23 0 overridable true policy count 1 workspace count 1 versioned false created at 2018 09 11T18 21 21 784Z updated at 2018 09 11T18 21 21 784Z relationships organization data id my organization type organizations policies data id pol u3S5p2Uwk21keu1s type policies workspaces data id ws 2HRvNs49EWPjDqT1 type workspaces links self api v2 policy sets polset 3yVQZvHzf5j3WRJ1 Note The data relationships projects and data relationships workspaces refer to the projects and workspaces attached to the policy set HCP Terraform omits these keys for policy sets marked as global which are implicitly related to all of the organization s workspaces Update a policy set PATCH policy sets id Parameter Description id The ID of the policy set to update Refer to List Policy Sets list policy sets for reference information about finding IDs Status Response Reason 200 JSON API document type policy sets The request was successful 404 JSON API error object Policy set not found or user unauthorized to perform action 422 JSON API error object Malformed request body missing attributes wrong types etc Request Body This PATCH endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string Must be policy sets data attributes name string previous value The name of the policy set Can include letters numbers and data attributes description string previous value A description of the set s purpose This field supports markdown and appears in the HCP Terraform UI data attributes global boolean previous value Whether or not the policies in this set should be checked in all of the organization s workspaces or only in workspaces directly attached to the set data attributes vcs repo object previous value VCS repository information When present HCP Terraform sources the policies and configuration from the specified VCS repository instead of using definitions from HCP Terraform Note that this option and policies relationships are mutually exclusive and may not be used simultaneously data attributes vcs repo branch string previous value The branch of the VCS repo When empty HCP Terraform uses the VCS provider s default branch value data attributes vcs repo identifier string previous value The VCS repository identifier in the the following format namespace repo An example identifier in GitHub is hashicorp my policy set The format for Azure DevOps is org project git repo data attributes vcs repo oauth token id string previous value The OAuth token ID to use to connect to the VCS host data attributes vcs repo ingress submodules boolean previous value Determines whether HCP Terraform instantiates repository submodules during the clone operation data attributes policies path boolean previous value The subdirectory of the attached VCS repository that contains the policies for this policy set HCP Terraform ignores files and directories outside of the sub path Changes to the unrelated files do not update the policy set You can only enable this option when a VCS repository is present data relationships projects array object previous value An array of references to projects that the policy set should be assigned to Sending an empty array clears all project assignments You can only specify this attribute when data attributes global is false data relationships workspaces array object previous value An array of references to workspaces that the policy set should be assigned to Sending an empty array clears all workspace assignments You can only specify this attribute when data attributes global is false data relationships workspace exclusions array object previous value An array of references to excluded workspaces that HCP Terraform will not enforce this policy set upon Sending an empty array clears all exclusions assignments data attributes agent enabled beta boolean false Only valid for sentinel policy sets Whether this policy set should run as a policy evaluation in the HCP Terraform agent data attributes policy tool version beta string latest The version of the tool that HCP Terraform uses to evaluate policies You can only set a policy tool version for sentinel policy sets if agent enabled is true Sample Payload json data type policy sets attributes name workspace scoped policy set description Policies added to this policy set will be enforced on specified workspaces global false agent enabled true policy tool version 0 23 0 relationships projects data id prj AwfuCJTkdai4xj9w type projects workspaces data id ws 2HRvNs49EWPjDqT1 type workspaces workspace exclusions data id ws FVVvzCDaykN1oHiw type workspaces Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request PATCH data payload json https app terraform io api v2 policy sets polset 3yVQZvHzf5j3WRJ1 Sample Response json data id polset 3yVQZvHzf5j3WRJ1 type policy sets attributes name workspace scoped policy set description Policies added to this policy set will be enforced on specified workspaces global false kind sentinel agent enabled true policy tool version 0 23 0 overridable true policy count 1 workspace count 1 versioned false created at 2018 09 11T18 21 21 784Z updated at 2018 09 11T18 21 21 784Z relationships organization data id my organization type organizations policies data id pol u3S5p2Uwk21keu1s type policies projects data id prj AwfuCJTkdai4xj9w type projects workspaces data id ws 2HRvNs49EWPjDqT1 type workspaces workspace exclusions data id ws FVVvzCDaykN1oHiw type workspaces links self api v2 policy sets polset 3yVQZvHzf5j3WRJ1 Add policies to the policy set POST policy sets id relationships policies Parameter Description id The ID of the policy set to add policies to Refer to List Policy Sets list policy sets for reference information about finding IDs Status Response Reason 204 No Content The request was successful 404 JSON API error object Policy set not found or user unauthorized to perform action 422 JSON API error object Malformed request body one or more policies not found wrong types etc Note This endpoint may only be used when there is no VCS repository associated with the policy set Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data array object A list of resource identifier objects that defines which policies will be added to the set These objects must contain id and type properties and the type property must be policies e g id pol u3S5p2Uwk21keu1s type policies Sample Payload json data id pol u3S5p2Uwk21keu1s type policies id pol 2HRvNs49EWPjDqT1 type policies Sample Request shell curl H Authorization Bearer TOKEN H Content Type application vnd api json request POST data payload json https app terraform io api v2 policy sets polset 3yVQZvHzf5j3WRJ1 relationships policies Attach a policy set to projects POST policy sets id relationships projects Parameter Description id The ID of the policy set to attach to projects Refer to List Policy Sets list policy sets for reference information about finding IDs Note You can not attach global policy sets to individual projects Status Response Reason 204 Nothing The request was successful 404 JSON API error object Policy set not found or user unauthorized to perform action 422 JSON API error object Malformed request body one or more projects not found wrong types etc Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data array object A list of resource identifier objects that defines which projects to attach the policy set to These objects must contain id and type properties and the type property must be projects e g id prj AwfuCJTkdai4xj9w type projects Sample Payload json data id prj AwfuCJTkdai4xj9w type projects id prj 2HRvNs49EWPjDqT1 type projects Sample Request shell curl H Authorization Bearer TOKEN H Content Type application vnd api json request POST data payload json https app terraform io api v2 policy sets polset 3yVQZvHzf5j3WRJ1 relationships projects Attach a policy set to workspaces POST policy sets id relationships workspaces Parameter Description id The ID of the policy set to attach to workspaces Refer to List Policy Sets list policy sets for reference information about finding IDs Note Policy sets marked as global cannot be attached to individual workspaces Status Response Reason 204 No Content The request was successful 404 JSON API error object Policy set not found or user unauthorized to perform action 422 JSON API error object Malformed request body one or more workspaces not found wrong types etc Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data array object A list of resource identifier objects that defines the workspaces the policy set will be attached to These objects must contain id and type properties and the type property must be workspaces e g id ws 2HRvNs49EWPjDqT1 type workspaces Sample Payload json data id ws u3S5p2Uwk21keu1s type workspaces id ws 2HRvNs49EWPjDqT1 type workspaces Sample Request shell curl H Authorization Bearer TOKEN H Content Type application vnd api json request POST data payload json https app terraform io api v2 policy sets polset 3yVQZvHzf5j3WRJ1 relationships workspaces Exclude a workspace from a policy set POST policy sets id relationships workspace exclusions Parameter Description id The ID of a policy set that you want HCP Terraform to exclude from the workspaces you specify Refer to List Policy Sets list policy sets for reference information about finding IDs Status Response Reason 204 No Content The request was successful 404 JSON API error object Policy set not found or user unauthorized to perform action 422 JSON API error object Malformed request body one or more excluded workspaces not found wrong types etc Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data array object A list of resource identifier objects that defines the excluded workspaces the policy set will be attached to These objects must contain id and type properties and the type property must be workspaces e g id ws 2HRvNs49EWPjDqT1 type workspaces Sample Payload json data id ws u3S5p2Uwk21keu1s type workspaces id ws 2HRvNs49EWPjDqT1 type workspaces Sample Request shell curl H Authorization Bearer TOKEN H Content Type application vnd api json request POST data payload json https app terraform io api v2 policy sets polset 3yVQZvHzf5j3WRJ1 relationships workspace exclusions Remove policies from the policy set DELETE policy sets id relationships policies Parameter Description id The ID of the policy set to remove policies from Refer to List Policy Sets list policy sets for reference information about finding IDs Status Response Reason 204 No Content The request was successful 404 JSON API error object Policy set not found or user unauthorized to perform action 422 JSON API error object Malformed request body wrong types etc Note This endpoint may only be used when there is no VCS repository associated with the policy set Request Body This DELETE endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data array object A list of resource identifier objects that defines which policies will be removed from the set These objects must contain id and type properties and the type property must be policies e g id pol u3S5p2Uwk21keu1s type policies Sample Payload json data id pol u3S5p2Uwk21keu1s type policies id pol 2HRvNs49EWPjDqT1 type policies Sample Request shell curl H Authorization Bearer TOKEN H Content Type application vnd api json request DELETE data payload json https app terraform io api v2 policy sets polset 3yVQZvHzf5j3WRJ1 relationships policies Detach a policy set from projects DELETE policy sets id relationships projects Parameter Description id The ID of the policy set you want to detach from the specified projects Refer to List Policy Sets list policy sets for reference information about finding IDs Note You can not attach global policy sets to individual projects Status Response Reason 204 Nothing The request was successful 404 JSON API error object Policy set not found or user unauthorized to perform action 422 JSON API error object Malformed request body one or more projects not found wrong types etc Request Body This DELETE endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data array object A list of resource identifier objects that defines the projects the policy set will be detached from These objects must contain id and type properties and the type property must be projects For example id prj AwfuCJTkdai4xj9w type projects Sample Payload json data id prj AwfuCJTkdai4xj9w type projects id prj 2HRvNs49EWPjDqT1 type projects Sample Request shell curl H Authorization Bearer TOKEN H Content Type application vnd api json request DELETE data payload json https app terraform io api v2 policy sets polset 3yVQZvHzf5j3WRJ1 relationships projects Detach the policy set from workspaces DELETE policy sets id relationships workspaces Parameter Description id The ID of the policy set to detach from workspaces Refer to List Policy Sets list policy sets for reference information about finding IDs Note Policy sets marked as global cannot be detached from individual workspaces Status Response Reason 204 No Content The request was successful 404 JSON API error object Policy set not found or user unauthorized to perform action 422 JSON API error object Malformed request body wrong types etc Request Body This DELETE endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data array object A list of resource identifier objects that defines which workspaces the policy set will be detached from These objects must contain id and type properties and the type property must be workspaces e g id ws 2HRvNs49EWPjDqT1 type workspaces Obtain workspace IDs from the workspace settings terraform cloud docs workspaces settings or the Show Workspace terraform cloud docs api docs workspaces show workspace endpoint Sample Payload json data id ws u3S5p2Uwk21keu1s type workspaces id ws 2HRvNs49EWPjDqT1 type workspaces Sample Request shell curl H Authorization Bearer TOKEN H Content Type application vnd api json request DELETE data payload json https app terraform io api v2 policy sets polset 3yVQZvHzf5j3WRJ1 relationships workspaces Reinclude a workspace to a policy set DELETE policy sets id relationships workspace exclusions Parameter Description id The ID of the policy set HCP Terraform should reinclude enforce on the specified workspaces Refer to List Policy Sets list policy sets for reference information about finding IDs Status Response Reason 204 No Content The request was successful 404 JSON API error object Policy set not found or user unauthorized to perform action 422 JSON API error object Malformed request body wrong types etc Request Body This DELETE endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data array object A list of resource identifier objects that defines which workspaces HCP Terraform should reinclude enforce this policy set on These objects must contain id and type properties and the type property must be workspaces e g id ws 2HRvNs49EWPjDqT1 type workspaces Obtain workspace IDs from the workspace settings terraform cloud docs workspaces settings or the Show Workspace terraform cloud docs api docs workspaces show workspace endpoint Sample Payload json data id ws u3S5p2Uwk21keu1s type workspaces id ws 2HRvNs49EWPjDqT1 type workspaces Sample Request shell curl H Authorization Bearer TOKEN H Content Type application vnd api json request DELETE data payload json https app terraform io api v2 policy sets polset 3yVQZvHzf5j3WRJ1 relationships workspace exclusions Delete a policy set DELETE policy sets id Parameter Description id The ID of the policy set to delete Refer to List Policy Sets list policy sets for reference information about finding IDs Status Response Reason 204 No Content Successfully deleted the policy set 404 JSON API error object Policy set not found or user unauthorized to perform action Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request DELETE https app terraform io api v2 policy sets polset 3yVQZvHzf5j3WRJ1 Create a policy set version For versioned policy sets which have no VCS repository attached versions of policy code may be uploaded directly to the API by creating a new policy set version and in a subsequent request uploading a tarball tar gz of data to it POST policy sets id versions Parameter Description id The ID of the policy set to create a new version for Status Response Reason 201 JSON API document type policy set versions The request was successful 404 JSON API error object Policy set not found or user unauthorized to perform action 422 JSON API error object The policy set does not support uploading versions Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST https app terraform io api v2 policy sets polset 3yVQZvHzf5j3WRJ1 versions Sample Response json data id polsetver cXciu9nQwmk9Cfrn type policy set versions attributes source tfe api status pending status timestamps error null created at 2019 06 28T23 53 15 875Z updated at 2019 06 28T23 53 15 875Z relationships policy set data id polset ws1CZBzm2h5K6ZT5 type policy sets links self api v2 policy set versions polsetver cXciu9nQwmk9Cfrn upload https archivist terraform io v1 object dmF1bHQ6djE6NWJPbHQ4QjV4R1ox The upload link URL in the above response is valid for one hour after creation Make a PUT request to this URL directly sending the policy set contents in tar gz format as the request body Once uploaded successfully you can request the Show Policy Set show a policy set endpoint again to verify that the status has changed from pending to ready Upload policy set versions PUT https archivist terraform io v1 object UNIQUE OBJECT ID The URL is provided in the upload attribute in the policy set versions resource Sample Request In the example below policy set tar gz is the local filename of the policy set version file to upload shell curl header Content Type application octet stream request PUT data binary policy set tar gz https archivist terraform io v1 object dmF1bHQ6djE6NWJPbHQ4QjV4R1ox Show a policy set version GET policy set versions id Parameter Description id The ID of the policy set version to show Status Response Reason 200 JSON API document type policy set versions The request was successful 404 JSON API error object Policy set version not found or user unauthorized to perform action Sample Request shell curl header Authorization Bearer TOKEN request GET https app terraform io api v2 policy set versions polsetver cXciu9nQwmk9Cfrn Sample Response json data id polsetver cXciu9nQwmk9Cfrn type policy set versions attributes source tfe api status pending status timestamps error null created at 2019 06 28T23 53 15 875Z updated at 2019 06 28T23 53 15 875Z relationships policy set data id polset ws1CZBzm2h5K6ZT5 type policy sets links self api v2 policy set versions polsetver cXciu9nQwmk9Cfrn upload https archivist terraform io v1 object dmF1bHQ6djE6NWJPbHQ4QjV4R1ox The upload link URL in the above response is valid for one hour after the created at timestamp of the policy set version Make a PUT request to this URL directly sending the policy set contents in tar gz format as the request body Once uploaded successfully you can request the Show Policy Set Version show a policy set version endpoint again to verify that the status has changed from pending to ready Available related resources The GET endpoints above can optionally return related resources for policy sets if requested with the include query parameter terraform cloud docs api docs inclusion of related resources The following resource types are available Resource Name Description current version The most recent successful policy set version newest version The most recently created policy set version regardless of status Note that this relationship may include an errored and unusable version and is intended to allow checking for VCS errors policies Individually managed policies which are associated with the policy set projects The projects this policy set applies to workspaces The workspaces this policy set applies to workspace exclusions The workspaces excluded from this policy set s enforcement The following resource types may be included for policy set versions Resource Name Description policy set The policy set associated with the specified policy set version Relationships The following relationships may be present in various responses for policy sets Resource Name Description current version The most recent successful policy set version newest version The most recently created policy set version regardless of status Note that this relationship may include an errored and unusable version and is intended to allow checking for VCS errors organization The organization associated with the specified policy set policies Individually managed policies which are associated with the policy set projects The projects this policy set applies to workspaces The workspaces this policy set applies to workspace exclusions The workspaces excluded from this policy set s enforcement The following relationships may be present in various responses for policy set versions Resource Name Description policy set The policy set associated with the specified policy set version
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 page title Teams API Docs HCP Terraform Use the teams endpoint to manage teams List show create update and delete teams using the HTTP API
--- page_title: Teams - API Docs - HCP Terraform description: >- Use the `/teams` endpoint to manage teams. List, show, create, update, and delete teams using the HTTP API. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # Teams API The Teams API is used to create, edit, and destroy teams as well as manage a team's organization-level permissions. The [Team Membership API](/terraform/cloud-docs/api-docs/team-members) is used to add or remove users from a team. Use the [Team Access API](/terraform/cloud-docs/api-docs/team-access) to associate a team with privileges on an individual workspace. <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/team-management.mdx' <!-- END: TFC:only name:pnp-callout --> Any member of an organization can view visible teams and any secret teams they are a member of. Only organization owners can modify teams or view the full set of secret teams. The organization token and the owners team token can act as an owner on these endpoints. ([More about permissions.](/terraform/cloud-docs/users-teams-organizations/permissions)) [permissions-citation]: #intentionally-unused---keep-for-maintainers ## Organization Membership -> **Note:** Users must be invited to join organizations before they can be added to teams. See [the Organization Memberships API documentation](/terraform/cloud-docs/api-docs/organization-memberships) for more information. Invited users who have not yet accepted will not appear in Teams API responses. ## List teams `GET organizations/:organization_name/teams` | Parameter | Description | | -------------------- | ------------------------------------------------ | | `:organization_name` | The name of the organization to list teams from. | The response may identify HashiCorp API service accounts, for example `api-team_XXXXXX`, as a members of a team. However, API service accounts do not appear in the UI. As a result, there may be differences between the number of team members reported by the UI and the API. For example, the UI may report `0` members on a team when and the API reports `1`. ### Query Parameters This endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. | Parameter | Description | | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `q` | **Optional.** Allows querying a list of teams by name. This search is case-insensitive. | | `filter[names]` | **Optional.** If specified, restricts results to a team with a matching name. If multiple comma separated values are specified, teams matching any of the names are returned.| | `page[number]` | **Optional.** If omitted, the endpoint will return the first page. | | `page[size]` | **Optional.** If omitted, the endpoint will return 20 teams per page. | ### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/organizations/my-organization/teams ``` ### Sample Response The `sso-team-id` attribute is only returned in Terraform Enterprise 202204-1 and later, or in HCP Terraform. The `allow-member-token-management` attribute is set to `false` for Terraform Enterprise versions older than 202408-1. ```json { "data": [ { "id": "team-6p5jTwJQXwqZBncC", "type": "teams", "attributes": { "name": "team-creation-test", "sso-team-id": "cb265c8e41bddf3f9926b2cf3d190f0e1627daa4", "users-count": 0, "visibility": "organization", "allow-member-token-management": true, "permissions": { "can-update-membership": true, "can-destroy": true, "can-update-organization-access": true, "can-update-api-token": true, "can-update-visibility": true }, "organization-access": { "manage-policies": true, "manage-policy-overrides": false, "manage-run-tasks": true, "manage-workspaces": false, "manage-vcs-settings": false, "manage-agent-pools": false, "manage-projects": false, "read-projects": false, "read-workspaces": false } }, "relationships": { "users": { "data": [] }, "authentication-token": { "meta": {} } }, "links": { "self": "/api/v2/teams/team-6p5jTwJQXwqZBncC" } } ] } ``` ## Create a Team `POST /organizations/:organization_name/teams` | Parameter | Description | | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `:organization_name` | The name of the organization to create the team in. The organization must already exist in the system, and the user must have permissions to create new teams. | | Status | Response | Reason | | ------- | --------------------------------------- | -------------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "teams"`) | Successfully created a team | | [400][] | [JSON API error object][] | Invalid `include` parameter | | [404][] | [JSON API error object][] | Organization not found, or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (missing attributes, wrong types, etc.) | | [500][] | [JSON API error object][] | Failure during team creation | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. -> **Note:** You cannot set `manage-workspaces` to `false` when setting `manage-projects` to `true`, since project permissions cascade down to workspaces. This is also the case for `read-workspaces` and `read-projects`. If `read-projects` is `true`, `read-workspaces` must be `true` as well. | Key path | Type | Default | Description | |-----------------------------------------|--------|------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `data.type` | string | | Must be `"teams"`. | | `data.attributes.name` | string | | The name of the team, which can only include letters, numbers, `-`, and `_`. This will be used as an identifier and must be unique in the organization. | | `data.attributes.sso-team-id` | string | (nothing) | The unique identifier of the team from the SAML `MemberOf` attribute. Only available in Terraform Enterprise 202204-1 and later, or in HCP Terraform. | | `data.attributes.organization-access` | object | (nothing) | Settings for the team's organization access. This object can include the `manage-policies`, `manage-policy-overrides`, `manage-run-tasks`, `manage-workspaces`, `manage-vcs-settings`, `manage-agent-pools`, `manage-providers`, `manage-modules`, `manage-projects`, `read-projects`, `read-workspaces`, `manage-membership`, `manage-teams`, and `manage-organization-access` properties with boolean values. All properties default to `false`. | | `data.attributes.visibility` **(beta)** | string | `"secret"` | The team's visibility. Must be `"secret"` or `"organization"` (visible). | ### Sample Payload ```json { "data": { "type": "teams", "attributes": { "name": "team-creation-test", "sso-team-id": "cb265c8e41bddf3f9926b2cf3d190f0e1627daa4", "organization-access": { "manage-workspaces": true } } } } ``` ### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/organizations/my-organization/teams ``` ### Sample Response The `sso-team-id` attribute is only returned in Terraform Enterprise 202204-1 and later, or in HCP Terraform. ```json { "data": { "attributes": { "name": "team-creation-test", "sso-team-id": "cb265c8e41bddf3f9926b2cf3d190f0e1627daa4", "organization-access": { "manage-policies": false, "manage-policy-overrides": false, "manage-run-tasks": false, "manage-vcs-settings": false, "manage-agent-pools": false, "manage-workspaces": true, "manage-providers": false, "manage-modules": false, "manage-projects": false, "read-projects": false, "read-workspaces": true, "manage-membership": false, "manage-teams": false, "manage-organization-access": false }, "permissions": { "can-update-membership": true, "can-destroy": true, "can-update-organization-access": true, "can-update-api-token": true, "can-update-visibility": true }, "users-count": 0, "visibility": "secret", "allow-member-token-management": true }, "id": "team-6p5jTwJQXwqZBncC", "links": { "self": "/api/v2/teams/team-6p5jTwJQXwqZBncC" }, "relationships": { "authentication-token": { "meta": {} }, "users": { "data": [] } }, "type": "teams" } } ``` ## Show Team Information `GET /teams/:team_id` | Parameter | Description | | ---------- | ------------------------ | | `:team_id` | The team ID to be shown. | ### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/teams/team-6p5jTwJQXwqZBncC ``` ### Sample Response The `sso-team-id` attribute is only returned in Terraform Enterprise 202204-1 and later, or in HCP Terraform. ```json { "data": { "id": "team-6p5jTwJQXwqZBncC", "type": "teams", "attributes": { "name": "team-creation-test", "sso-team-id": "cb265c8e41bddf3f9926b2cf3d190f0e1627daa4", "users-count": 0, "visibility": "organization", "allow-member-token-management": true, "permissions": { "can-update-membership": true, "can-destroy": true, "can-update-organization-access": true, "can-update-api-token": true, "can-update-visibility": true }, "organization-access": { "manage-policies": true, "manage-policy-overrides": false, "manage-run-tasks": true, "manage-workspaces": false, "manage-vcs-settings": false, "manage-agent-pools": false, "manage-providers": false, "manage-modules": false, "manage-projects": false, "read-projects": false, "read-workspaces": false, "manage-membership": false, "manage-teams": false, "manage-organization-access": false } }, "relationships": { "users": { "data": [] }, "authentication-token": { "meta": {} } }, "links": { "self": "/api/v2/teams/team-6p5jTwJQXwqZBncC" } } } ``` ## Update a Team `PATCH /teams/:team_id` | Parameter | Description | | ---------- | -------------------------- | | `:team_id` | The team ID to be updated. | | Status | Response | Reason | | ------- | --------------------------------------- | -------------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "teams"`) | Successfully created a team | | [400][] | [JSON API error object][] | Invalid `include` parameter | | [404][] | [JSON API error object][] | Team not found, or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (missing attributes, wrong types, etc.) | | [500][] | [JSON API error object][] | Failure during team creation | ### Request Body This PATCH endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. -> **Note:** You cannot set `manage-workspaces` to `false` when setting `manage-projects` to `true`, since project permissions cascade down to workspaces. This is also the case for `read-workspaces` and `read-projects`. If `read-projects` is `true`, `read-workspaces` must be `true` as well. | Key path | Type | Default | Description | |-----------------------------------------|--------|------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `data.type` | string | | Must be `"teams"`. | | `data.attributes.name` | string | (previous value) | The name of the team, which can only include letters, numbers, `-`, and `_`. This will be used as an identifier and must be unique in the organization. | | `data.attributes.sso-team-id` | string | (previous value) | The unique identifier of the team from the SAML `MemberOf` attribute. Only available in Terraform Enterprise 202204-1 and later, or in HCP Terraform. | | `data.attributes.organization-access` | object | (previous value) | Settings for the team's organization access. This object can include the `manage-policies`, `manage-policy-overrides`, `manage-run-tasks`, `manage-workspaces`, `manage-vcs-settings`, `manage-agent-pools`, `manage-providers`, `manage-modules`, `manage-projects`, `read-projects`, `read-workspaces`, `manage-membership`, `manage-teams`, and `manage-organization-access` properties with boolean values. All properties default to `false`. | | `data.attributes.visibility` **(beta)** | string | (previous value) | The team's visibility. Must be `"secret"` or `"organization"` (visible). | | `data.attributes.allow-team-token-management` | boolean | (previous value) | The ability to enable and disable team token management for a team. Defaults to true. | ### Sample Payload ```json { "data": { "type": "teams", "attributes": { "visibility": "organization", "allow-member-token-management": true, "organization-access": { "manage-vcs-settings": true } } } } ``` ### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request PATCH \ --data @payload.json \ https://app.terraform.io/api/v2/teams/team-6p5jTwJQXwqZBncC ``` ### Sample Response The `sso-team-id` attribute is only returned in Terraform Enterprise 202204-1 and later, or in HCP Terraform. ```json { "data": { "attributes": { "name": "team-creation-test", "sso-team-id": "cb265c8e41bddf3f9926b2cf3d190f0e1627daa4", "organization-access": { "manage-policies": false, "manage-policy-overrides": false, "manage-run-tasks": true, "manage-vcs-settings": true, "manage-agent-pools": false, "manage-workspaces": true, "manage-providers": false, "manage-modules": false, "manage-projects": false, "read-projects": false, "read-workspaces": true, "manage-membership": false, "manage-teams": false, "manage-organization-access": false }, "visibility": "organization", "allow-member-token-management": true, "permissions": { "can-update-membership": true, "can-destroy": true, "can-update-organization-access": true, "can-update-api-token": true, "can-update-visibility": true }, "users-count": 0 }, "id": "team-6p5jTwJQXwqZBncC", "links": { "self": "/api/v2/teams/team-6p5jTwJQXwqZBncC" }, "relationships": { "authentication-token": { "meta": {} }, "users": { "data": [] } }, "type": "teams" } } ``` ## Delete a Team `DELETE /teams/:team_id` | Parameter | Description | | ---------- | -------------------------- | | `:team_id` | The team ID to be deleted. | ### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request DELETE \ https://app.terraform.io/api/v2/teams/team-6p5jTwJQXwqZBncC ``` ## Available Related Resources The GET endpoints above can optionally return related resources, if requested with [the `include` query parameter](/terraform/cloud-docs/api-docs#inclusion-of-related-resources). The following resource types are available: - `users` (`string`) - Returns the full user record for every member of a team. - `organization-memberships` (`string`) - Returns the full organization membership record for every member of a team.
terraform
page title Teams API Docs HCP Terraform description Use the teams endpoint to manage teams List show create update and delete teams using the HTTP API 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects Teams API The Teams API is used to create edit and destroy teams as well as manage a team s organization level permissions The Team Membership API terraform cloud docs api docs team members is used to add or remove users from a team Use the Team Access API terraform cloud docs api docs team access to associate a team with privileges on an individual workspace BEGIN TFC only name pnp callout include tfc package callouts team management mdx END TFC only name pnp callout Any member of an organization can view visible teams and any secret teams they are a member of Only organization owners can modify teams or view the full set of secret teams The organization token and the owners team token can act as an owner on these endpoints More about permissions terraform cloud docs users teams organizations permissions permissions citation intentionally unused keep for maintainers Organization Membership Note Users must be invited to join organizations before they can be added to teams See the Organization Memberships API documentation terraform cloud docs api docs organization memberships for more information Invited users who have not yet accepted will not appear in Teams API responses List teams GET organizations organization name teams Parameter Description organization name The name of the organization to list teams from The response may identify HashiCorp API service accounts for example api team XXXXXX as a members of a team However API service accounts do not appear in the UI As a result there may be differences between the number of team members reported by the UI and the API For example the UI may report 0 members on a team when and the API reports 1 Query Parameters This endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters Remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs Parameter Description q Optional Allows querying a list of teams by name This search is case insensitive filter names Optional If specified restricts results to a team with a matching name If multiple comma separated values are specified teams matching any of the names are returned page number Optional If omitted the endpoint will return the first page page size Optional If omitted the endpoint will return 20 teams per page Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 organizations my organization teams Sample Response The sso team id attribute is only returned in Terraform Enterprise 202204 1 and later or in HCP Terraform The allow member token management attribute is set to false for Terraform Enterprise versions older than 202408 1 json data id team 6p5jTwJQXwqZBncC type teams attributes name team creation test sso team id cb265c8e41bddf3f9926b2cf3d190f0e1627daa4 users count 0 visibility organization allow member token management true permissions can update membership true can destroy true can update organization access true can update api token true can update visibility true organization access manage policies true manage policy overrides false manage run tasks true manage workspaces false manage vcs settings false manage agent pools false manage projects false read projects false read workspaces false relationships users data authentication token meta links self api v2 teams team 6p5jTwJQXwqZBncC Create a Team POST organizations organization name teams Parameter Description organization name The name of the organization to create the team in The organization must already exist in the system and the user must have permissions to create new teams Status Response Reason 200 JSON API document type teams Successfully created a team 400 JSON API error object Invalid include parameter 404 JSON API error object Organization not found or user unauthorized to perform action 422 JSON API error object Malformed request body missing attributes wrong types etc 500 JSON API error object Failure during team creation Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Note You cannot set manage workspaces to false when setting manage projects to true since project permissions cascade down to workspaces This is also the case for read workspaces and read projects If read projects is true read workspaces must be true as well Key path Type Default Description data type string Must be teams data attributes name string The name of the team which can only include letters numbers and This will be used as an identifier and must be unique in the organization data attributes sso team id string nothing The unique identifier of the team from the SAML MemberOf attribute Only available in Terraform Enterprise 202204 1 and later or in HCP Terraform data attributes organization access object nothing Settings for the team s organization access This object can include the manage policies manage policy overrides manage run tasks manage workspaces manage vcs settings manage agent pools manage providers manage modules manage projects read projects read workspaces manage membership manage teams and manage organization access properties with boolean values All properties default to false data attributes visibility beta string secret The team s visibility Must be secret or organization visible Sample Payload json data type teams attributes name team creation test sso team id cb265c8e41bddf3f9926b2cf3d190f0e1627daa4 organization access manage workspaces true Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 organizations my organization teams Sample Response The sso team id attribute is only returned in Terraform Enterprise 202204 1 and later or in HCP Terraform json data attributes name team creation test sso team id cb265c8e41bddf3f9926b2cf3d190f0e1627daa4 organization access manage policies false manage policy overrides false manage run tasks false manage vcs settings false manage agent pools false manage workspaces true manage providers false manage modules false manage projects false read projects false read workspaces true manage membership false manage teams false manage organization access false permissions can update membership true can destroy true can update organization access true can update api token true can update visibility true users count 0 visibility secret allow member token management true id team 6p5jTwJQXwqZBncC links self api v2 teams team 6p5jTwJQXwqZBncC relationships authentication token meta users data type teams Show Team Information GET teams team id Parameter Description team id The team ID to be shown Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 teams team 6p5jTwJQXwqZBncC Sample Response The sso team id attribute is only returned in Terraform Enterprise 202204 1 and later or in HCP Terraform json data id team 6p5jTwJQXwqZBncC type teams attributes name team creation test sso team id cb265c8e41bddf3f9926b2cf3d190f0e1627daa4 users count 0 visibility organization allow member token management true permissions can update membership true can destroy true can update organization access true can update api token true can update visibility true organization access manage policies true manage policy overrides false manage run tasks true manage workspaces false manage vcs settings false manage agent pools false manage providers false manage modules false manage projects false read projects false read workspaces false manage membership false manage teams false manage organization access false relationships users data authentication token meta links self api v2 teams team 6p5jTwJQXwqZBncC Update a Team PATCH teams team id Parameter Description team id The team ID to be updated Status Response Reason 200 JSON API document type teams Successfully created a team 400 JSON API error object Invalid include parameter 404 JSON API error object Team not found or user unauthorized to perform action 422 JSON API error object Malformed request body missing attributes wrong types etc 500 JSON API error object Failure during team creation Request Body This PATCH endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Note You cannot set manage workspaces to false when setting manage projects to true since project permissions cascade down to workspaces This is also the case for read workspaces and read projects If read projects is true read workspaces must be true as well Key path Type Default Description data type string Must be teams data attributes name string previous value The name of the team which can only include letters numbers and This will be used as an identifier and must be unique in the organization data attributes sso team id string previous value The unique identifier of the team from the SAML MemberOf attribute Only available in Terraform Enterprise 202204 1 and later or in HCP Terraform data attributes organization access object previous value Settings for the team s organization access This object can include the manage policies manage policy overrides manage run tasks manage workspaces manage vcs settings manage agent pools manage providers manage modules manage projects read projects read workspaces manage membership manage teams and manage organization access properties with boolean values All properties default to false data attributes visibility beta string previous value The team s visibility Must be secret or organization visible data attributes allow team token management boolean previous value The ability to enable and disable team token management for a team Defaults to true Sample Payload json data type teams attributes visibility organization allow member token management true organization access manage vcs settings true Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request PATCH data payload json https app terraform io api v2 teams team 6p5jTwJQXwqZBncC Sample Response The sso team id attribute is only returned in Terraform Enterprise 202204 1 and later or in HCP Terraform json data attributes name team creation test sso team id cb265c8e41bddf3f9926b2cf3d190f0e1627daa4 organization access manage policies false manage policy overrides false manage run tasks true manage vcs settings true manage agent pools false manage workspaces true manage providers false manage modules false manage projects false read projects false read workspaces true manage membership false manage teams false manage organization access false visibility organization allow member token management true permissions can update membership true can destroy true can update organization access true can update api token true can update visibility true users count 0 id team 6p5jTwJQXwqZBncC links self api v2 teams team 6p5jTwJQXwqZBncC relationships authentication token meta users data type teams Delete a Team DELETE teams team id Parameter Description team id The team ID to be deleted Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request DELETE https app terraform io api v2 teams team 6p5jTwJQXwqZBncC Available Related Resources The GET endpoints above can optionally return related resources if requested with the include query parameter terraform cloud docs api docs inclusion of related resources The following resource types are available users string Returns the full user record for every member of a team organization memberships string Returns the full organization membership record for every member of a team
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 page title Policy Evaluations API Docs HCP Terraform 404 https developer mozilla org en US docs Web HTTP Status 404 Use the policy evaluations endpoint to manage the Sentinel and OPA policy evaluations performed on a Terraform run List and show policy outcomes and list policy evaluations using the HTTP API
--- page_title: Policy Evaluations - API Docs - HCP Terraform description: >- Use the `/policy-evaluations` endpoint to manage the Sentinel and OPA policy evaluations performed on a Terraform run. List and show policy outcomes and list policy evaluations using the HTTP API. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # Policy Evaluations API Policy evaluations are run within the [HCP Terraform agents](/terraform/cloud-docs/api-docs/agents) in HCP Terraform's infrastructure. Policy evaluations do not have access to cost estimation data. This set of APIs provides endpoints to list and get policy evaluations and policy outcomes. ## List Policy Evaluations in the Task Stage Each run passes through several stages of action (pending, plan, policy check, apply, and completion), and shows the progress through those stages as [run states](/terraform/cloud-docs/run/states). This endpoint allows you to list policy evaluations that are part of the task stage. `GET /task-stages/:task_stage_id/policy-evaluations` | Parameter | Description | | --------------------------- | ------------------------------------------- | | `:task_stage_id` | The task stage ID to get. | | Status | Response | Reason | | ------- | --------------------------------------------- | --------------------------------------------------- | | [200][] | [JSON API document][] | Success | | [404][] | [JSON API error object][] | Task stage not found | ### Query Parameters This endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling does not automatically encode URLs. | Parameter | Description | | ---------------------------------- | ---------------------------------------------------------------------------- | | `page[number]` | **Optional.** If omitted, the endpoint returns the first page. | | `page[size]` | **Optional.** If omitted, the endpoint returns 20 agent pools per page. | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/task-stages/ts-rL5ZsuwfjqfPJcdi/policy-evaluations ``` ### Sample Response ```json { "data":[ { "id":"poleval-8Jj9Hfoz892D9WMX", "type":"policy-evaluations", "attributes":{ "status":"passed", "policy-kind":"opa", "policy-tool-version": "0.44.0", "result-count": { "advisory-failed":0, "errored":0, "mandatory-failed":0, "passed":1 } "status-timestamps":{ "passed-at":"2022-09-16T01:40:30+00:00", "queued-at":"2022-09-16T01:40:04+00:00", "running-at":"2022-09-16T01:40:08+00:00" }, "created-at":"2022-09-16T01:39:07.782Z", "updated-at":"2022-09-16T01:40:30.010Z" }, "relationships":{ "policy-attachable":{ "data":{ "id":"ts-yxskot8Gz5yHa38W", "type":"task-stages" } }, "policy-set-outcomes":{ "links":{ "related":"/api/v2/policy-evaluations/poleval-8Jj9Hfoz892D9WMX/policy-set-outcomes" } } }, "links":{ "self":"/api/v2/policy-evaluations/poleval-8Jj9Hfoz892D9WMX" } } ] } ``` ## List Policy Outcomes `GET /policy-evaluations/:policy_evaluation_id/policy-set-outcomes` | Parameter | Description | | --------------------------- | ---------------------------------------------------------- | | `:policy_evaluation_id` | The ID of the policy evaluation the outcome belongs to get | This endpoint allows you to list policy set outcomes that are part of the policy evaluation. | Status | Response | Reason | | ------- | --------------------------------------------- | ------------------------------------------------------- | | [200][] | [JSON API document][] | Success | | [404][] | [JSON API error object][] | Policy evaluation not found | ### Query Parameters This endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling does not automatically encode URLs. | Parameter | Description | |----------------------------------- | ----------------------------------------------------------------------- | | `page[number]` | **Optional.** If omitted, the endpoint returns the first page. | | `page[size]` | **Optional.** If omitted, the endpoint returns 20 policy sets per page. | | `filter[n][status]` | **Optional.** If omitted, the endpoint returns all policies regardless of status. Must be either "passed", "failed", or "errored". | | `filter[n][enforcementLevel]` | **Optional.** Only used if paired with a non-errored status filter. Must be either "advisory" or "mandatory." | -> **Note**: You can use `filter[n]` to combine combinations of statuses and enforcement levels. Policy outcomes with an errored status do not have an enforcement level. ### Sample Request The following example requests demonstrate how to call the `policy-set-outcomes` endpoint using cuRL. #### All Policy Outcomes The following example call returns all policy set outcomes. ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/policy-evaluations/poleval-8Jj9Hfoz892D9WMX/policy-set-outcomes ``` #### Failed and Errored Policy Outcomes The following example call filters the response so that it only contains failed outcomes and errors. ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/policy-evaluations/poleval-8Jj9Hfoz892D9WMX/policy-set-outcomes?filter[0][status]=errored&filter[1][status]=failed&filter[1][enforcementLevel]=mandatory ``` ### Sample Response The following example response shows that the `policyVCS` policy failed. ```json { "data":[ { "id":"psout-cu8E9a97LBepZZXd", "type":"policy-set-outcomes", "attributes":{ "outcomes":[ { "enforcement_level":"advisory", "query":"data.terraform.main.main", "status":"failed", "policy_name":"policyVCS", "description":"" } ], "error":"", "overridable":true, "policy-set-name":"opa-policies-vcs", "policy-set-description":null, "result-count":{ "advisory-failed":1, "errored":0, "mandatory-failed":0, "passed":0 }, "policy-tool-version": "0.54.0" }, "relationships":{ "policy-evaluation":{ "data":{ "id":"poleval-8Jj9Hfoz892D9WMX", "type":"policy-evaluations" } } } } ], "links":{ "self":"/api/v2/policy-evaluations/poleval-8Jj9Hfoz892D9WMX/policy-set-outcomes?page%5Bnumber%5D=1\u0026page%5Bsize%5D=20", "first":"/api/v2/policy-evaluations/poleval-8Jj9Hfoz892D9WMX/policy-set-outcomes?page%5Bnumber%5D=1\u0026page%5Bsize%5D=20", "prev":null, "next":null, "last":"/api/v2/policy-evaluations/poleval-8Jj9Hfoz892D9WMX/policy-set-outcomes?page%5Bnumber%5D=1\u0026page%5Bsize%5D=20" }, "meta":{ "pagination":{ "current-page":1, "page-size":20, "prev-page":null, "next-page":null, "total-pages":1, "total-count":1 } } } ``` ## Show a Policy Outcome `GET /policy-set-outcomes/:policy_set_outcome_id` | Parameter | Description | | ------------------------ | ----------------------------------------------------------------------------------------------------------------------- | | `:policy_set_outcome_id` | The ID of the policy outcome to show. Refer to [List the Policy Outcomes](#list-policy-outcomes) for reference information about finding IDs. | | Status | Response | Reason | | ------- | ------------------------------------------ | ------------------------------------------------------------------- | | [200][] | [JSON API document][] | The request was successful | | [404][] | [JSON API error object][] | Policy set outcome not found or user unauthorized to perform action | ### Sample Request The following example request gets the outcomes for the `psout-cu8E9a97LBepZZXd` policy set. ```shell curl --request GET \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/policy-set-outcomes/psout-cu8E9a97LBepZZXd ``` ### Sample Response The following example response shows that the `policyVCS` policy failed. ```json { "data":{ "id":"psout-cu8E9a97LBepZZXd", "type":"policy-set-outcomes", "attributes":{ "outcomes":[ { "enforcement_level":"advisory", "query":"data.terraform.main.main", "status":"failed", "policy_name":"policyVCS", "description":"" } ], "error":"", "overridable":true, "policy-set-name":"opa-policies-vcs", "policy-set-description":null, "result-count":{ "advisory-failed":1, "errored":0, "mandatory-failed":0, "passed":0 }, "policy-tool-version": "0.54.0" }, "relationships":{ "policy-evaluation":{ "data":{ "id":"poleval-8Jj9Hfoz892D9WMX", "type":"policy-evaluations" } } } } } ```
terraform
page title Policy Evaluations API Docs HCP Terraform description Use the policy evaluations endpoint to manage the Sentinel and OPA policy evaluations performed on a Terraform run List and show policy outcomes and list policy evaluations using the HTTP API 200 https developer mozilla org en US docs Web HTTP Status 200 404 https developer mozilla org en US docs Web HTTP Status 404 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects Policy Evaluations API Policy evaluations are run within the HCP Terraform agents terraform cloud docs api docs agents in HCP Terraform s infrastructure Policy evaluations do not have access to cost estimation data This set of APIs provides endpoints to list and get policy evaluations and policy outcomes List Policy Evaluations in the Task Stage Each run passes through several stages of action pending plan policy check apply and completion and shows the progress through those stages as run states terraform cloud docs run states This endpoint allows you to list policy evaluations that are part of the task stage GET task stages task stage id policy evaluations Parameter Description task stage id The task stage ID to get Status Response Reason 200 JSON API document Success 404 JSON API error object Task stage not found Query Parameters This endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters Remember to percent encode as 5B and as 5D if your tooling does not automatically encode URLs Parameter Description page number Optional If omitted the endpoint returns the first page page size Optional If omitted the endpoint returns 20 agent pools per page Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 task stages ts rL5ZsuwfjqfPJcdi policy evaluations Sample Response json data id poleval 8Jj9Hfoz892D9WMX type policy evaluations attributes status passed policy kind opa policy tool version 0 44 0 result count advisory failed 0 errored 0 mandatory failed 0 passed 1 status timestamps passed at 2022 09 16T01 40 30 00 00 queued at 2022 09 16T01 40 04 00 00 running at 2022 09 16T01 40 08 00 00 created at 2022 09 16T01 39 07 782Z updated at 2022 09 16T01 40 30 010Z relationships policy attachable data id ts yxskot8Gz5yHa38W type task stages policy set outcomes links related api v2 policy evaluations poleval 8Jj9Hfoz892D9WMX policy set outcomes links self api v2 policy evaluations poleval 8Jj9Hfoz892D9WMX List Policy Outcomes GET policy evaluations policy evaluation id policy set outcomes Parameter Description policy evaluation id The ID of the policy evaluation the outcome belongs to get This endpoint allows you to list policy set outcomes that are part of the policy evaluation Status Response Reason 200 JSON API document Success 404 JSON API error object Policy evaluation not found Query Parameters This endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters Remember to percent encode as 5B and as 5D if your tooling does not automatically encode URLs Parameter Description page number Optional If omitted the endpoint returns the first page page size Optional If omitted the endpoint returns 20 policy sets per page filter n status Optional If omitted the endpoint returns all policies regardless of status Must be either passed failed or errored filter n enforcementLevel Optional Only used if paired with a non errored status filter Must be either advisory or mandatory Note You can use filter n to combine combinations of statuses and enforcement levels Policy outcomes with an errored status do not have an enforcement level Sample Request The following example requests demonstrate how to call the policy set outcomes endpoint using cuRL All Policy Outcomes The following example call returns all policy set outcomes shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 policy evaluations poleval 8Jj9Hfoz892D9WMX policy set outcomes Failed and Errored Policy Outcomes The following example call filters the response so that it only contains failed outcomes and errors shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 policy evaluations poleval 8Jj9Hfoz892D9WMX policy set outcomes filter 0 status errored filter 1 status failed filter 1 enforcementLevel mandatory Sample Response The following example response shows that the policyVCS policy failed json data id psout cu8E9a97LBepZZXd type policy set outcomes attributes outcomes enforcement level advisory query data terraform main main status failed policy name policyVCS description error overridable true policy set name opa policies vcs policy set description null result count advisory failed 1 errored 0 mandatory failed 0 passed 0 policy tool version 0 54 0 relationships policy evaluation data id poleval 8Jj9Hfoz892D9WMX type policy evaluations links self api v2 policy evaluations poleval 8Jj9Hfoz892D9WMX policy set outcomes page 5Bnumber 5D 1 u0026page 5Bsize 5D 20 first api v2 policy evaluations poleval 8Jj9Hfoz892D9WMX policy set outcomes page 5Bnumber 5D 1 u0026page 5Bsize 5D 20 prev null next null last api v2 policy evaluations poleval 8Jj9Hfoz892D9WMX policy set outcomes page 5Bnumber 5D 1 u0026page 5Bsize 5D 20 meta pagination current page 1 page size 20 prev page null next page null total pages 1 total count 1 Show a Policy Outcome GET policy set outcomes policy set outcome id Parameter Description policy set outcome id The ID of the policy outcome to show Refer to List the Policy Outcomes list policy outcomes for reference information about finding IDs Status Response Reason 200 JSON API document The request was successful 404 JSON API error object Policy set outcome not found or user unauthorized to perform action Sample Request The following example request gets the outcomes for the psout cu8E9a97LBepZZXd policy set shell curl request GET H Authorization Bearer TOKEN H Content Type application vnd api json https app terraform io api v2 policy set outcomes psout cu8E9a97LBepZZXd Sample Response The following example response shows that the policyVCS policy failed json data id psout cu8E9a97LBepZZXd type policy set outcomes attributes outcomes enforcement level advisory query data terraform main main status failed policy name policyVCS description error overridable true policy set name opa policies vcs policy set description null result count advisory failed 1 errored 0 mandatory failed 0 passed 0 policy tool version 0 54 0 relationships policy evaluation data id poleval 8Jj9Hfoz892D9WMX type policy evaluations
terraform API Changelog Keep track of changes to the API for HCP Terraform and Terraform Enterprise page title API Changelog API Docs HCP Terraform page id api changelog Learn about the changes made to the HCP Terraform and Enterprise APIs
--- page_title: API Changelog - API Docs - HCP Terraform page_id: api-changelog description: >- Learn about the changes made to the HCP Terraform and Enterprise APIs. --- # API Changelog Keep track of changes to the API for HCP Terraform and Terraform Enterprise. ## 2024-10-15 * Add new documentation for the ability to deprecate, and revert the deprecation of, module versions. Learn more about [Managing module versions](/terraform/cloud-docs/api-docs/private-registry/manage-module-versions). ## 2024-10-14 * Update the [Organizations API](/terraform/cloud-docs/api-docs/organizations) to support the `speculative-plan-management-enabled` attribute, which controls [automatic cancellation of plan-only runs triggered by outdated commits](/terraform/cloud-docs/users-teams-organizations/organizations/vcs-speculative-plan-management). ## 2024-10-11 * Add documentation for new timeframe filter on List endpoints for [Runs](/terraform/cloud-docs/api-docs/run) API ## 2024-09-02 * Add warning about the deprecation and future removal of the [Policy Checks](/terraform/cloud-docs/api-docs/policy-checks) API. ## 2024-08-16 * Fixes Workspace API responses to be consistent and contain all attributes and relationships. ## 2024-08-14 * Add documentation for a new API endpoint that lists an [organization's team tokens](/terraform/cloud-docs/api-docs/team-tokens). ## 2024-08-01 <EnterpriseAlert> This endpoint is exclusive to Terraform Enterprise, and not available in HCP Terraform. </EnterpriseAlert> * Update the [admin settings API](/terraform/enterprise/api-docs/admin/settings##update-general-settings) and [admin organizations API](/terraform/enterprise/api-docs/admin/organizations#update-an-organization) to indicate that the `terraform-build-worker-plan-timeout` and `terraform-build-worker-apply-timeout` attributes are deprecated and will be replaced by `plan-timeout` and `apply-timeout`, respectively. <!-- BEGIN: TFC:only name:audit-trail-tokens --> ## 2024-07-24 * Remove beta tags from documentation for audit trail tokens. <!-- END: TFC:only name:audit-trail-tokens --> ## 2024-07-15 * Update the [Team API](/terraform/cloud-docs/api-docs/teams) to include `allow-member-token-management`. <!-- BEGIN: TFC:only name:audit-trail-tokens --> ## 2024-07-12 * Add beta tags to documentation for audit trail tokens. <!-- END: TFC:only name:audit-trail-tokens --> ## 2024-06-25 * Add API documentation for new [team token management setting](/terraform/cloud-docs/users-teams-organizations/api-tokens). * Update API documentation for the [manage teams permission](/terraform/cloud-docs/users-teams-organizations/permissions#team-management-permissions). ## 2024-05-29 * Add API documentation for the new [audit trails token](/terraform/cloud-docs/api-docs/audit-trails-tokens). ## 2024-05-23 * Update the [registry modules API](/terraform/cloud-docs/api-docs/private-registry/modules#create-a-module-version) for publishing new versions of branch based modules. ## 2024-05-10 * Add API documentation for new [manage agent pools permission](/terraform/cloud-docs/users-teams-organizations/permissions#manage-agent-pools). ## 2024-04-25 * Project names can now be up to 40 characters. ## 2024-04-08 * Add API documentation for new [team management permissions](/terraform/cloud-docs/users-teams-organizations/permissions#team-management-permissions). ## 2024-04-04 * Add a `sort` parameter to the [Projects list API](/terraform/cloud-docs/api-docs/projects#query-parameters) to allow sorting projects by name. * Add a `description` attribute to the [Projects API](/terraform/cloud-docs/api-docs/projects). * Add `project-count` and `workspace-count` attributes to sample [Projects API](/terraform/cloud-docs/api-docs/projects) responses. ## 2024-3-27 * Add `private-vcs` to [Feature Entitlements](/terraform/cloud-docs/api-docs#feature-entitlements). ## 2024-3-26 * Add API documentation for searching [variable sets](/terraform/cloud-docs/api-docs/variable-sets#list-variable-sets) by name. ## 2024-3-14 * Add documentation for creating runs with debugging mode enabled. ## 2024-3-12 * Update OAuth Client API endpoints to create, update, and return projects associated with an oauth client. * Add API endpoints to [Attach an OAuth Client](/terraform/cloud-docs/api-docs/oauth-clients#attach-an-oauth-client-to-projects) and [Detach an OAuth Client](/terraform/cloud-docs/api-docs/oauth-clients#detach-an-oauth-client-from-projects) from a project. * Add `organization-scoped` attribute to the [OAuth Clients API](/terraform/cloud-docs/api-docs/oauth-clients). ## 2024-2-29 * Update [run task stages](/terraform/cloud-docs/api-docs/run-tasks/run-task-stages-and-results) with new multi-stage payload format. * Update [run tasks](/terraform/cloud-docs/api-docs/run-tasks/run-tasks) with global run tasks request/response payloads. ## 2024-2-27 * Add `private-policy-agents` to [Feature Entitlements](/terraform/cloud-docs/api-docs#feature-entitlements). ## 2024-2-20 * Add documentation for configuring organization and workspace data retention policies through the API and on the different [types of data retention policies](/terraform/enterprise/api-docs/data-retention-policies). <!-- BEGIN: TFC:only name:explorer --> ## 2024-2-8 * Add [Explorer API documentation](/terraform/cloud-docs/api-docs/explorer) <!-- END: TFC:only name:explorer --> ## 2024-1-30 * Update the [Audit trails](/terraform/cloud-docs/api-docs/audit-trails) documentation to expand on the payloads for each event. ## 2024-1-24 - Introduce configurable data retention policies at the site-wide level and extend data retention policies at the organization and workspace levels. - Added and/or updated data retention policy documentation to the following topics: - [Admin Settings Documentation](/terraform/enterprise/application-administration/general#data-retention-policies) - [Admin API Documentation](/terraform/enterprise/api-docs/admin/settings#data-retention-policies) - [Organization Documentation](/terraform/enterprise/users-teams-organizations/organizations#data-retention-policies) - [Workspace Documentation](/terraform/enterprise/workspaces/settings/deletion#data-retention-policies) ## 2024-1-4 * Update the [Organizations API](/terraform/cloud-docs/api-docs/organizations) to support the `aggregated-commit-status-enabled` attribute, which controls whether [Aggregated Status Checks](/terraform/cloud-docs/users-teams-organizations/organizations/vcs-status-checks) are enabled. ## 2023-11-17 - Added the [`opa-versions` endpoint](/terraform/enterprise/api-docs/admin/opa-versions) to allow administrators to manage available Open Policy Agent (OPA) versions. - Added the [`sentinel-versions` endpoint](/terraform/enterprise/api-docs/admin/sentinel-versions) to allow administrators to manage available Sentinel versions. - Add `authenticated-resource` relationship to the [`account` API](/terraform/enterprise/api-docs/account). ## 2023-11-15 - Introduce configurable data retention policies at the [organization](/terraform/enterprise/users-teams-organizations/organizations#data-retention-policies) and [workspace](/terraform/enterprise/workspaces/settings/deletion#data-retention-policies) levels. - Added data retention policy documentation to the following topics: - [`state-versions` API documentation](/terraform/enterprise/api-docs/state-versions) - [`configuration-versions` API documentation](/terraform/enterprise/api-docs/configuration-versions) - [Organizations documentation](/terraform/enterprise/users-teams-organizations/organizations#destruction-and-deletion) - [Workspaces documentation](/terraform/enterprise/workspaces/settings/deletion#data-retention-policies) ## 2023-11-07 * Add `auto_destroy_activity_duration` to the [Workspaces API](/terraform/cloud-docs/api-docs/workspaces), which allows Terraform Cloud to schedule auto-destroy runs [based on workspace inactivity](/terraform/cloud-docs/workspaces/settings/deletion#automatically-destroy). ## 2023-10-31 * Update the [Workspaces API](/terraform/cloud-docs/api-docs/workspaces) to support the `auto-apply-run-trigger` attribute, which controls if run trigger runs are auto-applied. ## 2023-10-30 * Add `priority` attribute to the [Variable Sets API](/terraform/cloud-docs/api-docs/variable-sets). ## 2023-10-04 * Updates to [run task integration API](/terraform/cloud-docs/api-docs/run-tasks/run-tasks-integration) * Fix invalid JSON in the example payload. * Clarify the expected JSON:API payload fields. * Add `policy-tool-version` attribute to [Policy Set Outcomes](/terraform/cloud-docs/api-docs/policy-evaluations#list-policy-outcomes). ## 2023-10-03 * Update [Policy Sets API](/terraform/cloud-docs/api-docs/policy-sets) to include `agent-enabled` and `policy-tool-version`. * Update [Policy Evaluations API](/terraform/cloud-docs/api-docs/policy-evaluations) to include `policy-tool-version`. ## 2023-09-29 * Add support for [streamlined run task reviews](/terraform/cloud-docs/integrations/run-tasks), enabling run task integrations to return high fidelity results. * Update the [Terraform cloud run task API](/terraform/cloud-docs/api-docs/run-tasks/run-tasks) to enable streamlined run task reviews. * The [run task integration API](/terraform/cloud-docs/api-docs/run-tasks/run-tasks-integration) now guides integrations through sending rich results. * Updated the run task payload [JSON Schema](https://github.com/hashicorp/terraform-docs-common/blob/main/website/public/schema/run-tasks/runtask-result.json). ## 2023-09-25 * Add `intermediate` boolean attribute to the [State Versions API](/terraform/cloud-docs/api-docs/state-versions). ## 2023-09-19 * Add [failed state upload recovery](/terraform/cloud-docs/api-docs/applies#recover-a-failed-state-upload-after-applying) endpoint. ## 2023-09-15 * Add `auto-destroy-at` attribute to the [Workspaces API](/terraform/cloud-docs/api-docs/workspaces). * Update the [Notification Configurations API](/terraform/cloud-docs/api-docs/notification-configurations) to include [automatic destroy run](/terraform/cloud-docs/api-docs/notification-configurations#automatic-destroy-runs) details. ## 2023-09-08 * Update the [Organizations API](/terraform/cloud-docs/api-docs/organizations) to include `default-execution-mode` and `default-agent-pool`. * Update the [Workspaces API](/terraform/cloud-docs/api-docs/workspaces) to add a `setting-overwrites` object to allow you to overwrite `default-execution-mode` and `default-agent-pool`. ## 2023-09-06 * Update Policy Sets API endpoints to create, update, and return excluded workspaces associated with a policy set. * Add API endpoints to [Attach a Policy Set](/terraform/cloud-docs/api-docs/policy-sets#attach-a-policy-set-to-exclusions) and [Detach a Policy Set](/terraform/cloud-docs/api-docs/policy-sets#detach-a-policy-set-to-exclusions) from excluded workspaces. ## 2023-08-21 * Add `save-plan` attribute, `planned_and_saved` status, and `save_plan` operation type to [Runs endpoints](/terraform/cloud-docs/api-docs/run). ## 2023-08-10 * Add `provisional` to `configuration-versions` endpoint. ## 2023-07-26 * Add support for a `custom` option to the `team_project` access level along with various customizable permissions. The `project-access` permissions apply to the project itself, and `workspace-access` permissions apply to all workspaces within the project. For more information, see [Project Team Access](/terraform/cloud-docs/api-docs/project-team-access). ## 2023-06-09 * Introduce support for [`import` blocks](/terraform/language/import/generating-configuration). * [Runs](/terraform/cloud-docs/api-docs/run#create-a-run) have a new `allow-config-generation` option. * [Plans](/terraform/cloud-docs/api-docs/plans#show-a-plan) have new `resource-imports` and `generated-configuration` properties. * [Applies](/terraform/cloud-docs/api-docs/applies#show-an-apply) have a new `resource-imports` property. * The workspaces associated with a policy set can now be updated using the [Policy Sets PATCH endpoint](/terraform/cloud-docs/api-docs/policy-sets#update-a-policy-set) * Update the [Workspaces](/terraform/cloud-docs/api-docs/workspaces) API endpoints to include the associated [project](/terraform/cloud-docs/api-docs/projects). ## 2023-05-25 * Terraform Cloud sets the `configuration_version_download_url`, `configuration_version_id`, and `workspace_working_directory` properties for all stages of the [Run Task Request](/terraform/enterprise/api-docs/run-tasks/run-tasks-integration#request-body). * Add the new `enforcement-level` property in the request and response of [Policies endpoints](/terraform/cloud-docs/api-docs/policies). * Deprecate the old `enforce` property in the request and response of [Policies endpoints](/terraform/cloud-docs/api-docs/policies). * Add new properties to limit run tasks and policies for the Terraform Cloud free tier. We updated the [entitlement set](/terraform/cloud-docs/api-docs/organizations#show-the-entitlement-set), [feature set](/terraform/cloud-docs/api-docs/feature-sets#sample-response), and [subscription](/terraform/cloud-docs/api-docs/subscriptions#sample-response) endpoints with the following properties: * `run-task-limit` * `run-task-workspace-limit` * `run-task-mandatory-enforcement-limit` * `policy-set-limit` * `policy-limit` * `policy-mandatory-enforcement-limit` * `versioned-policy-set-limit` ## 2023-04-25 * Add the `version-id` property to the response for the Create, List, and Update [Workspace Variables endpoints](/terraform/cloud-docs/api-docs/workspaces-variables). ## 2023-03-30 * Add the `sort` query parameter to the Workspaces API's [list workspaces endpoint](/terraform/cloud-docs/api-docs/workspaces#list-workspaces). ## 2023-03-24 * Update the [Variable Sets](/terraform/cloud-docs/api-docs/variable-sets) API endpoints to include assigning variable sets to projects. ## 2023-03-20 * Add a names filter to the [Projects list API](/terraform/cloud-docs/api-docs/projects#query-parameters) to allow fetching a list of projects by name. ## 2023-03-13 * Update [Project Team Access API](/terraform/cloud-docs/api-docs/project-team-access) to include additional Project roles. * Update [Permissions](/terraform/cloud-docs/users-teams-organizations/permissions) to reflect the decoupling of projects and workspaces in the Organization Permissions UI. ## 2023-03-08 * Introduced the [GitHub App Installation APIs](/terraform/cloud-docs/api-docs/github-app-installations). * Updated [Workspaces API](/terraform/cloud-docs/api-docs/workspaces) to accept `vcs-repo.github-app-installation-id` to connect a workspace to a GitHub App Installation. * Updated [Registry Module API](/terraform/cloud-docs/api-docs/private-registry/modules) to accept `vcs-repo.github-app-installation-id` to connect to a GitHub App Installation. * Updated [Policy Sets API](/terraform/cloud-docs/api-docs/policy-sets) to accept `vcs-repo.github-app-installation-id` to connect to a GitHub App Installation. ## 2023-02-16 * Add `manage-membership` to the organization access settings of the [Team API](/terraform/cloud-docs/api-docs/teams). ## 2023-02-03 * Updated the [List Runs API](/terraform/cloud-docs/api-docs/run#list-runs-in-a-workspace) to note that the filter query parameters accept comma-separated lists. ## 2023-01-18 * Updated the [Team API](/terraform/cloud-docs/api-docs/teams) to include the `read-workspaces` and `read-projects` permissions which grants teams view access to workspaces and projects. ## 2023-01-17 * Add [Projects API](/terraform/cloud-docs/api-docs/projects) for creating, updating and deleting projects. * Add [Project Team Access API](/terraform/cloud-docs/api-docs/project-team-access) for managing access for teams to individual projects. * Update [Workspaces API](/terraform/cloud-docs/api-docs/workspaces) to include examples of creating a workspace in a project and moving a workspace between projects. * Update [List Teams API](/terraform/cloud-docs/api-docs/teams#query-parameters) to accept a search parameter `q`, so that teams can be searched by name. ## 2023-01-12 * Added new rollback to previous state endpoint to [State Versions API](/terraform/cloud-docs/api-docs/state-versions) ## 2022-12-22 * Updated [Safe Delete a workspace](/terraform/cloud-docs/api-docs/workspaces#safe-delete-a-workspace) to fix HTTP verb as `POST`. ## 2022-11-18 * Update [Policies API](/terraform/cloud-docs/api-docs/policies) to fix policy enforcement level defaults. Enforcement level is a required field, so no defaults are available. ## 2022-11-03 * Update [Policy Checks](/terraform/cloud-docs/api-docs/policy-checks) to fix policy set outcome return data type. ### 2022-10-17 * Updated the [Organizations API](/terraform/cloud-docs/api-docs/organizations) with the `allow-force-delete-workspaces`, which controls whether workspace administrators can delete workspaces with resources under management. * Updated the [Workspaces API](/terraform/cloud-docs/api-docs/workspaces) with a safe delete endpoint that guards against deleting workspaces that are managing resources. ### 2022-10-12 * Update [Policy Checks](/terraform/cloud-docs/api-docs/policy-checks) with result counts and support for filtering policy set outcomes. * Update [Team Membership API](/terraform/cloud-docs/api-docs/team-members) to include adding and removing users from teams using organization membership ID. <!-- BEGIN: TFC:only name:opa-policies --> ### 2022-10-06 * Updated the [Policies API](/terraform/cloud-docs/api-docs/policies) with support for Open Policy Agent (OPA) policies. * Update [Policy Sets](/terraform/cloud-docs/api-docs/policy-sets) with support for OPA policy sets. * Updated [Policy Checks](/terraform/cloud-docs/api-docs/policy-checks) to add support for listing policy evaluations and policy set outcomes. * Update [Run Tasks Stage](/terraform/cloud-docs/api-docs/run-tasks/run-task-stages-and-results) to include the new `policy_evaluations` attribute in the output. <!-- END: TFC:only name:opa-policies --> ### 2022-09-21 * Update [State Versions](/terraform/cloud-docs/api-docs/state-versions#create) with optional `json-state-outputs` and `json-state` attributes, which are base-64 encoded external JSON representations of the terraform state. The read-only `hosted-json-state-download-url` attribute links to this version of the state file when available. * Update [State Version Outputs](/terraform/cloud-docs/api-docs/state-version-outputs) with a `detailed-type` attribute, which refines the output with the precise Terraform type. ### 2022-07-26 * Updated the [Run status list](/terraform/cloud-docs/api-docs/run#run-states) with `fetching`, `queuing`, `pre_plan_running` and `pre_plan_completed` * Update [Run Tasks](/terraform/cloud-docs/api-docs/run-tasks.mdx) to include the new `stages` attribute when attaching or updating workspace tasks. * Updated [Run Tasks Integration](/terraform/cloud-docs/api-docs/run-tasks/run-tasks-integration) to specify the different request payloads for different stages. ### 2022-06-23 <!-- BEGIN: TFC:only name:health-assessments --> * Added the [Assessments](/terraform/cloud-docs/api-docs/assessments). * Updated [Workspace](/terraform/cloud-docs/api-docs/workspaces#create-a-workspace) and [Notification Configurations](/terraform/cloud-docs/api-docs/notification-configurations#notification-triggers) to account for assessments. <!-- END: TFC:only name:health-assessments --> * Added new query parameter(s) to [List Runs endpoint](/terraform/cloud-docs/api-docs/run#list-runs-in-a-workspace). ### 2022-06-21 * Updated [Admin Organizations](/terraform/enterprise/api-docs/admin/organizations) endpoints with new `workspace-limit` setting. This is available in Terraform Enterprise v202207-1 and later. * Updated [List Agent Pools](/terraform/cloud-docs/api-docs/agents#list-agent-pools) to accept a filter parameter `filter[allowed_workspaces][name]` so that agent pools can be filtered by name of an associated workspace. The given workspace must be allowed to use the agent pool. Refer to [Scoping Agent Pools to Specific Workspaces](/terraform/cloud-docs/agents#scope-an-agent-pool-to-specific-workspaces). * Added new `organization-scoped` attribute and `allowed-workspaces` relationship to the request/response body of the below endpoints. This is available in Terraform Enterprise v202207-1 and later. * [Show an Agent Pool](/terraform/cloud-docs/api-docs/agents#show-an-agent-pool) * [Create an Agent Pool](/terraform/cloud-docs/api-docs/agents#create-an-agent-pool) * [Update an Agent Pool](/terraform/cloud-docs/api-docs/agents#update-an-agent-pool) ### 2022-06-17 * Updated [Creating a Run Task](/terraform/cloud-docs/workspaces/settings/run-tasks#creating-a-run-task) section to include the new description information for the run task to be configured. * Update [Run Tasks](/terraform/cloud-docs/api-docs/run-tasks.mdx) to include the new description attribute. ### 2022-06-09 * Updated [List Agent Pools](/terraform/cloud-docs/api-docs/agents#list-agent-pools) to accept a search parameter `q`, so that agent pools can be searched by `name`. This is available in Terraform Enterprise v202207-1 and later. * Fixed [List Workspaces](/terraform/cloud-docs/api-docs/workspaces#list-workspaces) to add missing `search[tags]` query parameter. * Updated [List Workspaces](/terraform/cloud-docs/api-docs/workspaces#list-workspaces) to add new `search[exclude_tags]` query parameter. This is available in Terraform Enterprise v202207-1 and later. ### 2022-05-11 * Updated Run Tasks permission to the following endpoints: * [Organizations](/terraform/cloud-docs/api-docs/organizations#list-organizations). * [Team Access](/terraform/cloud-docs/api-docs/team-access#list-team-access-to-a-workspace). * [Teams](/terraform/cloud-docs/api-docs/teams#list-teams). ### 2022-05-04 * Updated [Feature Sets](/terraform/cloud-docs/api-docs/feature-sets#list-feature-sets) to add new `run-tasks` attribute. ### 2022-05-03 * Added Run Tasks permission to the following endpoints: * [Organizations](/terraform/cloud-docs/api-docs/organizations#list-organizations) * [Workspaces](/terraform/cloud-docs/api-docs/workspaces#show-workspace) ### 2022-04-29 * Updated [Run Tasks Integration](/terraform/cloud-docs/api-docs/run-tasks/run-tasks-integration) to specify the allowed `status` attribute values. * Updated [Organization Memberships](/terraform/cloud-docs/api-docs/organization-memberships#query-parameters) to add new `filter[email]` query parameter. * Updated [Teams](/terraform/cloud-docs/api-docs/teams#query-parameters) to add new `filter[names]` query parameter. ### 2022-04-04 * Added the [Run Tasks Integration](/terraform/cloud-docs/api-docs/run-tasks/run-tasks-integration) endpoint. ### 2022-03-14 * Added the [Download Configuration Files](/terraform/cloud-docs/api-docs/configuration-versions#download-configuration-files) endpoints. ### 2022-03-11 * Introduced [Archiving Configuration Versions](/terraform/cloud-docs/workspaces/configurations#archiving-configuration-versions). * Updated [Configuration Versions](/terraform/cloud-docs/api-docs/configuration-versions#attributes) to add new `fetching` and `archived` states. * Updated [Runs](/terraform/cloud-docs/api-docs/run#attributes) to add new `fetching` state. * Added the [Archive a Configuration Version](/terraform/cloud-docs/api-docs/configuration-versions#archive-a-configuration-version) endpoint. ### 2022-02-25 * Updated [Workspace Run Tasks](/terraform/cloud-docs/api-docs/run-tasks/run-tasks#show-a-run-task) to add new `enabled`attribute. ### 2022-02-28 * Introduced the [Registry Providers](/terraform/cloud-docs/api-docs/private-registry/providers) endpoints to manage private providers for a private registry. ### 2021-12-09 * Added `variables` field for POST /runs and the run resource, enabling run-specific variable values. ### 2021-12-03 * OAuth API updated to handle `secret` and `rsa_public_key` fields for POST/PUT. ### 2021-11-17 * Added pagination support to the following endpoints: * [Feature Sets](/terraform/cloud-docs/api-docs/feature-sets#list-feature-sets) - `GET /feature-sets` * [Notification Configurations](/terraform/cloud-docs/api-docs/notification-configurations#list-notification-configurations) - `GET /workspaces/:workspace_id/notification-configurations` * [Oauth Clients](/terraform/cloud-docs/api-docs/oauth-clients#list-oauth-clients) - `GET /organizations/:organization_name/oauth-clients` * [Oauth Tokens](/terraform/cloud-docs/api-docs/oauth-tokens#list-oauth-tokens) - `GET /oauth-clients/:oauth_client_id/oauth-tokens` * [Organization Feature Sets](/terraform/cloud-docs/api-docs/feature-sets#list-feature-sets-for-organization) - `GET /organizations/:organization_name/feature-sets` * [Organizations](/terraform/cloud-docs/api-docs/organizations#list-organizations) - `GET /organizations` * [Policy Checks](/terraform/cloud-docs/api-docs/policy-checks#list-policy-checks) - `GET /runs/:run_id/policy-checks` * [Policy Set Parameters](/terraform/cloud-docs/api-docs/policy-set-params#list-parameters) - `GET /policy-sets/:policy_set_id/parameters` * [SSH Keys](/terraform/cloud-docs/api-docs/ssh-keys#list-ssh-keys) - `GET /organizations/:organization_name/ssh-keys` * [User Tokens](/terraform/cloud-docs/api-docs/user-tokens#list-user-tokens) - `GET /users/:user_id/authentication-tokens` ### 2021-11-11 * Introduced the [Variable Sets](/terraform/cloud-docs/api-docs/variable-sets) endpoints for viewing and administering Variable Sets ### 2021-11-18 * Introduced the [Registry Providers](/terraform/cloud-docs/api-docs/private-registry/providers) endpoint to manage public providers for a private registry. These endpoints will be available in the following Terraform Enterprise Release: `v202112-1` ### 2021-09-12 * Added [Run Tasks Stages and Results](/terraform/cloud-docs/api-docs/run-tasks/run-task-stages-and-results) endpoint. ### 2021-08-18 * Introduced the [State Version Outputs](/terraform/cloud-docs/api-docs/state-versions) endpoint to retrieve the Outputs for a given State Version ### 2021-08-11 * **BREAKING CHANGE:** Security fix to [Configuration versions](/terraform/cloud-docs/api-docs/configuration-versions): upload-url attribute for [uploading configuration files](/terraform/cloud-docs/api-docs/configuration-versions#upload-configuration-files) is now only available on the create response. ### 2021-07-30 * Introduced Workspace Tagging * Updated [Workspaces](/terraform/cloud-docs/api-docs/workspaces): * added `tag-names` attribute. * added `POST /workspaces/:workspace_id/relationships/tags` * added `DELETE /workspaces/:workspace_id/relationships/tags` * Added [Organization Tags](/terraform/cloud-docs/api-docs/organization-tags). * Added `tags` attribute to [`tfrun`](/terraform/cloud-docs/policy-enforcement/sentinel/import/tfrun) ### 2021-07-19 * [Notification configurations](/terraform/cloud-docs/api-docs/notification-configurations): Gave organization tokens permission to create and manage notification configurations. ### 2021-07-09 * [State versions](/terraform/cloud-docs/api-docs/state-versions): Fixed the ID format for the workspace relationship of a state version. Previously, the reported ID was unusable due to a bug. * [Workspaces](/terraform/cloud-docs/api-docs/workspaces): Added `locked_by` as an includable related resource. * Added [Run Tasks](/terraform/cloud-docs/api-docs/run-tasks/run-tasks) API endpoint. ### 2021-06-8 * Updated [Registry Module APIs](/terraform/cloud-docs/api-docs/private-registry/modules). * added `registry_name` scoped APIs. * added `organization_name` scoped APIs. * added [Module List API](/terraform/cloud-docs/api-docs/private-registry/modules#list-registry-modules-for-an-organization). * updated [Module Delete APIs](/terraform/cloud-docs/api-docs/private-registry/modules#delete-a-module) (see deprecation note below). * **CLOUD**: added public registry module related APIs. * **DEPRECATION**: The following [Registry Module APIs](/terraform/cloud-docs/api-docs/private-registry/modules) have been replaced with newer apis and will be removed in the future. * The following endpoints to delete modules are replaced with [Module Delete APIs](/terraform/cloud-docs/api-docs/private-registry/modules#delete-a-module) * `POST /registry-modules/actions/delete/:organization_name/:name/:provider/:version` replaced with `DELETE /organizations/:organization_name/registry-modules/:registry_name/:namespace/:name/:provider/:version` * `POST /registry-modules/actions/delete/:organization_name/:name/:provider` replaced with `DELETE /organizations/:organization_name/registry-modules/:registry_name/:namespace/:name/:provider` * `POST /registry-modules/actions/delete/:organization_name/:name` replaced with `DELETE /organizations/:organization_name/registry-modules/:registry_name/:namespace/:name` * `POST /registry-modules` replaced with [`POST /organizations/:organization_name/registry-modules/vcs`](/terraform/cloud-docs/api-docs/private-registry/modules#publish-a-private-module-from-a-vcs) * `POST /registry-modules/:organization_name/:name/:provider/versions` replaced with [`POST /organizations/:organization_name/registry-modules/:registry_name/:namespace/:name/:provider/versions`](/terraform/cloud-docs/api-docs/private-registry/modules#create-a-module-version) * `GET /registry-modules/show/:organization_name/:name/:provider` replaced with [`GET /organizations/:organization_name/registry-modules/:registry_name/:namespace/:name/:provider`](/terraform/cloud-docs/api-docs/private-registry/modules#get-a-module) ### 2021-05-27 * **CLOUD**: [Agents](/terraform/cloud-docs/api-docs/agents): added [delete endpoint](/terraform/cloud-docs/api-docs/agents#delete-an-agent). ### 2021-05-19 * [Runs](/terraform/cloud-docs/api-docs/run): added `refresh`, `refresh-only`, and `replace-addrs` attributes. ### 2021-04-16 * Introduced [Controlled Remote State Access](https://www.hashicorp.com/blog/announcing-controlled-remote-state-access-for-terraform-cloud-and-enterprise). * [Admin Settings](/terraform/enterprise/api-docs/admin/settings): added `default-remote-state-access` attribute. * [Workspaces](/terraform/cloud-docs/api-docs/workspaces): * added `global-remote-state` attribute. * added [Remote State Consumers](/terraform/cloud-docs/api-docs/workspaces#get-remote-state-consumers) relationship. ### 2021-04-13 * [Teams](/terraform/cloud-docs/api-docs/teams): added `manage-policy-overrides` property to the `organization-access` attribute. ### 2021-03-23 * **ENTERPRISE**: `v202103-1` Introduced [Share Modules Across Organizations with Terraform Enterprise](https://www.hashicorp.com/blog/share-modules-across-organizations-terraform-enterprise). * [Admin Organizations](/terraform/enterprise/api-docs/admin/organizations): * added new query parameters to [List all Organizations endpoint](/terraform/enterprise/api-docs/admin/organizations#query-parameters) * added module-consumers link in `relationships` response * added [update module consumers endpoint](/terraform/enterprise/api-docs/admin/organizations#update-an-organization-39-s-module-consumers) * added [list module consumers endpoint](/terraform/enterprise/api-docs/admin/organizations#list-module-consumers-for-an-organization) * [Organizations](/terraform/cloud-docs/api-docs/organizations): added [Module Producers](/terraform/cloud-docs/api-docs/organizations#show-module-producers) * **DEPRECATION**: [Admin Module Sharing](/terraform/enterprise/api-docs/admin/module-sharing): is replaced with a new JSON::Api compliant [endpoint](/terraform/enterprise/api-docs/admin/organizations#update-an-organization-39-s-module-consumers) ### 2021-03-18 * **CLOUD**: Introduced [New Workspace Overview for Terraform Cloud](https://www.hashicorp.com/blog/new-workspace-overview-for-terraform-cloud). * [Workspaces](/terraform/cloud-docs/api-docs/workspaces): * added `resource-count` and `updated-at` attributes. * added [performance attributes](/terraform/cloud-docs/api-docs/workspaces#workspace-performance-attributes) (`apply-duration-average`, `plan-duration-average`, `policy-check-failures`, `run-failures`, `workspaces-kpis-run-count`). * added `readme` and `outputs` [related resources](/terraform/cloud-docs/api-docs/workspaces#available-related-resources). * [Team Access](/terraform/cloud-docs/api-docs/team-access): updated to support pagination. ### 2021-03-11 * Added [VCS Events](/terraform/cloud-docs/api-docs/vcs-events), limited to GitLab.com connections. ### 2021-03-08 * [Workspaces](/terraform/cloud-docs/api-docs/workspaces): added `current_configuration_version` and `current_configuration_version.ingress_attributes` as includable related resources.
terraform
page title API Changelog API Docs HCP Terraform page id api changelog description Learn about the changes made to the HCP Terraform and Enterprise APIs API Changelog Keep track of changes to the API for HCP Terraform and Terraform Enterprise 2024 10 15 Add new documentation for the ability to deprecate and revert the deprecation of module versions Learn more about Managing module versions terraform cloud docs api docs private registry manage module versions 2024 10 14 Update the Organizations API terraform cloud docs api docs organizations to support the speculative plan management enabled attribute which controls automatic cancellation of plan only runs triggered by outdated commits terraform cloud docs users teams organizations organizations vcs speculative plan management 2024 10 11 Add documentation for new timeframe filter on List endpoints for Runs terraform cloud docs api docs run API 2024 09 02 Add warning about the deprecation and future removal of the Policy Checks terraform cloud docs api docs policy checks API 2024 08 16 Fixes Workspace API responses to be consistent and contain all attributes and relationships 2024 08 14 Add documentation for a new API endpoint that lists an organization s team tokens terraform cloud docs api docs team tokens 2024 08 01 EnterpriseAlert This endpoint is exclusive to Terraform Enterprise and not available in HCP Terraform EnterpriseAlert Update the admin settings API terraform enterprise api docs admin settings update general settings and admin organizations API terraform enterprise api docs admin organizations update an organization to indicate that the terraform build worker plan timeout and terraform build worker apply timeout attributes are deprecated and will be replaced by plan timeout and apply timeout respectively BEGIN TFC only name audit trail tokens 2024 07 24 Remove beta tags from documentation for audit trail tokens END TFC only name audit trail tokens 2024 07 15 Update the Team API terraform cloud docs api docs teams to include allow member token management BEGIN TFC only name audit trail tokens 2024 07 12 Add beta tags to documentation for audit trail tokens END TFC only name audit trail tokens 2024 06 25 Add API documentation for new team token management setting terraform cloud docs users teams organizations api tokens Update API documentation for the manage teams permission terraform cloud docs users teams organizations permissions team management permissions 2024 05 29 Add API documentation for the new audit trails token terraform cloud docs api docs audit trails tokens 2024 05 23 Update the registry modules API terraform cloud docs api docs private registry modules create a module version for publishing new versions of branch based modules 2024 05 10 Add API documentation for new manage agent pools permission terraform cloud docs users teams organizations permissions manage agent pools 2024 04 25 Project names can now be up to 40 characters 2024 04 08 Add API documentation for new team management permissions terraform cloud docs users teams organizations permissions team management permissions 2024 04 04 Add a sort parameter to the Projects list API terraform cloud docs api docs projects query parameters to allow sorting projects by name Add a description attribute to the Projects API terraform cloud docs api docs projects Add project count and workspace count attributes to sample Projects API terraform cloud docs api docs projects responses 2024 3 27 Add private vcs to Feature Entitlements terraform cloud docs api docs feature entitlements 2024 3 26 Add API documentation for searching variable sets terraform cloud docs api docs variable sets list variable sets by name 2024 3 14 Add documentation for creating runs with debugging mode enabled 2024 3 12 Update OAuth Client API endpoints to create update and return projects associated with an oauth client Add API endpoints to Attach an OAuth Client terraform cloud docs api docs oauth clients attach an oauth client to projects and Detach an OAuth Client terraform cloud docs api docs oauth clients detach an oauth client from projects from a project Add organization scoped attribute to the OAuth Clients API terraform cloud docs api docs oauth clients 2024 2 29 Update run task stages terraform cloud docs api docs run tasks run task stages and results with new multi stage payload format Update run tasks terraform cloud docs api docs run tasks run tasks with global run tasks request response payloads 2024 2 27 Add private policy agents to Feature Entitlements terraform cloud docs api docs feature entitlements 2024 2 20 Add documentation for configuring organization and workspace data retention policies through the API and on the different types of data retention policies terraform enterprise api docs data retention policies BEGIN TFC only name explorer 2024 2 8 Add Explorer API documentation terraform cloud docs api docs explorer END TFC only name explorer 2024 1 30 Update the Audit trails terraform cloud docs api docs audit trails documentation to expand on the payloads for each event 2024 1 24 Introduce configurable data retention policies at the site wide level and extend data retention policies at the organization and workspace levels Added and or updated data retention policy documentation to the following topics Admin Settings Documentation terraform enterprise application administration general data retention policies Admin API Documentation terraform enterprise api docs admin settings data retention policies Organization Documentation terraform enterprise users teams organizations organizations data retention policies Workspace Documentation terraform enterprise workspaces settings deletion data retention policies 2024 1 4 Update the Organizations API terraform cloud docs api docs organizations to support the aggregated commit status enabled attribute which controls whether Aggregated Status Checks terraform cloud docs users teams organizations organizations vcs status checks are enabled 2023 11 17 Added the opa versions endpoint terraform enterprise api docs admin opa versions to allow administrators to manage available Open Policy Agent OPA versions Added the sentinel versions endpoint terraform enterprise api docs admin sentinel versions to allow administrators to manage available Sentinel versions Add authenticated resource relationship to the account API terraform enterprise api docs account 2023 11 15 Introduce configurable data retention policies at the organization terraform enterprise users teams organizations organizations data retention policies and workspace terraform enterprise workspaces settings deletion data retention policies levels Added data retention policy documentation to the following topics state versions API documentation terraform enterprise api docs state versions configuration versions API documentation terraform enterprise api docs configuration versions Organizations documentation terraform enterprise users teams organizations organizations destruction and deletion Workspaces documentation terraform enterprise workspaces settings deletion data retention policies 2023 11 07 Add auto destroy activity duration to the Workspaces API terraform cloud docs api docs workspaces which allows Terraform Cloud to schedule auto destroy runs based on workspace inactivity terraform cloud docs workspaces settings deletion automatically destroy 2023 10 31 Update the Workspaces API terraform cloud docs api docs workspaces to support the auto apply run trigger attribute which controls if run trigger runs are auto applied 2023 10 30 Add priority attribute to the Variable Sets API terraform cloud docs api docs variable sets 2023 10 04 Updates to run task integration API terraform cloud docs api docs run tasks run tasks integration Fix invalid JSON in the example payload Clarify the expected JSON API payload fields Add policy tool version attribute to Policy Set Outcomes terraform cloud docs api docs policy evaluations list policy outcomes 2023 10 03 Update Policy Sets API terraform cloud docs api docs policy sets to include agent enabled and policy tool version Update Policy Evaluations API terraform cloud docs api docs policy evaluations to include policy tool version 2023 09 29 Add support for streamlined run task reviews terraform cloud docs integrations run tasks enabling run task integrations to return high fidelity results Update the Terraform cloud run task API terraform cloud docs api docs run tasks run tasks to enable streamlined run task reviews The run task integration API terraform cloud docs api docs run tasks run tasks integration now guides integrations through sending rich results Updated the run task payload JSON Schema https github com hashicorp terraform docs common blob main website public schema run tasks runtask result json 2023 09 25 Add intermediate boolean attribute to the State Versions API terraform cloud docs api docs state versions 2023 09 19 Add failed state upload recovery terraform cloud docs api docs applies recover a failed state upload after applying endpoint 2023 09 15 Add auto destroy at attribute to the Workspaces API terraform cloud docs api docs workspaces Update the Notification Configurations API terraform cloud docs api docs notification configurations to include automatic destroy run terraform cloud docs api docs notification configurations automatic destroy runs details 2023 09 08 Update the Organizations API terraform cloud docs api docs organizations to include default execution mode and default agent pool Update the Workspaces API terraform cloud docs api docs workspaces to add a setting overwrites object to allow you to overwrite default execution mode and default agent pool 2023 09 06 Update Policy Sets API endpoints to create update and return excluded workspaces associated with a policy set Add API endpoints to Attach a Policy Set terraform cloud docs api docs policy sets attach a policy set to exclusions and Detach a Policy Set terraform cloud docs api docs policy sets detach a policy set to exclusions from excluded workspaces 2023 08 21 Add save plan attribute planned and saved status and save plan operation type to Runs endpoints terraform cloud docs api docs run 2023 08 10 Add provisional to configuration versions endpoint 2023 07 26 Add support for a custom option to the team project access level along with various customizable permissions The project access permissions apply to the project itself and workspace access permissions apply to all workspaces within the project For more information see Project Team Access terraform cloud docs api docs project team access 2023 06 09 Introduce support for import blocks terraform language import generating configuration Runs terraform cloud docs api docs run create a run have a new allow config generation option Plans terraform cloud docs api docs plans show a plan have new resource imports and generated configuration properties Applies terraform cloud docs api docs applies show an apply have a new resource imports property The workspaces associated with a policy set can now be updated using the Policy Sets PATCH endpoint terraform cloud docs api docs policy sets update a policy set Update the Workspaces terraform cloud docs api docs workspaces API endpoints to include the associated project terraform cloud docs api docs projects 2023 05 25 Terraform Cloud sets the configuration version download url configuration version id and workspace working directory properties for all stages of the Run Task Request terraform enterprise api docs run tasks run tasks integration request body Add the new enforcement level property in the request and response of Policies endpoints terraform cloud docs api docs policies Deprecate the old enforce property in the request and response of Policies endpoints terraform cloud docs api docs policies Add new properties to limit run tasks and policies for the Terraform Cloud free tier We updated the entitlement set terraform cloud docs api docs organizations show the entitlement set feature set terraform cloud docs api docs feature sets sample response and subscription terraform cloud docs api docs subscriptions sample response endpoints with the following properties run task limit run task workspace limit run task mandatory enforcement limit policy set limit policy limit policy mandatory enforcement limit versioned policy set limit 2023 04 25 Add the version id property to the response for the Create List and Update Workspace Variables endpoints terraform cloud docs api docs workspaces variables 2023 03 30 Add the sort query parameter to the Workspaces API s list workspaces endpoint terraform cloud docs api docs workspaces list workspaces 2023 03 24 Update the Variable Sets terraform cloud docs api docs variable sets API endpoints to include assigning variable sets to projects 2023 03 20 Add a names filter to the Projects list API terraform cloud docs api docs projects query parameters to allow fetching a list of projects by name 2023 03 13 Update Project Team Access API terraform cloud docs api docs project team access to include additional Project roles Update Permissions terraform cloud docs users teams organizations permissions to reflect the decoupling of projects and workspaces in the Organization Permissions UI 2023 03 08 Introduced the GitHub App Installation APIs terraform cloud docs api docs github app installations Updated Workspaces API terraform cloud docs api docs workspaces to accept vcs repo github app installation id to connect a workspace to a GitHub App Installation Updated Registry Module API terraform cloud docs api docs private registry modules to accept vcs repo github app installation id to connect to a GitHub App Installation Updated Policy Sets API terraform cloud docs api docs policy sets to accept vcs repo github app installation id to connect to a GitHub App Installation 2023 02 16 Add manage membership to the organization access settings of the Team API terraform cloud docs api docs teams 2023 02 03 Updated the List Runs API terraform cloud docs api docs run list runs in a workspace to note that the filter query parameters accept comma separated lists 2023 01 18 Updated the Team API terraform cloud docs api docs teams to include the read workspaces and read projects permissions which grants teams view access to workspaces and projects 2023 01 17 Add Projects API terraform cloud docs api docs projects for creating updating and deleting projects Add Project Team Access API terraform cloud docs api docs project team access for managing access for teams to individual projects Update Workspaces API terraform cloud docs api docs workspaces to include examples of creating a workspace in a project and moving a workspace between projects Update List Teams API terraform cloud docs api docs teams query parameters to accept a search parameter q so that teams can be searched by name 2023 01 12 Added new rollback to previous state endpoint to State Versions API terraform cloud docs api docs state versions 2022 12 22 Updated Safe Delete a workspace terraform cloud docs api docs workspaces safe delete a workspace to fix HTTP verb as POST 2022 11 18 Update Policies API terraform cloud docs api docs policies to fix policy enforcement level defaults Enforcement level is a required field so no defaults are available 2022 11 03 Update Policy Checks terraform cloud docs api docs policy checks to fix policy set outcome return data type 2022 10 17 Updated the Organizations API terraform cloud docs api docs organizations with the allow force delete workspaces which controls whether workspace administrators can delete workspaces with resources under management Updated the Workspaces API terraform cloud docs api docs workspaces with a safe delete endpoint that guards against deleting workspaces that are managing resources 2022 10 12 Update Policy Checks terraform cloud docs api docs policy checks with result counts and support for filtering policy set outcomes Update Team Membership API terraform cloud docs api docs team members to include adding and removing users from teams using organization membership ID BEGIN TFC only name opa policies 2022 10 06 Updated the Policies API terraform cloud docs api docs policies with support for Open Policy Agent OPA policies Update Policy Sets terraform cloud docs api docs policy sets with support for OPA policy sets Updated Policy Checks terraform cloud docs api docs policy checks to add support for listing policy evaluations and policy set outcomes Update Run Tasks Stage terraform cloud docs api docs run tasks run task stages and results to include the new policy evaluations attribute in the output END TFC only name opa policies 2022 09 21 Update State Versions terraform cloud docs api docs state versions create with optional json state outputs and json state attributes which are base 64 encoded external JSON representations of the terraform state The read only hosted json state download url attribute links to this version of the state file when available Update State Version Outputs terraform cloud docs api docs state version outputs with a detailed type attribute which refines the output with the precise Terraform type 2022 07 26 Updated the Run status list terraform cloud docs api docs run run states with fetching queuing pre plan running and pre plan completed Update Run Tasks terraform cloud docs api docs run tasks mdx to include the new stages attribute when attaching or updating workspace tasks Updated Run Tasks Integration terraform cloud docs api docs run tasks run tasks integration to specify the different request payloads for different stages 2022 06 23 BEGIN TFC only name health assessments Added the Assessments terraform cloud docs api docs assessments Updated Workspace terraform cloud docs api docs workspaces create a workspace and Notification Configurations terraform cloud docs api docs notification configurations notification triggers to account for assessments END TFC only name health assessments Added new query parameter s to List Runs endpoint terraform cloud docs api docs run list runs in a workspace 2022 06 21 Updated Admin Organizations terraform enterprise api docs admin organizations endpoints with new workspace limit setting This is available in Terraform Enterprise v202207 1 and later Updated List Agent Pools terraform cloud docs api docs agents list agent pools to accept a filter parameter filter allowed workspaces name so that agent pools can be filtered by name of an associated workspace The given workspace must be allowed to use the agent pool Refer to Scoping Agent Pools to Specific Workspaces terraform cloud docs agents scope an agent pool to specific workspaces Added new organization scoped attribute and allowed workspaces relationship to the request response body of the below endpoints This is available in Terraform Enterprise v202207 1 and later Show an Agent Pool terraform cloud docs api docs agents show an agent pool Create an Agent Pool terraform cloud docs api docs agents create an agent pool Update an Agent Pool terraform cloud docs api docs agents update an agent pool 2022 06 17 Updated Creating a Run Task terraform cloud docs workspaces settings run tasks creating a run task section to include the new description information for the run task to be configured Update Run Tasks terraform cloud docs api docs run tasks mdx to include the new description attribute 2022 06 09 Updated List Agent Pools terraform cloud docs api docs agents list agent pools to accept a search parameter q so that agent pools can be searched by name This is available in Terraform Enterprise v202207 1 and later Fixed List Workspaces terraform cloud docs api docs workspaces list workspaces to add missing search tags query parameter Updated List Workspaces terraform cloud docs api docs workspaces list workspaces to add new search exclude tags query parameter This is available in Terraform Enterprise v202207 1 and later 2022 05 11 Updated Run Tasks permission to the following endpoints Organizations terraform cloud docs api docs organizations list organizations Team Access terraform cloud docs api docs team access list team access to a workspace Teams terraform cloud docs api docs teams list teams 2022 05 04 Updated Feature Sets terraform cloud docs api docs feature sets list feature sets to add new run tasks attribute 2022 05 03 Added Run Tasks permission to the following endpoints Organizations terraform cloud docs api docs organizations list organizations Workspaces terraform cloud docs api docs workspaces show workspace 2022 04 29 Updated Run Tasks Integration terraform cloud docs api docs run tasks run tasks integration to specify the allowed status attribute values Updated Organization Memberships terraform cloud docs api docs organization memberships query parameters to add new filter email query parameter Updated Teams terraform cloud docs api docs teams query parameters to add new filter names query parameter 2022 04 04 Added the Run Tasks Integration terraform cloud docs api docs run tasks run tasks integration endpoint 2022 03 14 Added the Download Configuration Files terraform cloud docs api docs configuration versions download configuration files endpoints 2022 03 11 Introduced Archiving Configuration Versions terraform cloud docs workspaces configurations archiving configuration versions Updated Configuration Versions terraform cloud docs api docs configuration versions attributes to add new fetching and archived states Updated Runs terraform cloud docs api docs run attributes to add new fetching state Added the Archive a Configuration Version terraform cloud docs api docs configuration versions archive a configuration version endpoint 2022 02 25 Updated Workspace Run Tasks terraform cloud docs api docs run tasks run tasks show a run task to add new enabled attribute 2022 02 28 Introduced the Registry Providers terraform cloud docs api docs private registry providers endpoints to manage private providers for a private registry 2021 12 09 Added variables field for POST runs and the run resource enabling run specific variable values 2021 12 03 OAuth API updated to handle secret and rsa public key fields for POST PUT 2021 11 17 Added pagination support to the following endpoints Feature Sets terraform cloud docs api docs feature sets list feature sets GET feature sets Notification Configurations terraform cloud docs api docs notification configurations list notification configurations GET workspaces workspace id notification configurations Oauth Clients terraform cloud docs api docs oauth clients list oauth clients GET organizations organization name oauth clients Oauth Tokens terraform cloud docs api docs oauth tokens list oauth tokens GET oauth clients oauth client id oauth tokens Organization Feature Sets terraform cloud docs api docs feature sets list feature sets for organization GET organizations organization name feature sets Organizations terraform cloud docs api docs organizations list organizations GET organizations Policy Checks terraform cloud docs api docs policy checks list policy checks GET runs run id policy checks Policy Set Parameters terraform cloud docs api docs policy set params list parameters GET policy sets policy set id parameters SSH Keys terraform cloud docs api docs ssh keys list ssh keys GET organizations organization name ssh keys User Tokens terraform cloud docs api docs user tokens list user tokens GET users user id authentication tokens 2021 11 11 Introduced the Variable Sets terraform cloud docs api docs variable sets endpoints for viewing and administering Variable Sets 2021 11 18 Introduced the Registry Providers terraform cloud docs api docs private registry providers endpoint to manage public providers for a private registry These endpoints will be available in the following Terraform Enterprise Release v202112 1 2021 09 12 Added Run Tasks Stages and Results terraform cloud docs api docs run tasks run task stages and results endpoint 2021 08 18 Introduced the State Version Outputs terraform cloud docs api docs state versions endpoint to retrieve the Outputs for a given State Version 2021 08 11 BREAKING CHANGE Security fix to Configuration versions terraform cloud docs api docs configuration versions upload url attribute for uploading configuration files terraform cloud docs api docs configuration versions upload configuration files is now only available on the create response 2021 07 30 Introduced Workspace Tagging Updated Workspaces terraform cloud docs api docs workspaces added tag names attribute added POST workspaces workspace id relationships tags added DELETE workspaces workspace id relationships tags Added Organization Tags terraform cloud docs api docs organization tags Added tags attribute to tfrun terraform cloud docs policy enforcement sentinel import tfrun 2021 07 19 Notification configurations terraform cloud docs api docs notification configurations Gave organization tokens permission to create and manage notification configurations 2021 07 09 State versions terraform cloud docs api docs state versions Fixed the ID format for the workspace relationship of a state version Previously the reported ID was unusable due to a bug Workspaces terraform cloud docs api docs workspaces Added locked by as an includable related resource Added Run Tasks terraform cloud docs api docs run tasks run tasks API endpoint 2021 06 8 Updated Registry Module APIs terraform cloud docs api docs private registry modules added registry name scoped APIs added organization name scoped APIs added Module List API terraform cloud docs api docs private registry modules list registry modules for an organization updated Module Delete APIs terraform cloud docs api docs private registry modules delete a module see deprecation note below CLOUD added public registry module related APIs DEPRECATION The following Registry Module APIs terraform cloud docs api docs private registry modules have been replaced with newer apis and will be removed in the future The following endpoints to delete modules are replaced with Module Delete APIs terraform cloud docs api docs private registry modules delete a module POST registry modules actions delete organization name name provider version replaced with DELETE organizations organization name registry modules registry name namespace name provider version POST registry modules actions delete organization name name provider replaced with DELETE organizations organization name registry modules registry name namespace name provider POST registry modules actions delete organization name name replaced with DELETE organizations organization name registry modules registry name namespace name POST registry modules replaced with POST organizations organization name registry modules vcs terraform cloud docs api docs private registry modules publish a private module from a vcs POST registry modules organization name name provider versions replaced with POST organizations organization name registry modules registry name namespace name provider versions terraform cloud docs api docs private registry modules create a module version GET registry modules show organization name name provider replaced with GET organizations organization name registry modules registry name namespace name provider terraform cloud docs api docs private registry modules get a module 2021 05 27 CLOUD Agents terraform cloud docs api docs agents added delete endpoint terraform cloud docs api docs agents delete an agent 2021 05 19 Runs terraform cloud docs api docs run added refresh refresh only and replace addrs attributes 2021 04 16 Introduced Controlled Remote State Access https www hashicorp com blog announcing controlled remote state access for terraform cloud and enterprise Admin Settings terraform enterprise api docs admin settings added default remote state access attribute Workspaces terraform cloud docs api docs workspaces added global remote state attribute added Remote State Consumers terraform cloud docs api docs workspaces get remote state consumers relationship 2021 04 13 Teams terraform cloud docs api docs teams added manage policy overrides property to the organization access attribute 2021 03 23 ENTERPRISE v202103 1 Introduced Share Modules Across Organizations with Terraform Enterprise https www hashicorp com blog share modules across organizations terraform enterprise Admin Organizations terraform enterprise api docs admin organizations added new query parameters to List all Organizations endpoint terraform enterprise api docs admin organizations query parameters added module consumers link in relationships response added update module consumers endpoint terraform enterprise api docs admin organizations update an organization 39 s module consumers added list module consumers endpoint terraform enterprise api docs admin organizations list module consumers for an organization Organizations terraform cloud docs api docs organizations added Module Producers terraform cloud docs api docs organizations show module producers DEPRECATION Admin Module Sharing terraform enterprise api docs admin module sharing is replaced with a new JSON Api compliant endpoint terraform enterprise api docs admin organizations update an organization 39 s module consumers 2021 03 18 CLOUD Introduced New Workspace Overview for Terraform Cloud https www hashicorp com blog new workspace overview for terraform cloud Workspaces terraform cloud docs api docs workspaces added resource count and updated at attributes added performance attributes terraform cloud docs api docs workspaces workspace performance attributes apply duration average plan duration average policy check failures run failures workspaces kpis run count added readme and outputs related resources terraform cloud docs api docs workspaces available related resources Team Access terraform cloud docs api docs team access updated to support pagination 2021 03 11 Added VCS Events terraform cloud docs api docs vcs events limited to GitLab com connections 2021 03 08 Workspaces terraform cloud docs api docs workspaces added current configuration version and current configuration version ingress attributes as includable related resources
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 Use the authentication token endpoint to manage team API tokens Generate delete and list team API tokens using the HTTP API 201 https developer mozilla org en US docs Web HTTP Status 201 page title Team Tokens API Docs HCP Terraform
--- page_title: Team Tokens - API Docs - HCP Terraform description: >- Use the `/authentication-token` endpoint to manage team API tokens. Generate, delete, and list team API tokens using the HTTP API. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # Team token API Team API tokens grant access to a team's workspaces. Each team can have an API token that is not associated with a specific user. You can create and delete team tokens and list an organization's team tokens. ## Generate a new team token Generates a new team token and overrides existing token if one exists. | Method | Path | | :----- | :----------------------------------- | | POST | /teams/:team_id/authentication-token | This endpoint returns the secret text of the new authentication token. You can only access this token when you create it and can not recover it later. ### Parameters - `:team_id` (`string: <required>`) - specifies the team ID for generating the team token ### Request body This POST endpoint requires a JSON object with the following properties as a request payload. | Key path | Type | Default | Description | | ----------------------------- | ------ | ------- | --------------------------------------------------------------------------------------------------------------- | | `data.type` | string | | Must be `"authentication-token"`. | | `data.attributes.expired-at` | string | `null` | The UTC date and time that the Team Token will expire, in ISO 8601 format. If omitted or set to `null` the token will never expire. | ### Sample payload ```json { "data": { "type": "authentication-token", "attributes": { "expired-at": "2023-04-06T12:00:00.000Z" } } } ``` ### Sample request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/teams/team-BUHBEM97xboT8TVz/authentication-token ``` ### Sample response ```json { "data": { "id": "4111797", "type": "authentication-tokens", "attributes": { "created-at": "2017-11-29T19:18:09.976Z", "last-used-at": null, "description": null, "token": "QnbSxjjhVMHJgw.atlasv1.gxZnWIjI5j752DGqdwEUVLOFf0mtyaQ00H9bA1j90qWb254lEkQyOdfqqcq9zZL7Sm0", "expired-at": "2023-04-06T12:00:00.000Z" }, "relationships": { "team": { "data": { "id": "team-Y7RyjccPVBKVEdp7", "type": "teams" } }, "created-by": { "data": { "id": "user-62goNpx1ThQf689e", "type": "users" } } } } } ``` ## Delete the team token | Method | Path | | :----- | :----------------------------------- | | DELETE | /teams/:team_id/authentication-token | ### Parameters - `:team_id` (`string: <required>`) - specifies the team_id from which to delete the token ### Sample request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request DELETE \ https://app.terraform.io/api/v2/teams/team-BUHBEM97xboT8TVz/authentication-token ``` ## List team tokens Lists the [team tokens](/terraform/cloud-docs/users-teams-organizations/teams#api-tokens) in an organization. `GET organizations/:organization_name/team-tokens` | Parameter | Description | |----------------------|----------------------------------------------------------| | `:organization_name` | The name of the organization whose team tokens you want to list. | This endpoint returns object metadata and does not include secret authentication details of tokens. You can only view a token when you create it and cannot recover it later. By default, this endpoint returns tokens by ascending expiration date. | Status | Response | Reason | | ------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------- | | [200][] | [JSON API document][] (`type: "team-tokens"`) | The request was successful. | | [200][] | Empty [JSON API document][] | The specified organization has no team tokens. | | [404][] | [JSON API error object][] | Organization not found. | ### Query parameters This endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters) and searching with the `q` parameter. Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. | Parameter | Description | |----------------|---------------------------------------------------------------------| | `page[number]` | **Optional.** If omitted, the endpoint returns the first page. | | `page[size]` | **Optional.** If omitted, the endpoint returns 20 tokens per page. | | `q` | **Optional.** A search query string. You can search for a team authentication token using the team name. | | `sort` | **Optional.** Allows sorting the team tokens by `"team-name"`, `"created-by"`, `"expired-at"`, and `"last-used-at"`. Prepending a hyphen to the sort parameter reverses the order. For example, `"-team-name"` sorts by name in reverse alphabetical order. If omitted, the default sort order ascending. | ### Sample response ```json { "data": [ { "id": "at-TLhN8cc6ro6qYDvp", "type": "authentication-tokens", "attributes": { "created-at": "2024-06-19T18:28:25.267Z", "last-used-at": null, "description": null, "token": null, "expired-at": "2024-07-19T18:28:25.030Z" }, "relationships": { "team": { "data": { "id": "team-Y7RyjccPVBKVEdp7", "type": "teams" } }, "created-by": { "data": { "id": "user-ccU6h629sszLJBpY", "type": "users" } } } }, { "id": "at-qfc2wqqJ1T5sCamM", "type": "authentication-tokens", "attributes": { "created-at": "2024-06-19T18:44:44.051Z", "last-used-at": null, "description": null, "token": null, "expired-at": "2024-07-19T18:44:43.818Z" }, "relationships": { "team": { "data": { "id": "team-58pFiBffTLMxLphR", "type": "teams" } }, "created-by": { "data": { "id": "user-ccU6h629hhzLJBpY", "type": "users" } } } }, ] } ``` ## Show a team token Use this endpoint to display a [team token](/terraform/cloud-docs/users-teams-organizations/teams#api-tokens) for a particular team. `GET /teams/:team-id/authentication-token` | Parameter | Description | | ---------- | ------------------------- | | `:team-id` | The ID of the Team. | You can also fetch a team token directly by using the token's ID with the `authentication-tokens/` endpoint. `GET /authentication-tokens/:token-id` | Parameter | Description | | ----------- | ------------------------- | | `:token-id` | The ID of the Team Token. | The object returned by this endpoint only contains metadata, and does not include the secret text of the authentication token. A token's secret test is only shown upon creation, and cannot be recovered later. | Status | Response | Reason | | ------- | ------------------------------------------------------- | ------------------------------------------------------------ | | [200][] | [JSON API document][] (`type: "authentication-tokens"`) | The request was successful | | [404][] | [JSON API error object][] | Team Token not found, or unauthorized to view the Team Token | ### Sample request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/teams/team-6yEmxNAhaoQLH1Da/authentication-token ``` ### Sample response ```json { "data": { "id": "at-6yEmxNAhaoQLH1Da", "type": "authentication-tokens", "attributes": { "created-at": "2023-11-25T22:31:30.624Z", "last-used-at": "2023-11-26T20:34:59.487Z", "description": null, "token": null, "expired-at": "2024-04-06T12:00:00.000Z" }, "relationships": { "team": { "data": { "id": "team-LnREdjodkvZFGdXL", "type": "teams" } }, "created-by": { "data": { "id": "user-MA4GL63FmYRpSFxa", "type": "users" } } } } } ```
terraform
page title Team Tokens API Docs HCP Terraform description Use the authentication token endpoint to manage team API tokens Generate delete and list team API tokens using the HTTP API 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects Team token API Team API tokens grant access to a team s workspaces Each team can have an API token that is not associated with a specific user You can create and delete team tokens and list an organization s team tokens Generate a new team token Generates a new team token and overrides existing token if one exists Method Path POST teams team id authentication token This endpoint returns the secret text of the new authentication token You can only access this token when you create it and can not recover it later Parameters team id string required specifies the team ID for generating the team token Request body This POST endpoint requires a JSON object with the following properties as a request payload Key path Type Default Description data type string Must be authentication token data attributes expired at string null The UTC date and time that the Team Token will expire in ISO 8601 format If omitted or set to null the token will never expire Sample payload json data type authentication token attributes expired at 2023 04 06T12 00 00 000Z Sample request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 teams team BUHBEM97xboT8TVz authentication token Sample response json data id 4111797 type authentication tokens attributes created at 2017 11 29T19 18 09 976Z last used at null description null token QnbSxjjhVMHJgw atlasv1 gxZnWIjI5j752DGqdwEUVLOFf0mtyaQ00H9bA1j90qWb254lEkQyOdfqqcq9zZL7Sm0 expired at 2023 04 06T12 00 00 000Z relationships team data id team Y7RyjccPVBKVEdp7 type teams created by data id user 62goNpx1ThQf689e type users Delete the team token Method Path DELETE teams team id authentication token Parameters team id string required specifies the team id from which to delete the token Sample request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request DELETE https app terraform io api v2 teams team BUHBEM97xboT8TVz authentication token List team tokens Lists the team tokens terraform cloud docs users teams organizations teams api tokens in an organization GET organizations organization name team tokens Parameter Description organization name The name of the organization whose team tokens you want to list This endpoint returns object metadata and does not include secret authentication details of tokens You can only view a token when you create it and cannot recover it later By default this endpoint returns tokens by ascending expiration date Status Response Reason 200 JSON API document type team tokens The request was successful 200 Empty JSON API document The specified organization has no team tokens 404 JSON API error object Organization not found Query parameters This endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters and searching with the q parameter Remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs Parameter Description page number Optional If omitted the endpoint returns the first page page size Optional If omitted the endpoint returns 20 tokens per page q Optional A search query string You can search for a team authentication token using the team name sort Optional Allows sorting the team tokens by team name created by expired at and last used at Prepending a hyphen to the sort parameter reverses the order For example team name sorts by name in reverse alphabetical order If omitted the default sort order ascending Sample response json data id at TLhN8cc6ro6qYDvp type authentication tokens attributes created at 2024 06 19T18 28 25 267Z last used at null description null token null expired at 2024 07 19T18 28 25 030Z relationships team data id team Y7RyjccPVBKVEdp7 type teams created by data id user ccU6h629sszLJBpY type users id at qfc2wqqJ1T5sCamM type authentication tokens attributes created at 2024 06 19T18 44 44 051Z last used at null description null token null expired at 2024 07 19T18 44 43 818Z relationships team data id team 58pFiBffTLMxLphR type teams created by data id user ccU6h629hhzLJBpY type users Show a team token Use this endpoint to display a team token terraform cloud docs users teams organizations teams api tokens for a particular team GET teams team id authentication token Parameter Description team id The ID of the Team You can also fetch a team token directly by using the token s ID with the authentication tokens endpoint GET authentication tokens token id Parameter Description token id The ID of the Team Token The object returned by this endpoint only contains metadata and does not include the secret text of the authentication token A token s secret test is only shown upon creation and cannot be recovered later Status Response Reason 200 JSON API document type authentication tokens The request was successful 404 JSON API error object Team Token not found or unauthorized to view the Team Token Sample request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 teams team 6yEmxNAhaoQLH1Da authentication token Sample response json data id at 6yEmxNAhaoQLH1Da type authentication tokens attributes created at 2023 11 25T22 31 30 624Z last used at 2023 11 26T20 34 59 487Z description null token null expired at 2024 04 06T12 00 00 000Z relationships team data id team LnREdjodkvZFGdXL type teams created by data id user MA4GL63FmYRpSFxa type users
terraform A variable set terraform cloud docs workspaces variables scope is a resource that allows you to reuse the same variables across multiple workspaces and projects For example you could define a variable set of provider credentials and automatically apply it to a selection of workspaces all workspaces in a project or all workspaces in an organization Variable Sets API Use the varsets endpoint to manage variable sets List show create update and delete variable sets and apply or remove variable sets from workspaces using the HTTP API page title Variable Sets API Docs HCP Terraform
--- page_title: Variable Sets - API Docs - HCP Terraform description: >- Use the `/varsets` endpoint to manage variable sets. List, show, create, update, and delete variable sets, and apply or remove variable sets from workspaces using the HTTP API. --- # Variable Sets API A [variable set](/terraform/cloud-docs/workspaces/variables#scope) is a resource that allows you to reuse the same variables across multiple workspaces and projects. For example, you could define a variable set of provider credentials and automatically apply it to a selection of workspaces, all workspaces in a project, or all workspaces in an organization. You need [**Read** variables permission](/terraform/cloud-docs/users-teams-organizations/permissions#general-workspace-permissions) to view the variables for a particular workspace and to view the variable sets in the owning organization. To create or edit variable sets, your team must have [**Manage all workspaces** organization access](/terraform/cloud-docs/users-teams-organizations/teams/manage#managing-organization-access). ## Create a Variable Set `POST organizations/:organization_name/varsets` | Parameter | Description | | -------------------- | ------------------------------------------------------ | | `:organization_name` | The name of the organization the workspace belongs to. | ### Request Body Properties without a default value are required. | Key path | Type | Default | Description | |---------------------------------|---------|---------|-----------------------------------------------------------------------------------------------------------------------------| | `data.attributes.name` | string | | The name of the variable set. | | `data.attributes.description` | string | `""` | Text displayed in the UI to contextualize the variable set and its purpose. | | `data.attributes.global` | boolean | `false` | When true, HCP Terraform automatically applies the variable set to all current and future workspaces in the organization. | | `data.attributes.priority` | boolean | `false` | When true, the variables in the set override any other variable values with a more specific scope, including values set on the command line. | | `data.relationships.workspaces` | array | \`[]` | Array of references to workspaces that the variable set should be assigned to. | | `data.relationships.projects` | array | \`[]` | Array of references to projects that the variable set should be assigned to. | | `data.relationships.vars` | array | \`[]` | Array of complete variable definitions that comprise the variable set. | HCP Terraform does not allow different global variable sets to contain conflicting variables with the same name and type. You will receive a 422 response if you try to create a global variable set that contains conflicting variables. | Status | Response | Reason(s) | | ------- | ------------------------- | --------------------------------------------------------------------- | | [200][] | [JSON API document][] | Successfully added variable set | | [404][] | [JSON API error object][] | Organization not found, or user unauthorized to perform action | | [422][] | [JSON API error object][] | Problem with payload or request; details provided in the error object | ### Sample Payload ```json { "data": { "type": "varsets", "attributes": { "name": "MyVarset", "description": "Full of vars and such for mass reuse", "global": false, "priority": false, }, "relationships": { "workspaces": { "data": [ { "id": "ws-z6YvbWEYoE168kpq", "type": "workspaces" } ] }, "vars": { "data": [ { "type": "vars", "attributes": { "key": "c2e4612d993c18e42ef30405ea7d0e9ae", "value": "8676328808c5bf56ac5c8c0def3b7071", "category": "terraform" } } ] } } } } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/organizations/my-organization/varsets ``` ### Sample Response ```json { "data": { "id": "varset-kjkN545LH2Sfercv", "type": "varsets", "attributes": { "name": "MyVarset", "description": "Full of vars and such for mass reuse", "global": false, "priority": false, }, "relationships": { "workspaces": { "data": [ { "id": "ws-z6YvbWEYoE168kpq", "type": "workspaces" } ] }, "projects": { "data": [ { "id": "prj-lkjasdlkfjs", "type": "projects" } ] }, "vars": { "data": [ { "id": "var-Nh0doz0hzj9hrm34qq", "type": "vars", "attributes": { "key": "c2e4612d993c18e42ef30405ea7d0e9ae", "value": "8676328808c5bf56ac5c8c0def3b7071", "category": "terraform" } } ] } } } } ``` ## Update a Variable Set `PUT/PATCH varsets/:varset_id` | Parameter | Description | | ------------ | ------------------- | | `:varset_id` | The variable set ID | HCP Terraform does not allow global variable sets to contain conflicting variables with the same name and type. You will receive a 422 response if you try to create a global variable set that contains conflicting variables. ### Request Body | Key path | Type | Default | Description | |---------------------------------|---------|---------|------------------------------------------------------------------------------------------------------------------------------------------------------| | `data.attributes.name` | string | | The name of the variable set. | | `data.attributes.description` | string | | Text displayed in the UI to contextualize the variable set and its purpose. | | `data.attributes.global` | boolean | | When true, HCP Terraform automatically applies the variable set to all current and future workspaces in the organization. | | `data.attributes.priority` | boolean | `false` | When true, the variables in the set override any other variable values set with a more specific scope, including values set on the command line. | | `data.relationships.workspaces` | array | | **Optional** Array of references to workspaces that the variable set should be assigned to. Sending an empty array clears all workspace assignments. | | `data.relationships.projects` | array | | **Optional** Array of references to projects that the variable set should be assigned to. Sending an empty array clears all project assignments. | | `data.relationships.vars` | array | | **Optional** Array of complete variable definitions to add to the variable set. | | Status | Response | Reason(s) | | ------- | ------------------------- | ------------------------------------------------------------------------------ | | [200][] | [JSON API document][] | Successfully updated variable set | | [404][] | [JSON API error object][] | Organization or variable set not found, or user unauthorized to perform action | | [422][] | [JSON API error object][] | Problem with payload or request; details provided in the error object | ### Sample Payload ```json { "data": { "type": "varsets", "attributes": { "name": "MyVarset", "description": "Full of vars and such for mass reuse. Now global!", "global": true, "priority": true, }, "relationships": { "workspaces": { "data": [ { "id": "ws-FRFwkYoUoGn1e34b", "type": "workspaces" } ] }, "projects": { "data": [ { "id": "prj-kFjgSzcZSr5c3imE", "type": "projects" } ] }, "vars": { "data": [ { "type": "vars", "attributes": { "key": "c2e4612d993c18e42ef30405ea7d0e9ae", "value": "8676328808c5bf56ac5c8c0def3b7071", "category": "terraform" } } ] } } } } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request PATCH \ --data @payload.json \ https://app.terraform.io/api/v2/varsets/varset-kjkN545LH2Sfercv ``` ### Sample Response ```json { "data": { "id": "varset-kjkN545LH2Sfercv", "type": "varsets", "attributes": { "name": "MyVarset", "description": "Full of vars and such for mass reuse. Now global!", "global": true, "priority": true }, "relationships": { "vars": { "data": [ { "id": "var-Nh0doz0hzj9hrm34qq", "type": "vars", "attributes": { "key": "c2e4612d993c18e42ef30405ea7d0e9ae", "value": "8676328808c5bf56ac5c8c0def3b7071", "category": "terraform" } } ] } } } } ``` ## Delete a Variable Set `DELETE varsets/:varset_id` | Parameter | Description | | ------------ | ------------------- | | `:varset_id` | The variable set ID | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request DELETE \ https://app.terraform.io/api/v2/varsets/varset-kjkN545LH2Sfercv ``` On success, this endpoint responds with no content. ## Show Variable Set Fetch details about the specified variable set. `GET varsets/:varset_id` | Parameter | Description | | ------------ | ------------------- | | `:varset_id` | The variable set ID | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/varsets/varset-kjkN545LH2Sfercv ``` ### Sample Response ```json { "data": { "id": "varset-kjkN545LH2Sfercv", "type": "varsets", "attributes": { "name": "MyVarset", "description": "Full of vars and such for mass reuse", "global": false, "priority": false, "updated-at": "2023-03-06T21:48:33.588Z", "var-count": 5, "workspace-count": 2, "project-count": 2 }, "relationships": { "organization": { "data": { "id": "hashicorp", "type": "organizations" } }, "vars": { "data": [ { "id": "var-mMqadSCxZtrQJAv8", "type": "vars" }, { "id": "var-hFxUUKSk35QMsRVH", "type": "vars" }, { "id": "var-fkd6N48tXRmoaPxH", "type": "vars" }, { "id": "var-abcbBMBMWcZw3WiV", "type": "vars" }, { "id": "var-vqvRKK1ZoqQCiMwN", "type": "vars" } ] }, "workspaces": { "data": [ { "id": "ws-UohFdKAHUGsQ8Dtf", "type": "workspaces" }, { "id": "ws-XhGhaaCrsx9ATson", "type": "workspaces" } ] }, "projects": { "data": [ { "id": "prj-1JMwvPHFsdpsPhnt", "type": "projects" }, { "id": "prj-SLDGqbYqELXE1obp", "type": "projects" } ] } } } } ``` ## List Variable Sets List all variable sets for an organization. `GET organizations/:organization_name/varsets` | Parameter | Description | |----------------------|----------------------------------------------------------| | `:organization_name` | The name of the organization the variable sets belong to | List all variable sets for a project. This includes global variable sets from the project's organization. `GET projects/:project_id/varsets` | Parameter | Description | |---------------|----------------| | `:project_id` | The project ID | List all variable sets for a workspace. This includes global variable sets from the workspace's organization and variable sets attached to the project this workspace is contained within. `GET workspaces/:workspace_id/varsets` | Parameter | Description | |-----------------|------------------| | `:workspace_id` | The workspace ID | ### Query Parameters All list endpoints support pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters) and searching with the `q` parameter. Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. | Parameter | Description | |----------------|---------------------------------------------------------------------| | `page[number]` | **Optional.** If omitted, the endpoint returns the first page. | | `page[size]` | **Optional.** If omitted, the endpoint returns 20 varsets per page. | | `q` | **Optional.** A search query string. You can search for a variable set using its name. | ### Sample Response ```json { "data": [ { "id": "varset-kjkN545LH2Sfercv", "type": "varsets", "attributes": { "name": "MyVarset", "description": "Full of vars and such for mass reuse", "global": false, "priority": false, "updated-at": "2023-03-06T21:48:33.588Z", "var-count": 5, "workspace-count": 2, "project-count": 2 }, "relationships": { "organization": { "data": { "id": "hashicorp", "type": "organizations" } }, "vars": { "data": [ { "id": "var-mMqadSCxZtrQJAv8", "type": "vars" }, { "id": "var-hFxUUKSk35QMsRVH", "type": "vars" }, { "id": "var-fkd6N48tXRmoaPxH", "type": "vars" }, { "id": "var-abcbBMBMWcZw3WiV", "type": "vars" }, { "id": "var-vqvRKK1ZoqQCiMwN", "type": "vars" } ] }, "workspaces": { "data": [ { "id": "ws-UohFdKAHUGsQ8Dtf", "type": "workspaces" }, { "id": "ws-XhGhaaCrsx9ATson", "type": "workspaces" } ] }, "projects": { "data": [ { "id": "prj-1JMwvPHFsdpsPhnt", "type": "projects" }, { "id": "prj-SLDGqbYqELXE1obp", "type": "projects" } ] } } } ], "links": { "self": "https://app.terraform.io/api/v2/organizations/hashicorp/varsets?page%5Bnumber%5D=1&page%5Bsize%5D=20", "first": "https://app.terraform.io/api/v2/organizations/hashicorp/varsets?page%5Bnumber%5D=1&page%5Bsize%5D=20", "prev": null, "next": null, "last": "https://app.terraform.io/api/v2/organizations/hashicorp/varsets?page%5Bnumber%5D=1&page%5Bsize%5D=20" }, "meta": { "pagination": { "current-page": 1, "page-size": 20, "prev-page": null, "next-page": null, "total-pages": 1, "total-count": 1 } } } ``` ### Variable Relationships ## Add Variable `POST varsets/:varset_external_id/relationships/vars` | Parameter | Description | | ------------ | ------------------- | | `:varset_id` | The variable set ID | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | | ----------------------------- | ------ | ------- | --------------------------------------------------------------------------------------------------------------- | | `data.type` | string | | Must be `"vars"`. | | `data.attributes.key` | string | | The name of the variable. | | `data.attributes.value` | string | `""` | The value of the variable. | | `data.attributes.description` | string | | The description of the variable. | | `data.attributes.category` | string | | Whether this is a Terraform or environment variable. Valid values are `"terraform"` or `"env"`. | | `data.attributes.hcl` | bool | `false` | Whether to evaluate the value of the variable as a string of HCL code. Has no effect for environment variables. | | `data.attributes.sensitive` | bool | `false` | Whether the value is sensitive. If true, variable is not visible in the UI. | HCP Terraform does not allow different global variable sets to contain conflicting variables with the same name and type. You will receive a 422 response if you try to add a conflicting variable to a global variable set. | Status | Response | Reason(s) | | ------- | ------------------------- | --------------------------------------------------------------------- | | [200][] | [JSON API document][] | Successfully added variable to variable set | | [404][] | [JSON API error object][] | Variable set not found, or user unauthorized to perform action | | [422][] | [JSON API error object][] | Problem with payload or request; details provided in the error object | ### Sample Payload ```json { "data": { "type": "vars", "attributes": { "key": "g6e45ae7564a17e81ef62fd1c7fa86138", "value": "61e400d5ccffb3782f215344481e6c82", "description": "cheeeese", "sensitive": false, "category": "terraform", "hcl": false } } } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/varsets/varset-4q8f7H0NHG733bBH/relationships/vars ``` ### Sample Response ```json { "data": { "id":"var-EavQ1LztoRTQHSNT", "type": "vars", "attributes": { "key": "g6e45ae7564a17e81ef62fd1c7fa86138", "value": "61e400d5ccffb3782f215344481e6c82", "description": "cheeeese", "sensitive": false, "category": "terraform", "hcl": false } } } ``` ## Update a Variable in a Variable Set `PATCH varsets/:varset_id/relationships/vars/:var_id` | Parameter | Description | | ------------ | -------------------------------- | | `:varset_id` | The variable set ID | | `:var_id` | The ID of the variable to delete | HCP Terraform does not allow different global variable sets to contain conflicting variables with the same name and type. You will receive a 422 response if you try to add a conflicting variable to a global variable set. | Status | Response | Reason(s) | | ------- | ------------------------- | --------------------------------------------------------------------- | | [200][] | [JSON API document][] | Successfully updated variable for variable set | | [404][] | [JSON API error object][] | Variable set not found, or user unauthorized to perform action | | [422][] | [JSON API error object][] | Problem with payload or request; details provided in the error object | ### Sample Payload ```json { "data": { "type": "vars", "attributes": { "key": "g6e45ae7564a17e81ef62fd1c7fa86138", "value": "61e400d5ccffb3782f215344481e6c82", "description": "new cheeeese", "sensitive": false, "category": "terraform", "hcl": false } } } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request PATCH \ --data @payload.json \ https://app.terraform.io/api/v2/varsets/varset-4q8f7H0NHG733bBH/relationships/vars/var-EavQ1LztoRTQHSNT ``` ### Sample Response ```json { "data": { "id":"var-EavQ1LztoRTQHSNT", "type": "vars", "attributes": { "key": "g6e45ae7564a17e81ef62fd1c7fa86138", "value": "61e400d5ccffb3782f215344481e6c82", "description": "new cheeeese", "sensitive": false, "category": "terraform", "hcl": false } } } ``` ## Delete a Variable in a Variable Set `DELETE varsets/:varset_id/relationships/vars/:var_id` | Parameter | Description | | ------------ | -------------------------------- | | `:varset_id` | The variable set ID | | `:var_id` | The ID of the variable to delete | ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request DELETE \ https://app.terraform.io/api/v2/varsets/varset-4q8f7H0NHG733bBH/relationships/vars/var-EavQ1LztoRTQHSNT ``` On success, this endpoint responds with no content. ## List Variables in a Variable Set `GET varsets/:varset_id/relationships/vars` | Parameter | Description | | ------------ | ------------------- | | `:varset_id` | The variable set ID | ### Sample Response ```json { "data": [ { "id": "var-134r1k34nj5kjn", "type": "vars", "attributes": { "key": "F115037558b045dd82da40b089e5db745", "value": "1754288480dfd3060e2c37890422905f", "sensitive": false, "category": "terraform", "hcl": false, "created-at": "2021-10-29T18:54:29.379Z", "description": "" }, "relationships": { "varset": { "data": { "id": "varset-992UMULdeDuebi1x", "type": "varsets" }, "links": { "related": "/api/v2/varsets/1" } } }, "links": { "self": "/api/v2/vars/var-BEPU9NjPVCiCfrXj" } } ], "links": { "self": "app.terraform.io/app/varsets/varset-992UMULdeDuebi1x/vars", "first": "app.terraform.io/app/varsets/varset-992UMULdeDuebi1x/vars?page=1", "prev": null, "next": null, "last": "app.terraform.io/app/varsets/varset-992UMULdeDuebi1x/vars?page=1" } } ``` ## Apply Variable Set to Workspaces Accepts a list of workspaces to add the variable set to. `POST varsets/:varset_id/relationships/workspaces` | Parameter | Description | | ------------ | ------------------- | | `:varset_id` | The variable set ID | Properties without a default value are required. | Key path | Type | Default | Description | | ------------- | ------ | ------- | -------------------------------------------------- | | `data[].type` | string | | Must be `"workspaces"` | | `data[].id` | string | | The id of the workspace to add the variable set to | | Status | Response | Reason(s) | | ------- | ------------------------- | --------------------------------------------------------------------- | | [204][] | | Successfully added variable set to the requested workspaces | | [404][] | [JSON API error object][] | Variable set not found or user unauthorized to perform action | | [422][] | [JSON API error object][] | Problem with payload or request; details provided in the error object | ### Sample Payload ```json { "data": [ { "type": "workspaces", "id": "ws-YwfuBJZkdai4xj9w" } ] } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/varsets/varset-kjkN545LH2Sfercv/relationships/workspaces ``` ## Remove a Variable Set from Workspaces Accepts a list of workspaces to remove the variable set from. `DELETE varsets/:varset_id/relationships/workspaces` | Parameter | Description | | ------------ | ------------------- | | `:varset_id` | The variable set ID | Properties without a default value are required. | Key path | Type | Default | Description | | ------------- | ------ | ------- | ------------------------------------------------------- | | `data[].type` | string | | Must be `"workspaces"` | | `data[].id` | string | | The id of the workspace to delete the variable set from | | Status | Response | Reason(s) | | ------- | ------------------------- | --------------------------------------------------------------------- | | [204][] | | Successfully removed variable set from the requested workspaces | | [404][] | [JSON API error object][] | Variable set not found or user unauthorized to perform action | | [422][] | [JSON API error object][] | Problem with payload or request; details provided in the error object | ### Sample Payload ```json { "data": [ { "type": "workspaces", "id": "ws-YwfuBJZkdai4xj9w" }, { "type": "workspaces", "id": "ws-YwfuBJZkdai4xj9w" } ] } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request DELETE \ --data @payload.json \ https://app.terraform.io/api/v2/varsets/varset-kjkN545LH2Sfercv/relationships/workspaces ``` ## Apply Variable Set to Projects Accepts a list of projects to add the variable set to. When you apply a variable set to a project, all the workspaces in that project will have the variable set applied to them. `POST varsets/:varset_id/relationships/projects` | Parameter | Description | | ------------ | ------------------- | | `:varset_id` | The variable set ID | Properties without a default value are required. | Key path | Type | Default | Description | | ------------- | ------ | ------- | -------------------------------------------------- | | `data[].type` | string | | Must be `"projects"` | | `data[].id` | string | | The id of the project to add the variable set to | | Status | Response | Reason(s) | | ------- | ------------------------- | --------------------------------------------------------------------- | | [204][] | | Successfully added variable set to the requested projects | | [404][] | [JSON API error object][] | Variable set not found or user unauthorized to perform action | | [422][] | [JSON API error object][] | Problem with payload or request; details provided in the error object | ### Sample Payload ```json { "data": [ { "type": "projects", "id": "prj-YwfuBJZkdai4xj9w" } ] } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/varsets/varset-kjkN545LH2Sfercv/relationships/projects ``` ## Remove a Variable Set from Projects Accepts a list of projects to remove the variable set from. `DELETE varsets/:varset_id/relationships/projects` | Parameter | Description | | ------------ | ------------------- | | `:varset_id` | The variable set ID | Properties without a default value are required. | Key path | Type | Default | Description | | ------------- | ------ | ------- | ------------------------------------------------------- | | `data[].type` | string | | Must be `"projects"` | | `data[].id` | string | | The id of the project to delete the variable set from | | Status | Response | Reason(s) | | ------- | ------------------------- | --------------------------------------------------------------------- | | [204][] | | Successfully removed variable set from the requested projects | | [404][] | [JSON API error object][] | Variable set not found or user unauthorized to perform action | | [422][] | [JSON API error object][] | Problem with payload or request; details provided in the error object | ### Sample Payload ```json { "data": [ { "type": "projects", "id": "prj-YwfuBJZkdai4xj9w" }, { "type": "projects", "id": "prj-lkjasdfiojwerlkj" } ] } ``` ### Sample Request ```shell curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request DELETE \ --data @payload.json \ https://app.terraform.io/api/v2/varsets/varset-kjkN545LH2Sfercv/relationships/projects ``` [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [json api document]: /terraform/cloud-docs/api-docs#json-api-documents [json api error object]: https://jsonapi.org/format/#error-objects ## Available Related Resources The GET endpoints above can optionally return related resources, if requested with [the `include` query parameter](/terraform/cloud-docs/api-docs#inclusion-of-related-resources). The following resource types are available: | Resource Name | Description | | -------------------- | ------------------------------------------------- | | `vars` | Show each variable in a variable set and all of their attributes including `id`, `key`, `value`, `sensitive`, `category`, `hcl`, `created_at`, and `description`. |
terraform
page title Variable Sets API Docs HCP Terraform description Use the varsets endpoint to manage variable sets List show create update and delete variable sets and apply or remove variable sets from workspaces using the HTTP API Variable Sets API A variable set terraform cloud docs workspaces variables scope is a resource that allows you to reuse the same variables across multiple workspaces and projects For example you could define a variable set of provider credentials and automatically apply it to a selection of workspaces all workspaces in a project or all workspaces in an organization You need Read variables permission terraform cloud docs users teams organizations permissions general workspace permissions to view the variables for a particular workspace and to view the variable sets in the owning organization To create or edit variable sets your team must have Manage all workspaces organization access terraform cloud docs users teams organizations teams manage managing organization access Create a Variable Set POST organizations organization name varsets Parameter Description organization name The name of the organization the workspace belongs to Request Body Properties without a default value are required Key path Type Default Description data attributes name string The name of the variable set data attributes description string Text displayed in the UI to contextualize the variable set and its purpose data attributes global boolean false When true HCP Terraform automatically applies the variable set to all current and future workspaces in the organization data attributes priority boolean false When true the variables in the set override any other variable values with a more specific scope including values set on the command line data relationships workspaces array Array of references to workspaces that the variable set should be assigned to data relationships projects array Array of references to projects that the variable set should be assigned to data relationships vars array Array of complete variable definitions that comprise the variable set HCP Terraform does not allow different global variable sets to contain conflicting variables with the same name and type You will receive a 422 response if you try to create a global variable set that contains conflicting variables Status Response Reason s 200 JSON API document Successfully added variable set 404 JSON API error object Organization not found or user unauthorized to perform action 422 JSON API error object Problem with payload or request details provided in the error object Sample Payload json data type varsets attributes name MyVarset description Full of vars and such for mass reuse global false priority false relationships workspaces data id ws z6YvbWEYoE168kpq type workspaces vars data type vars attributes key c2e4612d993c18e42ef30405ea7d0e9ae value 8676328808c5bf56ac5c8c0def3b7071 category terraform Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 organizations my organization varsets Sample Response json data id varset kjkN545LH2Sfercv type varsets attributes name MyVarset description Full of vars and such for mass reuse global false priority false relationships workspaces data id ws z6YvbWEYoE168kpq type workspaces projects data id prj lkjasdlkfjs type projects vars data id var Nh0doz0hzj9hrm34qq type vars attributes key c2e4612d993c18e42ef30405ea7d0e9ae value 8676328808c5bf56ac5c8c0def3b7071 category terraform Update a Variable Set PUT PATCH varsets varset id Parameter Description varset id The variable set ID HCP Terraform does not allow global variable sets to contain conflicting variables with the same name and type You will receive a 422 response if you try to create a global variable set that contains conflicting variables Request Body Key path Type Default Description data attributes name string The name of the variable set data attributes description string Text displayed in the UI to contextualize the variable set and its purpose data attributes global boolean When true HCP Terraform automatically applies the variable set to all current and future workspaces in the organization data attributes priority boolean false When true the variables in the set override any other variable values set with a more specific scope including values set on the command line data relationships workspaces array Optional Array of references to workspaces that the variable set should be assigned to Sending an empty array clears all workspace assignments data relationships projects array Optional Array of references to projects that the variable set should be assigned to Sending an empty array clears all project assignments data relationships vars array Optional Array of complete variable definitions to add to the variable set Status Response Reason s 200 JSON API document Successfully updated variable set 404 JSON API error object Organization or variable set not found or user unauthorized to perform action 422 JSON API error object Problem with payload or request details provided in the error object Sample Payload json data type varsets attributes name MyVarset description Full of vars and such for mass reuse Now global global true priority true relationships workspaces data id ws FRFwkYoUoGn1e34b type workspaces projects data id prj kFjgSzcZSr5c3imE type projects vars data type vars attributes key c2e4612d993c18e42ef30405ea7d0e9ae value 8676328808c5bf56ac5c8c0def3b7071 category terraform Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request PATCH data payload json https app terraform io api v2 varsets varset kjkN545LH2Sfercv Sample Response json data id varset kjkN545LH2Sfercv type varsets attributes name MyVarset description Full of vars and such for mass reuse Now global global true priority true relationships vars data id var Nh0doz0hzj9hrm34qq type vars attributes key c2e4612d993c18e42ef30405ea7d0e9ae value 8676328808c5bf56ac5c8c0def3b7071 category terraform Delete a Variable Set DELETE varsets varset id Parameter Description varset id The variable set ID Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request DELETE https app terraform io api v2 varsets varset kjkN545LH2Sfercv On success this endpoint responds with no content Show Variable Set Fetch details about the specified variable set GET varsets varset id Parameter Description varset id The variable set ID Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 varsets varset kjkN545LH2Sfercv Sample Response json data id varset kjkN545LH2Sfercv type varsets attributes name MyVarset description Full of vars and such for mass reuse global false priority false updated at 2023 03 06T21 48 33 588Z var count 5 workspace count 2 project count 2 relationships organization data id hashicorp type organizations vars data id var mMqadSCxZtrQJAv8 type vars id var hFxUUKSk35QMsRVH type vars id var fkd6N48tXRmoaPxH type vars id var abcbBMBMWcZw3WiV type vars id var vqvRKK1ZoqQCiMwN type vars workspaces data id ws UohFdKAHUGsQ8Dtf type workspaces id ws XhGhaaCrsx9ATson type workspaces projects data id prj 1JMwvPHFsdpsPhnt type projects id prj SLDGqbYqELXE1obp type projects List Variable Sets List all variable sets for an organization GET organizations organization name varsets Parameter Description organization name The name of the organization the variable sets belong to List all variable sets for a project This includes global variable sets from the project s organization GET projects project id varsets Parameter Description project id The project ID List all variable sets for a workspace This includes global variable sets from the workspace s organization and variable sets attached to the project this workspace is contained within GET workspaces workspace id varsets Parameter Description workspace id The workspace ID Query Parameters All list endpoints support pagination with standard URL query parameters terraform cloud docs api docs query parameters and searching with the q parameter Remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs Parameter Description page number Optional If omitted the endpoint returns the first page page size Optional If omitted the endpoint returns 20 varsets per page q Optional A search query string You can search for a variable set using its name Sample Response json data id varset kjkN545LH2Sfercv type varsets attributes name MyVarset description Full of vars and such for mass reuse global false priority false updated at 2023 03 06T21 48 33 588Z var count 5 workspace count 2 project count 2 relationships organization data id hashicorp type organizations vars data id var mMqadSCxZtrQJAv8 type vars id var hFxUUKSk35QMsRVH type vars id var fkd6N48tXRmoaPxH type vars id var abcbBMBMWcZw3WiV type vars id var vqvRKK1ZoqQCiMwN type vars workspaces data id ws UohFdKAHUGsQ8Dtf type workspaces id ws XhGhaaCrsx9ATson type workspaces projects data id prj 1JMwvPHFsdpsPhnt type projects id prj SLDGqbYqELXE1obp type projects links self https app terraform io api v2 organizations hashicorp varsets page 5Bnumber 5D 1 page 5Bsize 5D 20 first https app terraform io api v2 organizations hashicorp varsets page 5Bnumber 5D 1 page 5Bsize 5D 20 prev null next null last https app terraform io api v2 organizations hashicorp varsets page 5Bnumber 5D 1 page 5Bsize 5D 20 meta pagination current page 1 page size 20 prev page null next page null total pages 1 total count 1 Variable Relationships Add Variable POST varsets varset external id relationships vars Parameter Description varset id The variable set ID Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string Must be vars data attributes key string The name of the variable data attributes value string The value of the variable data attributes description string The description of the variable data attributes category string Whether this is a Terraform or environment variable Valid values are terraform or env data attributes hcl bool false Whether to evaluate the value of the variable as a string of HCL code Has no effect for environment variables data attributes sensitive bool false Whether the value is sensitive If true variable is not visible in the UI HCP Terraform does not allow different global variable sets to contain conflicting variables with the same name and type You will receive a 422 response if you try to add a conflicting variable to a global variable set Status Response Reason s 200 JSON API document Successfully added variable to variable set 404 JSON API error object Variable set not found or user unauthorized to perform action 422 JSON API error object Problem with payload or request details provided in the error object Sample Payload json data type vars attributes key g6e45ae7564a17e81ef62fd1c7fa86138 value 61e400d5ccffb3782f215344481e6c82 description cheeeese sensitive false category terraform hcl false Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 varsets varset 4q8f7H0NHG733bBH relationships vars Sample Response json data id var EavQ1LztoRTQHSNT type vars attributes key g6e45ae7564a17e81ef62fd1c7fa86138 value 61e400d5ccffb3782f215344481e6c82 description cheeeese sensitive false category terraform hcl false Update a Variable in a Variable Set PATCH varsets varset id relationships vars var id Parameter Description varset id The variable set ID var id The ID of the variable to delete HCP Terraform does not allow different global variable sets to contain conflicting variables with the same name and type You will receive a 422 response if you try to add a conflicting variable to a global variable set Status Response Reason s 200 JSON API document Successfully updated variable for variable set 404 JSON API error object Variable set not found or user unauthorized to perform action 422 JSON API error object Problem with payload or request details provided in the error object Sample Payload json data type vars attributes key g6e45ae7564a17e81ef62fd1c7fa86138 value 61e400d5ccffb3782f215344481e6c82 description new cheeeese sensitive false category terraform hcl false Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request PATCH data payload json https app terraform io api v2 varsets varset 4q8f7H0NHG733bBH relationships vars var EavQ1LztoRTQHSNT Sample Response json data id var EavQ1LztoRTQHSNT type vars attributes key g6e45ae7564a17e81ef62fd1c7fa86138 value 61e400d5ccffb3782f215344481e6c82 description new cheeeese sensitive false category terraform hcl false Delete a Variable in a Variable Set DELETE varsets varset id relationships vars var id Parameter Description varset id The variable set ID var id The ID of the variable to delete Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request DELETE https app terraform io api v2 varsets varset 4q8f7H0NHG733bBH relationships vars var EavQ1LztoRTQHSNT On success this endpoint responds with no content List Variables in a Variable Set GET varsets varset id relationships vars Parameter Description varset id The variable set ID Sample Response json data id var 134r1k34nj5kjn type vars attributes key F115037558b045dd82da40b089e5db745 value 1754288480dfd3060e2c37890422905f sensitive false category terraform hcl false created at 2021 10 29T18 54 29 379Z description relationships varset data id varset 992UMULdeDuebi1x type varsets links related api v2 varsets 1 links self api v2 vars var BEPU9NjPVCiCfrXj links self app terraform io app varsets varset 992UMULdeDuebi1x vars first app terraform io app varsets varset 992UMULdeDuebi1x vars page 1 prev null next null last app terraform io app varsets varset 992UMULdeDuebi1x vars page 1 Apply Variable Set to Workspaces Accepts a list of workspaces to add the variable set to POST varsets varset id relationships workspaces Parameter Description varset id The variable set ID Properties without a default value are required Key path Type Default Description data type string Must be workspaces data id string The id of the workspace to add the variable set to Status Response Reason s 204 Successfully added variable set to the requested workspaces 404 JSON API error object Variable set not found or user unauthorized to perform action 422 JSON API error object Problem with payload or request details provided in the error object Sample Payload json data type workspaces id ws YwfuBJZkdai4xj9w Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 varsets varset kjkN545LH2Sfercv relationships workspaces Remove a Variable Set from Workspaces Accepts a list of workspaces to remove the variable set from DELETE varsets varset id relationships workspaces Parameter Description varset id The variable set ID Properties without a default value are required Key path Type Default Description data type string Must be workspaces data id string The id of the workspace to delete the variable set from Status Response Reason s 204 Successfully removed variable set from the requested workspaces 404 JSON API error object Variable set not found or user unauthorized to perform action 422 JSON API error object Problem with payload or request details provided in the error object Sample Payload json data type workspaces id ws YwfuBJZkdai4xj9w type workspaces id ws YwfuBJZkdai4xj9w Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request DELETE data payload json https app terraform io api v2 varsets varset kjkN545LH2Sfercv relationships workspaces Apply Variable Set to Projects Accepts a list of projects to add the variable set to When you apply a variable set to a project all the workspaces in that project will have the variable set applied to them POST varsets varset id relationships projects Parameter Description varset id The variable set ID Properties without a default value are required Key path Type Default Description data type string Must be projects data id string The id of the project to add the variable set to Status Response Reason s 204 Successfully added variable set to the requested projects 404 JSON API error object Variable set not found or user unauthorized to perform action 422 JSON API error object Problem with payload or request details provided in the error object Sample Payload json data type projects id prj YwfuBJZkdai4xj9w Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 varsets varset kjkN545LH2Sfercv relationships projects Remove a Variable Set from Projects Accepts a list of projects to remove the variable set from DELETE varsets varset id relationships projects Parameter Description varset id The variable set ID Properties without a default value are required Key path Type Default Description data type string Must be projects data id string The id of the project to delete the variable set from Status Response Reason s 204 Successfully removed variable set from the requested projects 404 JSON API error object Variable set not found or user unauthorized to perform action 422 JSON API error object Problem with payload or request details provided in the error object Sample Payload json data type projects id prj YwfuBJZkdai4xj9w type projects id prj lkjasdfiojwerlkj Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request DELETE data payload json https app terraform io api v2 varsets varset kjkN545LH2Sfercv relationships projects 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 json api document terraform cloud docs api docs json api documents json api error object https jsonapi org format error objects Available Related Resources The GET endpoints above can optionally return related resources if requested with the include query parameter terraform cloud docs api docs inclusion of related resources The following resource types are available Resource Name Description vars Show each variable in a variable set and all of their attributes including id key value sensitive category hcl created at and description
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 Use the assessment results endpoint to query health assessments Get continuous validation and drift detection health assessment results using the HTTP API 400 https developer mozilla org en US docs Web HTTP Status 400 page title Assessments API Docs HCP Terraform
--- page_title: Assessments - API Docs - HCP Terraform description: >- Use the `/assessment-results` endpoint to query health assessments. Get continuous validation and drift detection health assessment results using the HTTP API. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 # Assessment Results API An Assessment Result is the summary record of an instance of health assessment. HCP Terraform can perform automatic health assessments in a workspace to assess whether its real infrastructure matches the requirements defined in its Terraform configuration. Refer to [Health](/terraform/cloud-docs/workspaces/health) for more details. <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/health-assessments.mdx' <!-- END: TFC:only name:pnp-callout --> ## Show Assessment Result Any user with read access to a workspace can retrieve assessment results for the workspace. `GET api/v2/assessment-results/:assessment_result_id` | Parameter | Description | | ----------------------- | ------------------------ | | `:assessment_result_id` | The assessment result ID | ### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/assessment-results/asmtres-cHh5777xm ``` ### Sample Response ```json { "id": "asmtres-UG5rE9L1373hMYMA", "type": "assessment-results", "data": { "attributes": { "drifted": true, "succeeded": true, "error-msg": null, "created-at": "2022-07-02T22:29:58+00:00", }, "links": { "self": "/api/v2/assessment-results/asmtres-UG5rE9L1373hMYMA/" "json-output": "/api/v2/assessment-results/asmtres-UG5rE9L1373hMYMA/json-output" "json-schema": "/api/v2/assessment-results/asmtres-UG5rE9L1373hMYMA/json-schema" "log-output": "/api/v2/assessment-results/asmtres-UG5rE9L1373hMYMA/log-output" } } } ``` ## Retrieve the JSON output from the assessment execution The following endpoints retrieve files documenting the plan, schema, and logged runtime associated with the specified assessment result. They provide complete context for an assessment result. The responses do not adhere to JSON API spec. You cannot access these endpoints with [organization tokens](/terraform/cloud-docs/users-teams-organizations/api-tokens#organization-api-tokens). You must access them with a [user token](/terraform/cloud-docs/users-teams-organizations/users#api-tokens) or [team token](/terraform/cloud-docs/users-teams-organizations/api-tokens#team-api-tokens) that has admin level access to the workspace. Refer to [Permissions](/terraform/cloud-docs/users-teams-organizations/permissions) for details. [permissions-citation]: #intentionally-unused---keep-for-maintainers ### JSON Plan The following endpoint returns the JSON plan output associated with the assessment result. `GET api/v2/assessment-results/:assessment_result_id/json-output` #### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/assessment-results/asmtres-cHh5777xm/json-output ``` ### JSON Schema file The following endpoint returns the JSON [provider schema](/terraform/cli/commands/providers/schema) associated with the assessment result. `GET api/v2/assessment-results/:assessment_result_id/json-schema` #### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/assessment-results/asmtres-cHh5777xm/json-schema ``` ### JSON Log Output The following endpoint returns Terraform JSON log output. `GET api/v2/assessment-results/assessment_result_id/log-output` #### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ https://app.terraform.io/api/v2/assessment-results/asmtres-cHh5777xm/log-output ```
terraform
page title Assessments API Docs HCP Terraform description Use the assessment results endpoint to query health assessments Get continuous validation and drift detection health assessment results using the HTTP API 200 https developer mozilla org en US docs Web HTTP Status 200 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 422 https developer mozilla org en US docs Web HTTP Status 422 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 Assessment Results API An Assessment Result is the summary record of an instance of health assessment HCP Terraform can perform automatic health assessments in a workspace to assess whether its real infrastructure matches the requirements defined in its Terraform configuration Refer to Health terraform cloud docs workspaces health for more details BEGIN TFC only name pnp callout include tfc package callouts health assessments mdx END TFC only name pnp callout Show Assessment Result Any user with read access to a workspace can retrieve assessment results for the workspace GET api v2 assessment results assessment result id Parameter Description assessment result id The assessment result ID Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 assessment results asmtres cHh5777xm Sample Response json id asmtres UG5rE9L1373hMYMA type assessment results data attributes drifted true succeeded true error msg null created at 2022 07 02T22 29 58 00 00 links self api v2 assessment results asmtres UG5rE9L1373hMYMA json output api v2 assessment results asmtres UG5rE9L1373hMYMA json output json schema api v2 assessment results asmtres UG5rE9L1373hMYMA json schema log output api v2 assessment results asmtres UG5rE9L1373hMYMA log output Retrieve the JSON output from the assessment execution The following endpoints retrieve files documenting the plan schema and logged runtime associated with the specified assessment result They provide complete context for an assessment result The responses do not adhere to JSON API spec You cannot access these endpoints with organization tokens terraform cloud docs users teams organizations api tokens organization api tokens You must access them with a user token terraform cloud docs users teams organizations users api tokens or team token terraform cloud docs users teams organizations api tokens team api tokens that has admin level access to the workspace Refer to Permissions terraform cloud docs users teams organizations permissions for details permissions citation intentionally unused keep for maintainers JSON Plan The following endpoint returns the JSON plan output associated with the assessment result GET api v2 assessment results assessment result id json output Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 assessment results asmtres cHh5777xm json output JSON Schema file The following endpoint returns the JSON provider schema terraform cli commands providers schema associated with the assessment result GET api v2 assessment results assessment result id json schema Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 assessment results asmtres cHh5777xm json schema JSON Log Output The following endpoint returns Terraform JSON log output GET api v2 assessment results assessment result id log output Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json https app terraform io api v2 assessment results asmtres cHh5777xm log output
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 page title Project Team Access API Docs HCP Terraform Use the team projects endpoint to manage team access to a project List show add update and remove team access from a project using the HTTP API
--- page_title: Project Team Access - API Docs - HCP Terraform description: >- Use the `/team-projects` endpoint to manage team access to a project. List, show, add, update, and remove team access from a project using the HTTP API. --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # Project Team Access API <!-- BEGIN: TFC:only name:pnp-callout --> -> **Note:** Team management is available in HCP Terraform **Standard** Edition. [Learn more about HCP Terraform pricing](https://www.hashicorp.com/products/terraform/pricing). <!-- END: TFC:only name:pnp-callout --> The team access APIs are used to associate a team to permissions on a project. A single `team-project` resource contains the relationship between the Team and Project, including the privileges the team has on the project. ## Resource permissions A `team-project` resource represents a team's local permissions on a specific project. Teams can also have organization-level permissions that grant access to projects. HCP Terraform uses the more restrictive access level. For example, a team with the **Manage projects** permission enabled has admin access on all projects, even if their `team-project` on a particular project only grants read access. For more information, refer to [Managing Project Access](/terraform/cloud-docs/users-teams-organizations/teams/manage#managing-project-access). Any member of an organization can view team access relative to their own team memberships, including secret teams of which they are a member. Organization owners and project admins can modify team access or view the full set of secret team accesses. The organization token and the owners team token can act as an owner on these endpoints. Refer to [Permissions](/terraform/cloud-docs/users-teams-organizations/permissions) for additional information. ## Project Team Access Levels | Access Level | Description | |-----------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `read` | Read project and Read workspace access role on project workspaces | | `write` | Read project and Write workspace access role on project workspaces | | `maintain` | Read project and Admin workspace access role on project workspaces | | `admin` | Admin project, Admin workspace access role on project workspaces, create workspaces within project, move workspaces between projects, manage project team access | | `custom` | Custom access permissions on project and project's workspaces | ## List Team Access to a Project `GET /team-projects` | Status | Response | Reason | |---------|-------------------------------------------------|----------------------------------------------------------| | [200][] | [JSON API document][] (`type: "team-projects"`) | The request was successful | | [404][] | [JSON API error object][] | Project not found or user unauthorized to perform action | ### Query Parameters [These are standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters); remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. This endpoint supports pagination [with standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). | Parameter | Description | |-----------------------|-------------------------------------------------------| | `filter[project][id]` | **Required.** The project ID to list team access for. | | `page[number]` | **Optional.** | | `page[size]` | **Optional.** | ### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ "https://app.terraform.io/api/v2/team-projects?filter%5Bproject%5D%5Bid%5D=prj-ckZoJwdERaWcFHwi" ``` ### Sample Response ```json { "data": [ { "id": "tprj-TLznAnYdcsD2Dcmm", "type": "team-projects", "attributes": { "access": "read", "project-access": { "settings": "read", "teams": "none" }, "workspace-access": { "create": false, "move": false, "locking": false, "delete": false, "runs": "read", "variables": "read", "state-versions": "read", "sentinel-mocks": "none", "run-tasks": false } }, "relationships": { "team": { "data": { "id": "team-KpibQGL5GqRAWBwT", "type": "teams" }, "links": { "related": "/api/v2/teams/team-KpibQGL5GqRAWBwT" } }, "project": { "data": { "id": "prj-ckZoJwdERaWcFHwi", "type": "projects" }, "links": { "related": "/api/v2/projects/prj-ckZoJwdERaWcFHwi" } } }, "links": { "self": "/api/v2/team-projects/tprj-TLznAnYdcsD2Dcmm" } } ], "links": { "self": "https://app.terraform.io/api/v2/team-projects?filter%5Bproject%5D%5Bid%5D=prj-ckZoJwdERaWcFHwi&page%5Bnumber%5D=1&page%5Bsize%5D=20", "first": "https://app.terraform.io/api/v2/team-projects?filter%5Bproject%5D%5Bid%5D=prj-ckZoJwdERaWcFHwi&page%5Bnumber%5D=1&page%5Bsize%5D=20", "prev": null, "next": null, "last": "https://app.terraform.io/api/v2/team-projects?filter%5Bproject%5D%5Bid%5D=prj-ckZoJwdERaWcFHwi&page%5Bnumber%5D=1&page%5Bsize%5D=20" }, "meta": { "pagination": { "current-page": 1, "page-size": 20, "prev-page": null, "next-page": null, "total-pages": 1, "total-count": 1 } } } ``` ## Show a Team Access relationship `GET /team-projects/:id` | Status | Response | Reason | |---------|-------------------------------------------------|--------------------------------------------------------------| | [200][] | [JSON API document][] (`type: "team-projects"`) | The request was successful | | [404][] | [JSON API error object][] | Team access not found or user unauthorized to perform action | | Parameter | Description | |-----------|------------------------------------------------------------------------------------------------------------------------------------------| | `:id` | The ID of the team/project relationship. Obtain this from the [list team access action](#list-team-access-to-a-project) described above. | As mentioned in [Add Team Access to a Project](#add-team-access-to-a-project) and [Update to a Project](#update-team-access-to-a-project), several permission attributes are not editable unless you set `access` to `custom`. If you set `access` to `read`, `plan`, `write`, or `admin`, certain attributes are read-only and reflect the _implicit permissions_ granted to the current access level. For example, if you set `access` to `read`, the implicit permission level for project settings and workspace run is "read". Conversely, if you set the access level to `admin`, the implicit permission level for the project settings is "delete", while the workspace runs permission is "apply". Several permission attributes are not editable unless `access` is set to `custom`. When access is `read`, `plan`, `write`, or `admin`, these attributes are read-only and reflect the implicit permissions granted to the current access level. For example, when access is `read`, the implicit level for the project settings and workspace runs permissions are "read". Conversely, when the access level is `admin`, the implicit level for the project settings is "delete" and the workspace runs permission is "apply". To see all of the implied permissions at different access levels, see [Implied Custom Permission Levels](#implied-custom-permission-levels). ### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request GET \ https://app.terraform.io/api/v2/team-projects/tprj-s68jV4FWCDwWvQq8 ``` ### Sample Response ```json { "data": { "id": "tprj-TLznAnYdcsD2Dcmm", "type": "team-projects", "attributes": { "access": "read", "project-access": { "settings": "read", "teams": "none" }, "workspace-access": { "create": false, "move": false, "locking": false, "delete": false, "runs": "read", "variables": "read", "state-versions": "read", "sentinel-mocks": "none", "run-tasks": false } }, "relationships": { "team": { "data": { "id": "team-KpibQGL5GqRAWBwT", "type": "teams" }, "links": { "related": "/api/v2/teams/team-KpibQGL5GqRAWBwT" } }, "project": { "data": { "id": "prj-ckZoJwdERaWcFHwi", "type": "projects" }, "links": { "related": "/api/v2/projects/prj-ckZoJwdERaWcFHwi" } } }, "links": { "self": "/api/v2/team-projects/tprj-TLznAnYdcsD2Dcmm" } } } ``` ## Add Team Access to a Project `POST /team-projects` | Status | Response | Reason | |---------|-------------------------------------------------|------------------------------------------------------------------| | [200][] | [JSON API document][] (`type: "team-projects"`) | The request was successful | | [404][] | [JSON API error object][] | Project or Team not found or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (missing attributes, wrong types, etc.) | ### Request Body This POST endpoint requires a JSON object with the following properties as a request payload. Properties without a default value are required. | Key path | Type | Default | Description | |-----------------------------------------------------------|-------- |---------|----------------------------------------------------------------------------------------------------| | `data.type` | string | | Must be `"team-projects"`. | | `data.attributes.access` | string | | The type of access to grant. Valid values are `read`, `write`, `maintain`, `admin`, or `custom`. | | `data.relationships.project.data.type` | string | | Must be `projects`. | | `data.relationships.project.data.id` | string | | The project ID to which the team is to be added. | | `data.relationships.team.data.type` | string | | Must be `teams`. | | `data.relationships.team.data.id` | string | | The ID of the team to add to the project. | | `data.attributes.project-access.settings` | string | "read" | If `access` is `custom`, the permission to grant for the project's settings. Can only be used when `access` is `custom`. Valid values include `read`, `update`, or `delete`. | | `data.attributes.project-access.teams` | string | "none" | If `access` is `custom`, the permission to grant for the project's teams. Can only be used when `access` is `custom`. Valid values include `none`, `read`, or `manage`. | | `data.attributes.workspace-access.runs` | string | "read" | If `access` is `custom`, the permission to grant for the project's workspaces' runs. Can only be used when `access` is `custom`. Valid values include `read`, `plan`, or `apply`. | | `data.attributes.workspace-access.sentinel-mocks` | string | "none" | If `access` is `custom`, the permission to grant for the project's workspaces' Sentinel mocks. Can only be used when `access` is `custom`. Valid values include `none`, or `read`. | | `data.attributes.workspace-access.state-versions` | string | "none" | If `access` is `custom`, the permission to grant for the project's workspaces state versions. Can only be used when `access` is `custom`. Valid values include `none`, `read-outputs`, `read`, or `write`. | | `data.attributes.workspace-access.variables` | string | "none" | If `access` is `custom`, the permission to grant for the project's workspaces' variables. Can only be used when `access` is `custom`. Valid values include `none`, `read`, or `write`. | | `data.attributes.workspace-access.create` | boolean | false | If `access` is `custom`, this permission allows the team to create workspaces in the project. | | `data.attributes.workspace-access.locking` | boolean | false | If `access` is `custom`, the permission granting the ability to manually lock or unlock the project's workspaces. Can only be used when `access` is `custom`. | | `data.attributes.workspace-access.delete` | boolean | false | If `access` is `custom`, the permission granting the ability to delete the project's workspaces. Can only be used when `access` is `custom`. | | `data.attributes.workspace-access.move` | boolean | false | If `access` is `move`, this permission allows the team to move workspaces into and out of the project. The team must also have permissions to the project(s) receiving the the workspace(s). | | `data.attributes.workspace-access.run-tasks` | boolean | false | If `access` is `custom`, this permission allows the team to manage run tasks within the project's workspaces. | ### Sample Payload ```json { "data": { "attributes": { "access": "read" }, "relationships": { "project": { "data": { "type": "projects", "id": "prj-ckZoJwdERaWcFHwi" } }, "team": { "data": { "type": "teams", "id": "team-xMGyoUhKmTkTzmAy" } } }, "type": "team-projects" } } ``` ### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data @payload.json \ https://app.terraform.io/api/v2/team-projects ``` ### Sample Response ```json { "data": { "id": "tprj-WbG7p5KnT7S7HZqw", "type": "team-projects", "attributes": { "access": "read", "project-access": { "settings": "read", "teams": "none" }, "workspace-access": { "create": false, "move": false, "locking": false, "runs": "read", "variables": "read", "state-versions": "read", "sentinel-mocks": "none", "run-tasks": false } }, "relationships": { "team": { "data": { "id": "team-xMGyoUhKmTkTzmAy", "type": "teams" }, "links": { "related": "/api/v2/teams/team-xMGyoUhKmTkTzmAy" } }, "project": { "data": { "id": "prj-ckZoJwdERaWcFHwi", "type": "projects" }, "links": { "related": "/api/v2/projects/prj-ckZoJwdERaWcFHwi" } } }, "links": { "self": "/api/v2/team-projects/tprj-WbG7p5KnT7S7HZqw" } } } ``` ## Update Team Access to a Project `PATCH /team-projects/:id` | Status | Response | Reason | |---------|-------------------------------------------------|----------------------------------------------------------------| | [200][] | [JSON API document][] (`type: "team-projects"`) | The request was successful | | [404][] | [JSON API error object][] | Team Access not found or user unauthorized to perform action | | [422][] | [JSON API error object][] | Malformed request body (missing attributes, wrong types, etc.) | | Parameter | | | Description | |--------------------------|--------|-----|------------------------------------------------------------------------------------------------------------------------------------------| | `:id` | | | The ID of the team/project relationship. Obtain this from the [list team access action](#list-team-access-to-a-project) described above. | | `data.attributes.access` | string | | The type of access to grant. Valid values are `read`, `write`, `maintain`, `admin`, or `custom`. | ### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request PATCH \ --data @payload.json \ https://app.terraform.io/api/v2/team-projects/tprj-WbG7p5KnT7S7HZqw ``` ### Sample Payload ```json { "data": { "id": "tprj-WbG7p5KnT7S7HZqw", "attributes": { "access": "custom", "project-access": { "settings": "delete" "teams": "manage", }, "workspace-access" : { "runs": "apply", "sentinel-mocks": "read", "state-versions": "write", "variables": "write", "create": true, "locking": true, "delete": true, "move": true, "run-tasks": true } } } } ``` ### Sample Response ```json { "data": { "id": "tprj-WbG7p5KnT7S7HZqw", "type": "team-projects", "attributes": { "access": "custom", "project-access": { "settings": "delete" "teams": "manage", }, "workspace-access" : { "runs": "apply", "sentinel-mocks": "read", "state-versions": "write", "variables": "write", "create": true, "locking": true, "delete": true, "move": true, "run-tasks": true } }, "relationships": { "team": { "data": { "id": "team-xMGyoUhKmTkTzmAy", "type": "teams" }, "links": { "related": "/api/v2/teams/team-xMGyoUhKmTkTzmAy" } }, "project": { "data": { "id": "prj-ckZoJwdERaWcFHwi", "type": "projects" }, "links": { "related": "/api/v2/projects/prj-ckZoJwdERaWcFHwi" } } }, "links": { "self": "/api/v2/team-projects/tprj-WbG7p5KnT7S7HZqw" } } } ``` ## Remove Team Access from a Project `DELETE /team-projects/:id` | Status | Response | Reason | |---------|---------------------------|--------------------------------------------------------------| | [204][] | | The Team Access was successfully destroyed | | [404][] | [JSON API error object][] | Team Access not found or user unauthorized to perform action | | Parameter | Description | |-----------|------------------------------------------------------------------------------------------------------------------------------------------| | `:id` | The ID of the team/project relationship. Obtain this from the [list team access action](#list-team-access-to-a-project) described above. | ### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request DELETE \ https://app.terraform.io/api/v2/team-projects/tprj-WbG7p5KnT7S7HZqw ``` ## Implied Custom Permission Levels As mentioned above, when setting team access levels (`read`, `write`, `maintain`, or `admin`), you can individually set the following permissions if you use the `custom` access level. The below table lists each access level alongside its implicit custom permission level. If you use the `custom` access level and do not specify a certain permission's level, that permission uses the default value listed below. | Permissions | `read` | `write` | `maintain` | `admin ` | `custom` default | |---------------------------------|--------|---------|------------|----------|------------------| | project-access.settings | "read" | "read" | "read" | "delete" | "read" | | project-access.teams | "none" | "none" | "none" | "manage" | "none" | | workspace-access.runs | "read" | "apply" | "apply" | "apply" | "read" | | workspace-access.sentinel-mocks | "none" | "read" | "read" | "read" | "none" | | workspace-access.state-versions | "read" | "write" | "write" | "write" | "none" | | workspace-access.variables | "read" | "write" | "write" | "write" | "none" | | workspace-access.create | false | false | true | true | false | | workspace-access.locking | false | true | true | true | false | | workspace-access.delete | false | false | true | true | false | | workspace-access.move | false | false | false | true | false | | workspace-access.run-tasks | false | false | true | true | false |
terraform
page title Project Team Access API Docs HCP Terraform description Use the team projects endpoint to manage team access to a project List show add update and remove team access from a project using the HTTP API 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects Project Team Access API BEGIN TFC only name pnp callout Note Team management is available in HCP Terraform Standard Edition Learn more about HCP Terraform pricing https www hashicorp com products terraform pricing END TFC only name pnp callout The team access APIs are used to associate a team to permissions on a project A single team project resource contains the relationship between the Team and Project including the privileges the team has on the project Resource permissions A team project resource represents a team s local permissions on a specific project Teams can also have organization level permissions that grant access to projects HCP Terraform uses the more restrictive access level For example a team with the Manage projects permission enabled has admin access on all projects even if their team project on a particular project only grants read access For more information refer to Managing Project Access terraform cloud docs users teams organizations teams manage managing project access Any member of an organization can view team access relative to their own team memberships including secret teams of which they are a member Organization owners and project admins can modify team access or view the full set of secret team accesses The organization token and the owners team token can act as an owner on these endpoints Refer to Permissions terraform cloud docs users teams organizations permissions for additional information Project Team Access Levels Access Level Description read Read project and Read workspace access role on project workspaces write Read project and Write workspace access role on project workspaces maintain Read project and Admin workspace access role on project workspaces admin Admin project Admin workspace access role on project workspaces create workspaces within project move workspaces between projects manage project team access custom Custom access permissions on project and project s workspaces List Team Access to a Project GET team projects Status Response Reason 200 JSON API document type team projects The request was successful 404 JSON API error object Project not found or user unauthorized to perform action Query Parameters These are standard URL query parameters terraform cloud docs api docs query parameters remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs This endpoint supports pagination with standard URL query parameters terraform cloud docs api docs query parameters Parameter Description filter project id Required The project ID to list team access for page number Optional page size Optional Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 team projects filter 5Bproject 5D 5Bid 5D prj ckZoJwdERaWcFHwi Sample Response json data id tprj TLznAnYdcsD2Dcmm type team projects attributes access read project access settings read teams none workspace access create false move false locking false delete false runs read variables read state versions read sentinel mocks none run tasks false relationships team data id team KpibQGL5GqRAWBwT type teams links related api v2 teams team KpibQGL5GqRAWBwT project data id prj ckZoJwdERaWcFHwi type projects links related api v2 projects prj ckZoJwdERaWcFHwi links self api v2 team projects tprj TLznAnYdcsD2Dcmm links self https app terraform io api v2 team projects filter 5Bproject 5D 5Bid 5D prj ckZoJwdERaWcFHwi page 5Bnumber 5D 1 page 5Bsize 5D 20 first https app terraform io api v2 team projects filter 5Bproject 5D 5Bid 5D prj ckZoJwdERaWcFHwi page 5Bnumber 5D 1 page 5Bsize 5D 20 prev null next null last https app terraform io api v2 team projects filter 5Bproject 5D 5Bid 5D prj ckZoJwdERaWcFHwi page 5Bnumber 5D 1 page 5Bsize 5D 20 meta pagination current page 1 page size 20 prev page null next page null total pages 1 total count 1 Show a Team Access relationship GET team projects id Status Response Reason 200 JSON API document type team projects The request was successful 404 JSON API error object Team access not found or user unauthorized to perform action Parameter Description id The ID of the team project relationship Obtain this from the list team access action list team access to a project described above As mentioned in Add Team Access to a Project add team access to a project and Update to a Project update team access to a project several permission attributes are not editable unless you set access to custom If you set access to read plan write or admin certain attributes are read only and reflect the implicit permissions granted to the current access level For example if you set access to read the implicit permission level for project settings and workspace run is read Conversely if you set the access level to admin the implicit permission level for the project settings is delete while the workspace runs permission is apply Several permission attributes are not editable unless access is set to custom When access is read plan write or admin these attributes are read only and reflect the implicit permissions granted to the current access level For example when access is read the implicit level for the project settings and workspace runs permissions are read Conversely when the access level is admin the implicit level for the project settings is delete and the workspace runs permission is apply To see all of the implied permissions at different access levels see Implied Custom Permission Levels implied custom permission levels Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request GET https app terraform io api v2 team projects tprj s68jV4FWCDwWvQq8 Sample Response json data id tprj TLznAnYdcsD2Dcmm type team projects attributes access read project access settings read teams none workspace access create false move false locking false delete false runs read variables read state versions read sentinel mocks none run tasks false relationships team data id team KpibQGL5GqRAWBwT type teams links related api v2 teams team KpibQGL5GqRAWBwT project data id prj ckZoJwdERaWcFHwi type projects links related api v2 projects prj ckZoJwdERaWcFHwi links self api v2 team projects tprj TLznAnYdcsD2Dcmm Add Team Access to a Project POST team projects Status Response Reason 200 JSON API document type team projects The request was successful 404 JSON API error object Project or Team not found or user unauthorized to perform action 422 JSON API error object Malformed request body missing attributes wrong types etc Request Body This POST endpoint requires a JSON object with the following properties as a request payload Properties without a default value are required Key path Type Default Description data type string Must be team projects data attributes access string The type of access to grant Valid values are read write maintain admin or custom data relationships project data type string Must be projects data relationships project data id string The project ID to which the team is to be added data relationships team data type string Must be teams data relationships team data id string The ID of the team to add to the project data attributes project access settings string read If access is custom the permission to grant for the project s settings Can only be used when access is custom Valid values include read update or delete data attributes project access teams string none If access is custom the permission to grant for the project s teams Can only be used when access is custom Valid values include none read or manage data attributes workspace access runs string read If access is custom the permission to grant for the project s workspaces runs Can only be used when access is custom Valid values include read plan or apply data attributes workspace access sentinel mocks string none If access is custom the permission to grant for the project s workspaces Sentinel mocks Can only be used when access is custom Valid values include none or read data attributes workspace access state versions string none If access is custom the permission to grant for the project s workspaces state versions Can only be used when access is custom Valid values include none read outputs read or write data attributes workspace access variables string none If access is custom the permission to grant for the project s workspaces variables Can only be used when access is custom Valid values include none read or write data attributes workspace access create boolean false If access is custom this permission allows the team to create workspaces in the project data attributes workspace access locking boolean false If access is custom the permission granting the ability to manually lock or unlock the project s workspaces Can only be used when access is custom data attributes workspace access delete boolean false If access is custom the permission granting the ability to delete the project s workspaces Can only be used when access is custom data attributes workspace access move boolean false If access is move this permission allows the team to move workspaces into and out of the project The team must also have permissions to the project s receiving the the workspace s data attributes workspace access run tasks boolean false If access is custom this permission allows the team to manage run tasks within the project s workspaces Sample Payload json data attributes access read relationships project data type projects id prj ckZoJwdERaWcFHwi team data type teams id team xMGyoUhKmTkTzmAy type team projects Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request POST data payload json https app terraform io api v2 team projects Sample Response json data id tprj WbG7p5KnT7S7HZqw type team projects attributes access read project access settings read teams none workspace access create false move false locking false runs read variables read state versions read sentinel mocks none run tasks false relationships team data id team xMGyoUhKmTkTzmAy type teams links related api v2 teams team xMGyoUhKmTkTzmAy project data id prj ckZoJwdERaWcFHwi type projects links related api v2 projects prj ckZoJwdERaWcFHwi links self api v2 team projects tprj WbG7p5KnT7S7HZqw Update Team Access to a Project PATCH team projects id Status Response Reason 200 JSON API document type team projects The request was successful 404 JSON API error object Team Access not found or user unauthorized to perform action 422 JSON API error object Malformed request body missing attributes wrong types etc Parameter Description id The ID of the team project relationship Obtain this from the list team access action list team access to a project described above data attributes access string The type of access to grant Valid values are read write maintain admin or custom Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request PATCH data payload json https app terraform io api v2 team projects tprj WbG7p5KnT7S7HZqw Sample Payload json data id tprj WbG7p5KnT7S7HZqw attributes access custom project access settings delete teams manage workspace access runs apply sentinel mocks read state versions write variables write create true locking true delete true move true run tasks true Sample Response json data id tprj WbG7p5KnT7S7HZqw type team projects attributes access custom project access settings delete teams manage workspace access runs apply sentinel mocks read state versions write variables write create true locking true delete true move true run tasks true relationships team data id team xMGyoUhKmTkTzmAy type teams links related api v2 teams team xMGyoUhKmTkTzmAy project data id prj ckZoJwdERaWcFHwi type projects links related api v2 projects prj ckZoJwdERaWcFHwi links self api v2 team projects tprj WbG7p5KnT7S7HZqw Remove Team Access from a Project DELETE team projects id Status Response Reason 204 The Team Access was successfully destroyed 404 JSON API error object Team Access not found or user unauthorized to perform action Parameter Description id The ID of the team project relationship Obtain this from the list team access action list team access to a project described above Sample Request shell curl header Authorization Bearer TOKEN header Content Type application vnd api json request DELETE https app terraform io api v2 team projects tprj WbG7p5KnT7S7HZqw Implied Custom Permission Levels As mentioned above when setting team access levels read write maintain or admin you can individually set the following permissions if you use the custom access level The below table lists each access level alongside its implicit custom permission level If you use the custom access level and do not specify a certain permission s level that permission uses the default value listed below Permissions read write maintain admin custom default project access settings read read read delete read project access teams none none none manage none workspace access runs read apply apply apply read workspace access sentinel mocks none read read read none workspace access state versions read write write write none workspace access variables read write write write none workspace access create false false true true false workspace access locking false true true true false workspace access delete false false true true false workspace access move false false false true false workspace access run tasks false false true true false
terraform 200 https developer mozilla org en US docs Web HTTP Status 200 Use the organization audit trail endpoint to query audit events Get a list of an organization s audit events for the past 14 days using the HTTP API page title Audit Trails API Docs HCP Terraform 201 https developer mozilla org en US docs Web HTTP Status 201 tfc only true
--- page_title: Audit Trails - API Docs - HCP Terraform description: >- Use the `/organization/audit-trail` endpoint to query audit events. Get a list of an organization's audit events for the past 14 days using the HTTP API. tfc_only: true --- [200]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200 [201]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 [202]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 [400]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 [401]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401 [403]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403 [404]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 [409]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 [412]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412 [422]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 [429]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429 [500]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500 [504]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504 [JSON API document]: /terraform/cloud-docs/api-docs#json-api-documents [JSON API error object]: https://jsonapi.org/format/#error-objects # Audit Trails API HCP Terraform retains 14 days of audit log information. The audit trails API exposes a stream of audit events, which describe changes to the application entities (workspaces, runs, etc.) that belong to an HCP Terraform organization. Unlike other APIs, the Audit Trails API does not use the [JSON API specification](/terraform/cloud-docs/api-docs#json-api-formatting). <!-- BEGIN: TFC:only name:pnp-callout --> @include 'tfc-package-callouts/audit-trails.mdx' <!-- END: TFC:only name:pnp-callout --> ## List an organization's audit events `GET /organization/audit-trail` -> **Note:** This endpoint cannot be accessed with a [user token](/terraform/cloud-docs/users-teams-organizations/users#api-tokens) or [team token](/terraform/cloud-docs/users-teams-organizations/api-tokens#team-api-tokens). You must access it with an [organization token](/terraform/cloud-docs/users-teams-organizations/api-tokens#organization-api-tokens). ### Query Parameters [These are standard URL query parameters](/terraform/cloud-docs/api-docs#query-parameters). Remember to percent-encode `[` as `%5B` and `]` as `%5D` if your tooling doesn't automatically encode URLs. | Parameter | Description | | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `since` | **Optional.** Returns only audit trails created after this date (UTC and in [ISO8601 Format](https://www.iso.org/iso-8601-date-and-time-format.html) - YYYY-MM-DDTHH:MM:SS.SSSZ) | | `page[number]` | **Optional.** If omitted, the endpoint will return the first page. | | `page[size]` | **Optional.** If omitted, the endpoint will return 1000 audit events per page. | ### Sample Request ```shell $ curl \ --header "Authorization: Bearer $TOKEN" \ --request GET \ "https://app.terraform.io/api/v2/organization/audit-trail?page[number]=1&since=2020-05-30T17:52:46.000Z" ``` ### Sample Response ```json { "data": [ { "id": "ae66e491-db59-457c-8445-9c908ee726ae", "version": "0", "type": "Resource", "timestamp": "2020-06-30T17:52:46.000Z", "auth": { "accessor_id": "user-MaPuLxAXvtq2PWTH", "description": "pveverka", "type": "Client", "impersonator_id": null, "organization_id": "org-AGLwRmx1snv34Yts" }, "request": { "id": "4df584d4-7e2a-01e6-6cc0-4adbefa020e6" }, "resource": { "id": "at-sjt83qTw3GZatuPm", "type": "authentication_token", "action": "create", "meta": null } } ], "pagination": { "current_page": 1, "prev_page": null, "next_page": 2, "total_pages": 8, "total_count": 778 } } ``` ## Standard response fields Every audit log event in the response array includes the following standard fields: | Key | Data Type or format | Description | | ---------------------- | ------------ | ----------------------------------------------------------- | | `id` | UUID | The ID of this audit trail | | `version` | number | The audit trail schema version | | `type` | string | The type of audit trail (defaults to `Resource`) | | `timestamp` | string | UTC ISO8601 DateTime (for example,`2020-06-16T20:26:58.000Z`) | | `auth.accessor_id` | string | The ID of audited actor (for example, `user-V3R563qtJNcExAkN`) | | `auth.description` | string | Username of audited actor | | `auth.type` | string | Authentication type, is either `Client`, `Impersonated`, or `System`. | | `auth.impersonator_id` | string | The ID of impersonating actor (if available) | | `auth.organization_id` | string | The ID of organization (for example, `org-QpXoEnULx3r2r1CA`) | | `request.id` | UUID | The ID for request (if available) | | `resource.id` | string | The ID of resource (for example,`run-FwnENkvDnrpyFC7M`) | | `resource.type` | string | Type of resource (for example, `run`) | | `resource.action` | string | Action audited (for example, `applied`) | | `resource.meta` | map | Key-value metadata about this audited event (defaults to `null`) | The following audit trail events _only_ contain these standard fields: | Event | Action | Description | |----------------------------|--------------------------------------------------------------|------------------------------------------------------------| | `agent` | `destroy` | Logged when an agent is destroyed. | | `authentication_token` | `create`, `show`, `destroy` | Events related to authentication tokens. | | `configuration_version` | `show`, `download` | Events related to configuration versions. | | `notification_configuration` | `create`, `update`, `destroy`, `enable` | Events related to notification configurations. | | `oauth_client` | `create`, `update`, `destroy` | Events related to OAuth clients. | | `oauth_token` | `index`, `show`, `update`, `destroy` | Events related to OAuth tokens. | | `organization` | `create`, `update`, `destroy` | Events related to organizations. | | `organization_user` | `create`, `update`, `destroy` | Events related to organization users. | | `policy` | `update`, `destroy` | Events related to policies. | | `policy_check` | `override` | Events related to policy checks. | | `policy_config` | `create` | Events related to policy configurations. | | `policy_set` | `destroy` | Events related to policy sets. | | `policy_version` | `create` | Events related to policy versions. | | `project` | `create`, `update`, `destroy` | Events related to projects. | | `registry_module` | `destroy`, `update` | Events related to registry modules. | | `registry_provider` | `create`, `destroy` | Events related to registry providers. | | `registry_provider_platform` | `create`, `destroy` | Events related to registry provider platforms. | | `registry_provider_version` | `create`, `destroy` | Events related to registry provider versions. | | `run` | `apply`, `cancel`, `force_cancel`, `discard`, `force_execute`, `create` | Events related to runs. | | `run_trigger` | `create`, `destroy` | Events related to run triggers. | | `saml_configuration` | `create`, `update`, `destroy`, `enable`, `disable` | Events related to SAML configurations. | | `ssh_key` | `index`, `show`, `create`, `update`, `destroy` | Events related to SSH keys. | | `stack` | `create` | Events related to creating stacks. | | `state_version` | `index`, `show`, `create`, `soft_delete_backing_data`, `restore_backing_data`, `permanently_delete_backing_data` | Events related to state versions. | | `task_stage` | `override` | Events related to an overridden task stage. | | `user` | `index` | Events related to indexing users. | | `var` | `index`, `show`, `create`, `update`, `destroy` | Events related to variables. | | `vcs_repo` | `create` | Events related to creating a connection to a VCS repo. | The following sections list the audit log events containing both the standard response schema and a specific payload for each action. ## Data retention policy events You can define [data retention policies](/terraform/cloud-docs/workspaces/settings/deletion#data-retention-policies) to help reduce object storage consumption. ### Destroy An HCP Terraform organization emits this event when it destroys a data retention policy(`data_retention_policy`). Alongside the [standard audit trail fields](#standard-response-fields), this event response includes the following fields: | Key | Data Type | Description | | --- | --- | --- | | `delete_older_than_n_days` | integer | The number of days to retain data before deletion. Must be greater than 0. | | `organization` | string | The organization associated with the data retention policy. | | `organization_id` | string | The ID of the organization associated with the data retention policy. | ## Project events [Projects](/terraform/cloud-docs/projects/manage) let you organize your workspaces and scope access to workspace resources. ### Add Team An HCP Terraform organization emits this event when someone in your organization adds a team(`add_team`) to a project. Alongside the [standard audit trail fields](#standard-response-fields), this event response includes the following fields: | Key | Data Type | Description | | --- | --- | --- | | `team` | string | The name or identifier of the team. | | `permissions` | string | The permissions granted to the team. | ### Update Team Permissions An HCP Terraform organization emits this event when someone in your organization updates the permissions(`update_team_permissions`) of a team on a project. Alongside the [standard audit trail fields](#standard-response-fields), this event response includes the following fields: | Key | Data Type | Description | | --- | --- | --- | | `team` | string | The name or identifier of the team. | | `permissions` | string | The updated permissions for the team. | ### Remove Team An HCP Terraform organization emits this event when someone in your organization removes a team(`remove_team`) from a project. Alongside the [standard audit trail fields](#standard-response-fields), this event response includes the following fields: | Key | Data Type | Description | | --- | --- | --- | | `team` | string | The name or identifier of the team. | ## Policy checks [Policy checks run Sentinel policies](/terraform/enterprise/policy-enforcement/manage-policy-sets). Policy checks have a lifecycle that includes the following events: * `passed` * `queued` * `passed` * `soft_failed` * `hard_failed` * `overridden` * `canceled` * `force_canceled` * `errored` Every policy check event in the response array includes the following standard fields: | Key | Data Type | Description | | --- | --- | --- | | `comment` | `null` or string | The comment associated with the policy check. | | `run.id` | string | The ID of the associated run. | | `run.message` | string | The message associated with the run. | | `workspace.id` | string | The ID of the associated workspace. | | `workspace.name` | string | The name of the associated workspace. | ### Passed, soft failed, hard failed, and errored Alongside the [standard audit trail fields](#standard-response-fields) and [standard policy check fields](#policy-checks), certain policy check events include a result (`includes_result`) and return the following fields: | Key | Data Type | Description | | --------------------- | --------------- | ----------------------------------------------- | | `result` | [Policy Result] | An array of policy results. | | `passed` | integer | Number of policy checks passed. | | `total_failed` | integer | Total number of failed policy checks. | | `hard_failed` | integer | Number of policy checks with hard failures. | | `soft_failed` | integer | Number of policy checks with soft failures. | | `advisory_failed` | integer | Number of policy checks with advisory failures. | | `duration_ms` | integer | Duration of the policy check in milliseconds. | | `sentinel` | string | The Sentinel policy associated with the check. | ### Overridden, canceled, and force canceled Alongside the [standard audit trail fields](#standard-response-fields) and [standard policy check fields](#policy-checks), certain event responses include the following fields: | Key | Data Type | Description | | --- | --- | --- | | `actor` | string | The user who performed the action. | ## Policy evaluation [Policy evaluations](/terraform/enterprise/policy-enforcement/policy-results#view-policy-results) run in the HCP Terraform agent in HCP Terraform's infrastructure. Policy evaluations have a lifecycle that includes the following events: * `queue` * `run` * `pass` * `fail` * `override` * `error` * `cancel` * `force_cancel` Every policy evaluation event in the response array includes the following standard fields: | Key | Data Type | Description | | --- | --- | --- | | `comment` | `null` or string | The comment associated with policy evaluation. | | `payload.workspace.id` | string | The ID of the associated workspace. | | `payload.workspace.name` | string | The name of the associated workspace. | | `payload.run.id` | string | The ID of the associated run. | | `payload.run.message` | string | The message associated with the run. | | `actor` | string | The policy owner. | Policy checks and policy evaluations serve the same purpose, but have different workflows for enforcing policies. For more information, refer to [Differences between policy checks and policy evaluations](/terraform/enterprise/policy-enforcement/manage-policy-sets#differences-between-policy-checks-and-policy-evaluations). ## Registry module events [HCP Terraform's private registry](/terraform/cloud-docs/registry) lets you share Terraform providers and Terraform modules across your organization. ### Destroy version An HCP Terraform organization emits this event when someone in your organization destroys a specific version of a registry module(`destroy_version`). Alongside the [standard audit trail fields](#standard-response-fields), this event response includes the following fields: | Key | Data Type | Description | | --- | --- | --- | | `version` | integer | The version number of the registry module to destroy. | ## Run task events You can create HCP Terraform [run tasks](/terraform/cloud-docs/workspaces/settings/run-tasks) at an organization level to directly integrate third-party tools and services at certain stages in the HCP Terraform run lifecycle. You can use run tasks to validate Terraform configuration files, analyze execution plans before applying them, scan for security vulnerabilities, or perform other custom actions. ### Create An HCP Terraform organization emits this event when someone in your organization creates a task. Alongside the [standard audit trail fields](#standard-response-fields), this event response includes the following fields: | Key | Data Type | Description | | --- | --- | --- | | `task_name` | string | The name of the task. | | `task_category` | string | The task's category | | `task_url` | string | The task's URL. | | `task_enabled` | boolean | Indicates whether the task is enabled or not. | | `task_hmac_key_present` | boolean | Specifies if an HMAC key is present for the task. | ### Destroy An HCP Terraform organization emits this event when someone in your organization destroys a task. Alongside the [standard audit trail fields](#standard-response-fields), this event response includes the following fields: | Key | Data Type | Description | | --- | --- | --- | | `task_name` | string | The name of the task to be destroyed. | | `task_category` | string | The category of the task to be destroyed. | | `task_url` | string | The URL associated with the task to be destroyed. | | `task_enabled` | boolean | Indicates whether the task to be destroyed is enabled. | | `task_hmac_key_present` | boolean | Specifies if an HMAC key is present for the task to be destroyed. | ### Update An HCP Terraform organization emits this event when someone in your organization updates a task. Alongside the [standard audit trail fields](#standard-response-fields), this event response includes the following fields: | Key | Data Type | Description | | --- | --- | --- | | `task_name` | string | The name of the task to be updated. | | `task_category` | string | The updated category of the task. | | `task_url` | string | The updated URL associated with the task. | | `task_enabled` | boolean | Indicates whether the task is enabled after the update. | | `task_hmac_key_present` | boolean | Specifies if an HMAC key is present for the updated task. | | `task_hmac_key_changed` | boolean | Indicates whether the HMAC key for the task has changed during the update. | ### Callback An HCP Terraform organization emits this event when a [run task](/terraform/cloud-docs/workspaces/settings/run-tasks) result's (`task_result`) callback action occurs. Alongside the [standard audit trail fields](#standard-response-fields), this event response includes the following fields: | Key | Data Type | Description | | --- | --- | --- | | `task_result_status` | string | The status of the task result. | | `task_result_url` | string | The URL associated with the task result. | | `task_result_message` | string | A message associated with the task result. | | `workspace` | string | The workspace related to the task result. | | `workspace_id` | string | The ID of the workspace related to the task result. | | `run_id` | string | The ID of the run associated with the task result. | | `run_created_at` | date (iso8601) | The timestamp when the run was created. | | `run_created_by` | string | The user who created the run. | | `run_message` | string | The message associated with the run. | | `run_is_speculative` | boolean | Indicates whether the run is speculative or not. | | `workspace_task_id` | string | The ID of the workspace task associated with the result. | | `workspace_task_stage` | string | The stage of the workspace task. | | `workspace_task_enforcement` | string | The enforcement level of the workspace task. | | `organization_task` | string | The organization task related to the task result. | | `organization_task_id` | string | The ID of the organization task related to the result. | | `organization_task_url` | string | The URL associated with the organization task. | ### Create a workspace's run task An HCP Terraform organization emits this event when someone in your organization [associates a new run task with a workspace](/terraform/cloud-docs/workspaces/settings/run-tasks#associating-run-tasks-with-a-workspace) (`workspace_task`). Alongside the [standard audit trail fields](#standard-response-fields), this event response includes the following fields: | Key | Data Type | Description | | --- | --- | --- | | `task_enforcement_level` | string | The task's enforcement level. | | `task_stage` | string | The stage of the task. | | `workspace` | string | The workspace associated with the task. | | `workspace_id` | string | The ID of the workspace. | | `organization_task` | string | The organization's task. | | `organization_task_id` | string | The ID of the organization's task.| ### Update a workspace's run task An HCP Terraform organization emits this event when someone in your organization updates a workspace's associated run task (`workspace_task`). Alongside the [standard audit trail fields](#standard-response-fields), this event response includes the following fields: | Key | Data Type | Description | | --- | --- | --- | | `task_enforcement_level` | string | The task's enforcement level. | | `task_stage` | string | The stage of the task. | | `workspace` | string | The workspace associated with the task. | | `workspace_id` | string | The ID of the workspace. | | `organization_task` | string | The organization's task. | | `organization_task_id` | string | The ID of the organization's task.| ### Destroy a workspace's run task An HCP Terraform organization emits this event when someone in your organization destroys a workspace's associated run task (`workspace_task`). Alongside the [standard audit trail fields](#standard-response-fields), this event response includes the following fields: | Key | Data Type | Description | | --- | --- | --- | | `task_enforcement_level` | string | The task's enforcement level. | | `task_stage` | string | The stage of the task. | | `workspace` | string | The workspace associated with the task. | | `workspace_id` | string | The ID of the workspace. | | `organization_task` | string | The organization's task. | | `organization_task_id` | string | The ID of the organization's task.| ## Team events Teams are [groups of HCP Terraform users within an organization](/terraform/cloud-docs/users-teams-organizations/teams). ### Add Member An HCP Terraform organization emits this event when someone in your organization adds a member(`add_member`) to a team. Alongside the [standard audit trail fields](#standard-response-fields), this event response includes the following fields: | Key | Data Type | Description | | --- | --- | --- | | `user` | string | The user being added to the team. | ### Remove Member An HCP Terraform organization emits this event when someone in your organization removes a member(`remove_member`) from a team. Alongside the [standard audit trail fields](#standard-response-fields), this event response includes the following fields: | Key | Data Type | Description | | --- | --- | --- | | `user` | string | The user being removed from the team. | ## Workspace comment events [Workspace comments](/terraform/cloud-docs/api-docs/comments) allow users to leave feedback or record decisions about a run. ### Create An HCP Terraform organization emits this event when someone in your organization creates a comment on a workspace(`workspace_comment`). Alongside the [standard audit trail fields](#standard-response-fields), this event response includes the following fields: | Key | Data Type | Description | | --- | --- | --- | | `resource`| string | The resource associated with the comment. | ## Workspace events HCP Terraform manages infrastructure collections with [workspaces](/terraform/cloud-docs/workspaces). ### Add Team An HCP Terraform organization emits this event when someone in your organization adds a team(`add_team`) to a workspace. Alongside the [standard audit trail fields](#standard-response-fields), this event response includes the following fields: | Key | Data Type | Description | | --- | --- | --- | | `team` | string | The name or identifier of the team. | | `permissions` | string | The permissions granted to the team. | ### Update Team Permissions An HCP Terraform organization emits this event when someone in your organization updates the permissions(`update_team_permissions`) of a team on a workspace. Alongside the [standard audit trail fields](#standard-response-fields), this event response includes the following fields: | Key | Data Type | Description | | --- | --- | --- | | `team` | string | The name or identifier of the team. | | `permissions` | string | The updated permissions for the team. | ### Remove Team An HCP Terraform organization emits this event when someone in your organization removes a team(`remove_team`) from a workspace. Alongside the [standard audit trail fields](#standard-response-fields), this event response includes the following fields: | Key | Data Type | Description | | --- | --- | --- | | `team` | string | The name or identifier of the team.
terraform
page title Audit Trails API Docs HCP Terraform description Use the organization audit trail endpoint to query audit events Get a list of an organization s audit events for the past 14 days using the HTTP API tfc only true 200 https developer mozilla org en US docs Web HTTP Status 200 201 https developer mozilla org en US docs Web HTTP Status 201 202 https developer mozilla org en US docs Web HTTP Status 202 204 https developer mozilla org en US docs Web HTTP Status 204 400 https developer mozilla org en US docs Web HTTP Status 400 401 https developer mozilla org en US docs Web HTTP Status 401 403 https developer mozilla org en US docs Web HTTP Status 403 404 https developer mozilla org en US docs Web HTTP Status 404 409 https developer mozilla org en US docs Web HTTP Status 409 412 https developer mozilla org en US docs Web HTTP Status 412 422 https developer mozilla org en US docs Web HTTP Status 422 429 https developer mozilla org en US docs Web HTTP Status 429 500 https developer mozilla org en US docs Web HTTP Status 500 504 https developer mozilla org en US docs Web HTTP Status 504 JSON API document terraform cloud docs api docs json api documents JSON API error object https jsonapi org format error objects Audit Trails API HCP Terraform retains 14 days of audit log information The audit trails API exposes a stream of audit events which describe changes to the application entities workspaces runs etc that belong to an HCP Terraform organization Unlike other APIs the Audit Trails API does not use the JSON API specification terraform cloud docs api docs json api formatting BEGIN TFC only name pnp callout include tfc package callouts audit trails mdx END TFC only name pnp callout List an organization s audit events GET organization audit trail Note This endpoint cannot be accessed with a user token terraform cloud docs users teams organizations users api tokens or team token terraform cloud docs users teams organizations api tokens team api tokens You must access it with an organization token terraform cloud docs users teams organizations api tokens organization api tokens Query Parameters These are standard URL query parameters terraform cloud docs api docs query parameters Remember to percent encode as 5B and as 5D if your tooling doesn t automatically encode URLs Parameter Description since Optional Returns only audit trails created after this date UTC and in ISO8601 Format https www iso org iso 8601 date and time format html YYYY MM DDTHH MM SS SSSZ page number Optional If omitted the endpoint will return the first page page size Optional If omitted the endpoint will return 1000 audit events per page Sample Request shell curl header Authorization Bearer TOKEN request GET https app terraform io api v2 organization audit trail page number 1 since 2020 05 30T17 52 46 000Z Sample Response json data id ae66e491 db59 457c 8445 9c908ee726ae version 0 type Resource timestamp 2020 06 30T17 52 46 000Z auth accessor id user MaPuLxAXvtq2PWTH description pveverka type Client impersonator id null organization id org AGLwRmx1snv34Yts request id 4df584d4 7e2a 01e6 6cc0 4adbefa020e6 resource id at sjt83qTw3GZatuPm type authentication token action create meta null pagination current page 1 prev page null next page 2 total pages 8 total count 778 Standard response fields Every audit log event in the response array includes the following standard fields Key Data Type or format Description id UUID The ID of this audit trail version number The audit trail schema version type string The type of audit trail defaults to Resource timestamp string UTC ISO8601 DateTime for example 2020 06 16T20 26 58 000Z auth accessor id string The ID of audited actor for example user V3R563qtJNcExAkN auth description string Username of audited actor auth type string Authentication type is either Client Impersonated or System auth impersonator id string The ID of impersonating actor if available auth organization id string The ID of organization for example org QpXoEnULx3r2r1CA request id UUID The ID for request if available resource id string The ID of resource for example run FwnENkvDnrpyFC7M resource type string Type of resource for example run resource action string Action audited for example applied resource meta map Key value metadata about this audited event defaults to null The following audit trail events only contain these standard fields Event Action Description agent destroy Logged when an agent is destroyed authentication token create show destroy Events related to authentication tokens configuration version show download Events related to configuration versions notification configuration create update destroy enable Events related to notification configurations oauth client create update destroy Events related to OAuth clients oauth token index show update destroy Events related to OAuth tokens organization create update destroy Events related to organizations organization user create update destroy Events related to organization users policy update destroy Events related to policies policy check override Events related to policy checks policy config create Events related to policy configurations policy set destroy Events related to policy sets policy version create Events related to policy versions project create update destroy Events related to projects registry module destroy update Events related to registry modules registry provider create destroy Events related to registry providers registry provider platform create destroy Events related to registry provider platforms registry provider version create destroy Events related to registry provider versions run apply cancel force cancel discard force execute create Events related to runs run trigger create destroy Events related to run triggers saml configuration create update destroy enable disable Events related to SAML configurations ssh key index show create update destroy Events related to SSH keys stack create Events related to creating stacks state version index show create soft delete backing data restore backing data permanently delete backing data Events related to state versions task stage override Events related to an overridden task stage user index Events related to indexing users var index show create update destroy Events related to variables vcs repo create Events related to creating a connection to a VCS repo The following sections list the audit log events containing both the standard response schema and a specific payload for each action Data retention policy events You can define data retention policies terraform cloud docs workspaces settings deletion data retention policies to help reduce object storage consumption Destroy An HCP Terraform organization emits this event when it destroys a data retention policy data retention policy Alongside the standard audit trail fields standard response fields this event response includes the following fields Key Data Type Description delete older than n days integer The number of days to retain data before deletion Must be greater than 0 organization string The organization associated with the data retention policy organization id string The ID of the organization associated with the data retention policy Project events Projects terraform cloud docs projects manage let you organize your workspaces and scope access to workspace resources Add Team An HCP Terraform organization emits this event when someone in your organization adds a team add team to a project Alongside the standard audit trail fields standard response fields this event response includes the following fields Key Data Type Description team string The name or identifier of the team permissions string The permissions granted to the team Update Team Permissions An HCP Terraform organization emits this event when someone in your organization updates the permissions update team permissions of a team on a project Alongside the standard audit trail fields standard response fields this event response includes the following fields Key Data Type Description team string The name or identifier of the team permissions string The updated permissions for the team Remove Team An HCP Terraform organization emits this event when someone in your organization removes a team remove team from a project Alongside the standard audit trail fields standard response fields this event response includes the following fields Key Data Type Description team string The name or identifier of the team Policy checks Policy checks run Sentinel policies terraform enterprise policy enforcement manage policy sets Policy checks have a lifecycle that includes the following events passed queued passed soft failed hard failed overridden canceled force canceled errored Every policy check event in the response array includes the following standard fields Key Data Type Description comment null or string The comment associated with the policy check run id string The ID of the associated run run message string The message associated with the run workspace id string The ID of the associated workspace workspace name string The name of the associated workspace Passed soft failed hard failed and errored Alongside the standard audit trail fields standard response fields and standard policy check fields policy checks certain policy check events include a result includes result and return the following fields Key Data Type Description result Policy Result An array of policy results passed integer Number of policy checks passed total failed integer Total number of failed policy checks hard failed integer Number of policy checks with hard failures soft failed integer Number of policy checks with soft failures advisory failed integer Number of policy checks with advisory failures duration ms integer Duration of the policy check in milliseconds sentinel string The Sentinel policy associated with the check Overridden canceled and force canceled Alongside the standard audit trail fields standard response fields and standard policy check fields policy checks certain event responses include the following fields Key Data Type Description actor string The user who performed the action Policy evaluation Policy evaluations terraform enterprise policy enforcement policy results view policy results run in the HCP Terraform agent in HCP Terraform s infrastructure Policy evaluations have a lifecycle that includes the following events queue run pass fail override error cancel force cancel Every policy evaluation event in the response array includes the following standard fields Key Data Type Description comment null or string The comment associated with policy evaluation payload workspace id string The ID of the associated workspace payload workspace name string The name of the associated workspace payload run id string The ID of the associated run payload run message string The message associated with the run actor string The policy owner Policy checks and policy evaluations serve the same purpose but have different workflows for enforcing policies For more information refer to Differences between policy checks and policy evaluations terraform enterprise policy enforcement manage policy sets differences between policy checks and policy evaluations Registry module events HCP Terraform s private registry terraform cloud docs registry lets you share Terraform providers and Terraform modules across your organization Destroy version An HCP Terraform organization emits this event when someone in your organization destroys a specific version of a registry module destroy version Alongside the standard audit trail fields standard response fields this event response includes the following fields Key Data Type Description version integer The version number of the registry module to destroy Run task events You can create HCP Terraform run tasks terraform cloud docs workspaces settings run tasks at an organization level to directly integrate third party tools and services at certain stages in the HCP Terraform run lifecycle You can use run tasks to validate Terraform configuration files analyze execution plans before applying them scan for security vulnerabilities or perform other custom actions Create An HCP Terraform organization emits this event when someone in your organization creates a task Alongside the standard audit trail fields standard response fields this event response includes the following fields Key Data Type Description task name string The name of the task task category string The task s category task url string The task s URL task enabled boolean Indicates whether the task is enabled or not task hmac key present boolean Specifies if an HMAC key is present for the task Destroy An HCP Terraform organization emits this event when someone in your organization destroys a task Alongside the standard audit trail fields standard response fields this event response includes the following fields Key Data Type Description task name string The name of the task to be destroyed task category string The category of the task to be destroyed task url string The URL associated with the task to be destroyed task enabled boolean Indicates whether the task to be destroyed is enabled task hmac key present boolean Specifies if an HMAC key is present for the task to be destroyed Update An HCP Terraform organization emits this event when someone in your organization updates a task Alongside the standard audit trail fields standard response fields this event response includes the following fields Key Data Type Description task name string The name of the task to be updated task category string The updated category of the task task url string The updated URL associated with the task task enabled boolean Indicates whether the task is enabled after the update task hmac key present boolean Specifies if an HMAC key is present for the updated task task hmac key changed boolean Indicates whether the HMAC key for the task has changed during the update Callback An HCP Terraform organization emits this event when a run task terraform cloud docs workspaces settings run tasks result s task result callback action occurs Alongside the standard audit trail fields standard response fields this event response includes the following fields Key Data Type Description task result status string The status of the task result task result url string The URL associated with the task result task result message string A message associated with the task result workspace string The workspace related to the task result workspace id string The ID of the workspace related to the task result run id string The ID of the run associated with the task result run created at date iso8601 The timestamp when the run was created run created by string The user who created the run run message string The message associated with the run run is speculative boolean Indicates whether the run is speculative or not workspace task id string The ID of the workspace task associated with the result workspace task stage string The stage of the workspace task workspace task enforcement string The enforcement level of the workspace task organization task string The organization task related to the task result organization task id string The ID of the organization task related to the result organization task url string The URL associated with the organization task Create a workspace s run task An HCP Terraform organization emits this event when someone in your organization associates a new run task with a workspace terraform cloud docs workspaces settings run tasks associating run tasks with a workspace workspace task Alongside the standard audit trail fields standard response fields this event response includes the following fields Key Data Type Description task enforcement level string The task s enforcement level task stage string The stage of the task workspace string The workspace associated with the task workspace id string The ID of the workspace organization task string The organization s task organization task id string The ID of the organization s task Update a workspace s run task An HCP Terraform organization emits this event when someone in your organization updates a workspace s associated run task workspace task Alongside the standard audit trail fields standard response fields this event response includes the following fields Key Data Type Description task enforcement level string The task s enforcement level task stage string The stage of the task workspace string The workspace associated with the task workspace id string The ID of the workspace organization task string The organization s task organization task id string The ID of the organization s task Destroy a workspace s run task An HCP Terraform organization emits this event when someone in your organization destroys a workspace s associated run task workspace task Alongside the standard audit trail fields standard response fields this event response includes the following fields Key Data Type Description task enforcement level string The task s enforcement level task stage string The stage of the task workspace string The workspace associated with the task workspace id string The ID of the workspace organization task string The organization s task organization task id string The ID of the organization s task Team events Teams are groups of HCP Terraform users within an organization terraform cloud docs users teams organizations teams Add Member An HCP Terraform organization emits this event when someone in your organization adds a member add member to a team Alongside the standard audit trail fields standard response fields this event response includes the following fields Key Data Type Description user string The user being added to the team Remove Member An HCP Terraform organization emits this event when someone in your organization removes a member remove member from a team Alongside the standard audit trail fields standard response fields this event response includes the following fields Key Data Type Description user string The user being removed from the team Workspace comment events Workspace comments terraform cloud docs api docs comments allow users to leave feedback or record decisions about a run Create An HCP Terraform organization emits this event when someone in your organization creates a comment on a workspace workspace comment Alongside the standard audit trail fields standard response fields this event response includes the following fields Key Data Type Description resource string The resource associated with the comment Workspace events HCP Terraform manages infrastructure collections with workspaces terraform cloud docs workspaces Add Team An HCP Terraform organization emits this event when someone in your organization adds a team add team to a workspace Alongside the standard audit trail fields standard response fields this event response includes the following fields Key Data Type Description team string The name or identifier of the team permissions string The permissions granted to the team Update Team Permissions An HCP Terraform organization emits this event when someone in your organization updates the permissions update team permissions of a team on a workspace Alongside the standard audit trail fields standard response fields this event response includes the following fields Key Data Type Description team string The name or identifier of the team permissions string The updated permissions for the team Remove Team An HCP Terraform organization emits this event when someone in your organization removes a team remove team from a workspace Alongside the standard audit trail fields standard response fields this event response includes the following fields Key Data Type Description team string The name or identifier of the team