HCP Terraform Cloud CLI — Complete Master Tutorial

HCP Terraform Cloud — CLI Command Summary

Organization: motoshare | Project: proezi

#Cloud operationCommand / ExampleUsage
1Login to Terraform Cloudterraform loginAuthenticate with HCP Terraform
2Login to specific hostnameterraform login app.terraform.ioAuthenticate explicitly with Terraform Cloud
3Logoutterraform logoutRemove locally saved credentials
4Authenticate using tokenexport TF_TOKEN_app_terraform_io="$TFC_TOKEN"Authenticate from CI/CD without interactive login
5Set Cloud organizationexport TF_CLOUD_ORGANIZATION=motoshareConfigure organization when omitted from the cloud block
6Set Cloud projectexport TF_CLOUD_PROJECT=proeziConfigure project when omitted from the cloud block
7Set Cloud workspaceexport TF_WORKSPACE=proezi_devSelect an existing workspace when cloud configuration permits
8Connect to Terraform Cloudterraform initInitialize the cloud block and connect the working directory
9Migrate existing state to Cloudterraform init -migrate-stateMigrate state from an existing backend to HCP Terraform
10List connected Cloud workspacesterraform workspace listList workspaces mapped by the current cloud configuration
11Show selected Cloud workspaceterraform workspace showIdentify the active workspace
12Switch to Dev workspaceterraform workspace select proezi_devSelect Dev when using a tag-based workspace configuration
13Switch to Stage workspaceterraform workspace select proezi_stageSelect Stage when using a tag-based configuration
14Switch to Prod workspaceterraform workspace select proezi_prodSelect Prod when using a tag-based configuration
15Trigger remote Cloud planterraform planExecute a speculative plan in HCP Terraform
16Trigger remote Cloud applyterraform applyStart a remote plan/apply run in a CLI-driven workspace
17Save remote Cloud planterraform plan -out=cloud.tfplanSave a remote run for later review and approval
18Inspect remote Cloud planterraform show cloud.tfplanReview the saved remote plan
19Apply saved remote planterraform apply cloud.tfplanApply the saved run in its originating workspace
20Inspect Cloud remote stateterraform state listList resources tracked in HCP Terraform state
21Download Cloud remote stateterraform state pullRetrieve the workspace’s current state document
22Read Cloud outputsterraform outputRead output values from the connected HCP workspace
23Trigger remote destroyterraform destroyDestroy tracked infrastructure in a CLI-driven workspace; destructive

Beginner → Advanced | Practical Examples | Hands-on Labs | Real Organization & Workspaces | Updated October 2026

This guide explains how to operate HCP Terraform (formerly Terraform Cloud) from the command line, using your actual organization and workspace names.

You’ll learn how to authenticate, connect Terraform code to cloud workspaces, execute plans and applies, manage variables, inspect remote state, troubleshoot failures, and automate Terraform operations.

1. Your HCP Terraform environment

Organization: motoshare

These are the workspace names you supplied. I have not inspected their private settings or state, so the examples will distinguish configuration assumptions from confirmed details.

2. Understand Terraform CLI vs Terraform Cloud API

This is the most important distinction.

InterfacePurposeExample
Terraform CLIPlan, apply, validate, and manage infrastructureterraform plan
HCP Terraform CLI-driven workflowExecute Terraform CLI operations using an HCP Terraform workspaceterraform apply with a cloud block
HCP Terraform REST APIManage organizations, projects, workspaces, variables, and runs programmaticallycurl .../api/v2/...
HCP Terraform UIConfigure workspaces, teams, permissions, variables, and review runsapp.terraform.io

There is no general built-in terraform cloud command that administers every HCP Terraform resource. You use the normal Terraform CLI for infrastructure, and the API or the hashicorp/tfe provider for broader platform administration.

With Remote Execution, plans and applies run on HCP Terraform workers, and the results stream to your terminal. With Local Execution, Terraform runs on your computer while HCP Terraform stores the state.

HashiCorp Developer

+1

3. Prerequisites and installation

You’ll need Terraform CLI, an HCP Terraform account with access to motoshare, and a terminal. For API demonstrations, install curl and jq.

3.1 Install Terraform CLI on macOS

brew tap hashicorp/tap
brew install hashicorp/tap/terraform

Verify the installation:

terraform version

To explore the commands available in your installed version:

terraform -help
terraform init -help
terraform plan -help
terraform workspace -help

Usage: The -help option is especially useful because command flags and features can change between Terraform versions.

3.2 Log in to Terraform Cloud

terraform login

You can also specify the hostname:

terraform login app.terraform.io

Terraform opens an authentication flow for creating and saving an HCP Terraform user token.

After logging in, the CLI can access workspaces your identity is authorized to use.

3.3 Where are credentials stored?

On macOS and Linux, the default login credentials are stored at:

~/.terraform.d/credentials.tfrc.json

The token is stored as readable text, so protect that file and never commit it to Git.

To remove locally stored login credentials:

terraform logout

This removes the local credential but does not revoke the token on the server.

HashiCorp Developer

+1

3.4 Authenticate in CI/CD without interactive login

For a CI/CD job, you can provide the token through a protected environment variable:

export TF_TOKEN_app_terraform_io="$TFC_TOKEN"

Here, TFC_TOKEN represents a token securely injected into the job by your CI secrets manager.

Avoid hardcoding the token in Terraform files, shell scripts, or GitHub repositories.

4. Connect your Terraform CLI to an existing workspace

We’ll use your proezi_dev workspace for this example.

Step 1: Create a working directory

mkdir -p ~/terraform-training/proezi-dev
cd ~/terraform-training/proezi-dev

Step 2: Create cloud.tf

terraform {
  required_version = ">= 1.6.0"

  cloud {
    organization = "motoshare"

    workspaces {
      name    = "proezi_dev"
      project = "proezi"
    }
  }
}

What each setting does:

SettingPurpose
required_versionEnforces Terraform CLI version compatibility
cloudEnables HCP Terraform integration
organizationSelects the motoshare organization
workspaces.nameTargets proezi_dev
workspaces.projectAssociates the workspace with project proezi

You don’t need to configure a separate backend "remote" block when using cloud. Terraform does not allow both together.

HashiCorp Developer

Step 3: Initialize

terraform init

This connects the working directory to your HCP Terraform workspace, initializes providers and modules as needed, and prepares the state backend.

Typical successful output:

Initializing HCP Terraform...

HCP Terraform has been successfully initialized!

Terraform has been successfully initialized!

Step 4: Inspect existing infrastructure state

These are read-only commands:

terraform state list
terraform output

The first command lists resource addresses recorded in the workspace state. The second displays root-module output values, if any.

Important: Do not run terraform plan, terraform apply, or terraform destroy against this empty example directory if proezi_dev already manages real infrastructure. Missing resource definitions could cause Terraform to propose destroying existing resources.

This section is only for establishing connectivity and inspecting state.

5. Hands-on lab — Your first CLI-driven Terraform Cloud run

For actual experimentation, I recommend creating a separate workspace, proezi_cli_lab, inside the proezi project. This keeps your real Dev, Stage, and Prod infrastructure untouched.

The exercise uses Terraform’s built-in terraform_data resource, so it doesn’t require AWS, Azure, or other cloud provider credentials and won’t provision external infrastructure.

5.1 Prepare the lab directory

mkdir -p ~/terraform-training/proezi-cli-lab
cd ~/terraform-training/proezi-cli-lab

Create these files:

proezi-cli-lab/
├── cloud.tf
├── variables.tf
├── main.tf
├── outputs.tf
└── lab.auto.tfvars

5.2 File 1 — cloud.tf

terraform {
  required_version = ">= 1.6.0"

  cloud {
    organization = "motoshare"

    workspaces {
      name    = "proezi_cli_lab"
      project = "proezi"
    }
  }
}

When terraform init encounters a named workspace that doesn’t exist, it can create the workspace automatically, subject to your permissions. Verify the new workspace’s settings before its first run.

HashiCorp Developer

5.3 File 2 — variables.tf

variable "app_name" {
  description = "Application name"
  type        = string
  default     = "proezi"
}

variable "environment" {
  description = "Deployment environment"
  type        = string
  default     = "lab"
}

variable "replicas" {
  description = "Desired replica count"
  type        = number
  default     = 1

  validation {
    condition     = var.replicas >= 1
    error_message = "Replicas must be at least 1."
  }
}

5.4 File 3 — main.tf

resource "terraform_data" "application" {
  input = {
    name        = var.app_name
    environment = var.environment
    replicas    = var.replicas
  }
}

terraform_data is useful for learning Terraform operations without provisioning a real virtual machine, network, or database.

5.5 File 4 — outputs.tf

output "application_details" {
  description = "Application configuration"

  value = terraform_data.application.output
}

output "environment_name" {
  value = var.environment
}

5.6 File 5 — lab.auto.tfvars

app_name    = "proezi"
environment = "lab"
replicas    = 2

Terraform automatically loads files ending in .auto.tfvars.

5.7 Execute the full CLI workflow

Run the commands:

terraform init

terraform fmt

terraform validate

terraform plan

Since this is a new lab workspace, the plan should propose creating one terraform_data.application resource, assuming no existing lab state or policies prevent the run.

Apply the configuration:

terraform apply

Review the plan and type:

yes

The apply runs in HCP Terraform when the workspace uses Remote Execution. You can view its history in:

Open proezi_cli_labThis link targets the proposed lab workspace, which will exist only after you create it.

Now inspect the output:

terraform output
terraform output environment_name
terraform output -json

Expected environment_name:

"lab"

5.8 Update a variable and rerun

Edit lab.auto.tfvars:

replicas = 3

Run:

terraform plan
terraform apply

Terraform should show an in-place change to the lab’s stored data resource, rather than creating real servers.

Learning outcome: You’ve completed a CLI-driven remote run, created state in HCP Terraform, updated configuration, and inspected outputs.

6. Master Terraform CLI command reference

The commands below work in ordinary Terraform configurations. When you connect a directory to HCP Terraform, their behavior depends on the workspace’s execution mode and workflow settings.

6.1 Setup, authentication, and initialization

CommandExampleUsage
versionterraform versionDisplay CLI and provider versions
-helpterraform plan -helpShow options and syntax
loginterraform loginAuthenticate with HCP Terraform
logoutterraform logoutRemove local authentication token
initterraform initInitialize providers, modules, and cloud connection
init -upgradeterraform init -upgradeUpgrade selected providers/modules within configured constraints
init -reconfigureterraform init -reconfigureReconfigure backend or cloud connection without attempting state migration
init -migrate-stateterraform init -migrate-stateMigrate existing state when intentionally changing its storage configuration

Use -migrate-state only after reviewing the source and destination state and taking appropriate backups.

6.2 Code validation and planning

CommandExampleUsage
fmtterraform fmtFormat HCL files
fmt -checkterraform fmt -check -recursiveCheck formatting without rewriting files
validateterraform validateVerify configuration syntax and structural validity
planterraform planPreview infrastructure changes
plan -varterraform plan -var='replicas=3'Supply a run-specific Terraform variable
plan -var-fileterraform plan -var-file=dev.tfvarsLoad variable values from a selected file
plan -outterraform plan -out=review.tfplanSave a plan for later inspection/apply
plan -detailed-exitcodeterraform plan -detailed-exitcodeIndicate whether changes are needed via exit status
plan -refresh-onlyterraform plan -refresh-onlyInspect state updates based on real infrastructure
plan -replaceterraform plan -replace=aws_instance.webPreview replacement of a specific resource
plan -targetterraform plan -target=aws_instance.webTarget a resource for exceptional recovery or repair

-target and -replace are not normal deployment practices. Use them only when their behavior is understood and justified.

6.3 Applying and managing infrastructure

CommandExampleUsage
applyterraform applyPlan and apply changes
apply -auto-approveterraform apply -auto-approveSkip interactive approval; suitable only for properly controlled automation
apply FILEterraform apply review.tfplanApply a previously saved plan
apply -refresh-onlyterraform apply -refresh-onlyUpdate state and outputs without normal infrastructure reconciliation
destroyterraform destroyDestroy all resources managed by the selected configuration/state
destroy -targetterraform destroy -target=aws_instance.webTarget a subset for destruction; exceptional use only
showterraform showDisplay state information
show FILEterraform show review.tfplanDisplay the contents of a saved plan
outputterraform outputShow root-module output values
output -jsonterraform output -jsonExport output values in JSON
output -rawterraform output -raw environment_nameGet a string output without quotes

6.4 Terraform state operations

CommandExampleUsage
state listterraform state listList tracked resources
state showterraform state show terraform_data.applicationInspect one tracked resource
state pullterraform state pullRetrieve the current state document
state mvterraform state mv OLD NEWChange a resource address in state
state rmterraform state rm ADDRESSStop tracking a resource without deleting it
state replace-providerterraform state replace-provider OLD NEWChange provider addresses stored in state
importterraform import ADDRESS IDBring an existing remote resource under Terraform state management
force-unlockterraform force-unlock LOCK_IDManually release a state lock where supported by the backend

State-changing commands require special care because incorrect changes can cause future Terraform plans to replace or destroy infrastructure. Terraform state subcommands support remote state, and state modification commands write local backups.

6.5 Workspaces, modules, testing, and debugging

CommandExampleUsage
workspace listterraform workspace listList workspaces available through the configuration
workspace selectterraform workspace select proezi_devSelect a different workspace, when supported
workspace showterraform workspace showDisplay the selected CLI workspace
workspace newterraform workspace new demoCreate a workspace, where supported
workspace deleteterraform workspace delete demoDelete an eligible workspace; destructive administrative action
providersterraform providersDisplay required provider dependencies
getterraform getDownload modules; generally prefer terraform init
consoleterraform consoleInteractively test HCL expressions
graphterraform graphGenerate dependency-graph output
testterraform testExecute Terraform test files

Important workspace limitation: terraform workspace select is not the way to switch between workspaces when your cloud block specifies a fixed workspaces.name. Section 9 explains supported workspace-selection methods.

7. Planning and applying — Detailed examples

These exercises use the separate proezi_cli_lab workspace created in Section 5.

7.1 Example: Standard remote plan

terraform plan

When to use: Before every infrastructure change.

With a remote-execution workspace, this creates a speculative plan using your local Terraform files and the remote workspace context.

A speculative plan can show potential changes, but cannot subsequently be applied directly.

HashiCorp Developer

7.2 Example: Pass a variable directly

terraform plan -var="replicas=4"

When to use: Temporarily override a Terraform input variable for a single run.

The CLI value does not permanently change the stored workspace variable.

7.3 Example: Use an explicit variable file

Create dev.tfvars:

app_name    = "proezi"
environment = "development"
replicas    = 2

Execute:

terraform plan -var-file="dev.tfvars"

When to use: You want reusable environment-specific values without hardcoding everything into .tf resources.

7.4 Example: Check if a deployment is needed

terraform plan -detailed-exitcode
echo $?

Exit codes:

CodeMeaning
0Plan succeeded; no changes
1An error occurred
2Plan succeeded; changes are proposed

This is helpful in CI/CD pipelines that need to distinguish infrastructure drift or new changes from errors.

7.5 Example: Save, review, and apply a plan

terraform plan -out=review.tfplan

Inspect:

terraform show review.tfplan

Apply:

terraform apply review.tfplan

For remote CLI-driven runs, this requires Terraform CLI 1.6 or later.

HCP Terraform’s remote saved-plan file is a reference to a remote run, not an ordinary local binary plan. It can only be applied in the originating remote workspace, and it becomes stale if the underlying state is no longer valid.

7.6 Example: Use automation approval

terraform apply -auto-approve

When to use: Only in approved automation where plan review, change controls, and workspace permissions are already established.

Do not use this as a shortcut for deploying into proezi_prod.

7.7 Example: Inspect a plan in JSON

For a remote saved plan:

terraform show -json review.tfplan

Unlike the human-readable plan, JSON can contain sensitive values in unredacted form. HCP Terraform requires workspace admin permission to inspect a remote saved plan in JSON. Store such output securely.

7.8 Example: Refresh state

terraform plan -refresh-only

This previews how state would change to reflect infrastructure modified outside Terraform.

To commit a refresh-only operation:

terraform apply -refresh-only

This does not perform ordinary desired-state reconciliation. It updates Terraform’s recorded view of existing infrastructure and outputs.

8. Terraform Cloud variables through CLI

HCP Terraform variables are especially important because they can be defined at multiple scopes.

8.1 Common ways to provide variable values

MethodExampleWhere the value comes from
Variable defaultdefault = 2Terraform configuration
Automatic .tfvarslab.auto.tfvarsConfiguration files
Explicit .tfvars-var-file=dev.tfvarsCommand line
CLI argument-var='replicas=4'Command line
Local shellTF_VAR_replicas=4Your terminal
Workspace Terraform variablereplicas = 2HCP workspace settings
Project variable setShared application settingsHCP project
Organization variable setShared settings across projectsHCP organization

8.2 Example: Local environment variable

export TF_VAR_replicas=5

terraform plan

Remove it after the test:

unset TF_VAR_replicas

8.3 Example: Store the value in HCP Terraform

Open:

proezi_dev → Variables

Create a Terraform variable:

KeyValueCategory
environmentdevelopmentTerraform
replicas2Terraform
app_nameproeziTerraform

These are illustrative values, not changes I’ve made. Only add keys actually declared in the Terraform configuration used by that workspace.

For proezi_stage, you might set environment = staging; for proezi_prod, environment = production.

Workspace variables are persistent and apply to the workspace’s runs unless overridden by a higher-precedence source.

8.4 Variable precedence in remote CLI runs

The practical precedence, highest first, is:

This is a simplified grouping. Within priority and ordinary variable sets, HCP Terraform also applies rules for set ownership, scope, and lexical order of set names.

For example, suppose:

  • lab.auto.tfvars sets replicas = 2
  • Your HCP workspace sets replicas = 3
  • You execute terraform plan -var='replicas=6'

The plan uses 6, unless a priority variable set enforces a different value.

Important distinction: TF_VAR_replicas is a Terraform input variable. AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and similar provider environment variables are a separate category. With remote execution, provider credentials generally need to be available in the HCP remote run environment, not merely on your laptop. Prefer short-lived, dynamic provider credentials where possible.

HashiCorp Developer

9. Managing Dev, Stage, and Prod workspaces

This section directly addresses your three workspaces:

  • proezi_dev
  • proezi_stage
  • proezi_prod

There are three useful ways to target them.

Method A — Separate Terraform directories

Recommended for straightforward environment isolation

terraform/
├── dev/
│   └── cloud.tf
├── stage/
│   └── cloud.tf
└── prod/
    └── cloud.tf

Each directory contains its own configuration for the correct HCP workspace.

For Dev:

terraform {
  cloud {
    organization = "motoshare"

    workspaces {
      name    = "proezi_dev"
      project = "proezi"
    }
  }
}

For Stage, use name = "proezi_stage". For Prod, use name = "proezi_prod".

You can then execute commands from the repository root:

terraform -chdir=dev init
terraform -chdir=dev plan

terraform -chdir=stage init
terraform -chdir=stage plan

terraform -chdir=prod init
terraform -chdir=prod plan

This is a clear mapping, but each directory must contain the intended complete configuration for its environment. Don’t create only a cloud.tf and then run apply against a workspace that already manages resources.

Method B — Workspace selection using tags

If the three workspaces use the same Terraform configuration, you can choose them from one working directory using workspace tags.

First, deliberately apply the same key-value tag to all three workspaces through the HCP Terraform UI:

application = proezi

Then, using Terraform CLI 1.10 or later, configure:

terraform {
  cloud {
    organization = "motoshare"

    workspaces {
      tags = {
        application = "proezi"
      }

      project = "proezi"
    }
  }
}

Now:

terraform init

List matching workspaces:

terraform workspace list

Select Dev:

terraform workspace select proezi_dev

Confirm the selection:

terraform workspace show

Run:

terraform plan

Switch to Stage:

terraform workspace select proezi_stage
terraform plan

Switch to Prod:

terraform workspace select proezi_prod
terraform plan

This requires each workspace to match the configured tags and project.

Crucial: workspaces.name and workspaces.tags are mutually exclusive. You cannot use terraform workspace select to switch among several HCP workspaces when the configuration is bound to a single name.

Method C — Workspace selection through an environment variable

For scripts that must target an existing workspace without hardcoding its name, you can omit the workspaces block:

terraform {
  cloud {
    organization = "motoshare"
  }
}

Then:

export TF_WORKSPACE=proezi_dev

terraform init
terraform plan

The environment variable selects an existing HCP Terraform workspace. It does not automatically create a missing workspace in this configuration.

To change the target in automation, supply a different TF_WORKSPACE value for a separately initialized job or working directory.

Production recommendation: Keep production targeting explicit, use separate pipeline approvals, and validate the selected workspace before any state-changing operation.

HashiCorp Developer

10. Remote state management — Hands-on examples

Terraform state records which infrastructure objects Terraform manages.

In HCP Terraform, state is stored centrally and can be shared by authorized users and automation.

10.1 List resources in remote state

From an initialized workspace directory:

terraform state list

For the lab, an expected resource address is:

terraform_data.application

For a real AWS configuration, the output might look like:

aws_vpc.main
aws_subnet.public
aws_security_group.web
aws_instance.web

These AWS addresses are examples, not confirmed resources in your workspaces.

10.2 Inspect one resource

terraform state show terraform_data.application

Usage: Examine a resource’s recorded attributes without generating a new plan.

10.3 Back up remote state

From the isolated lab directory:

umask 077
terraform state pull > lab-state-backup.tfstate

Usage: Capture a state snapshot before maintenance or recovery exercises.

Never commit state backups to Git or share them casually. State may contain passwords, credentials, identifiers, and other sensitive values.

10.4 Move a resource address in state

Command format:

terraform state mv OLD_ADDRESS NEW_ADDRESS

Illustration:

terraform state mv \
  terraform_data.application \
  terraform_data.proezi_application

Usage: Rename a tracked resource address without creating a new infrastructure object.

Do not execute this illustration without also updating the HCL resource declaration to match. A moved block in version-controlled configuration is generally preferable for planned refactoring.

10.5 Remove a resource from state

terraform state rm terraform_data.application

Usage: Tell Terraform to forget an object.

This does not destroy the underlying object. For a real cloud resource, it can leave infrastructure running and unmanaged, so this command is intentionally a reference example, not a recommended lab step.

10.6 Import existing infrastructure

Suppose an AWS S3 bucket already exists.

A conventional CLI import looks like:

terraform import \
  aws_s3_bucket.existing \
  my-existing-bucket

You must first declare the resource in Terraform configuration and provide a correctly configured AWS provider.

An important HCP-specific detail is that terraform import runs locally, even when plans and applies run remotely. Your local environment may therefore need access to provider credentials and the target infrastructure.

Related Posts

Terraform tflint terraform-docs trivy tenv pre-commit Tools — Installation Guide for Windows PowerShell

Updated: October 2026 | Windows 10/11 | PowerShell 5.1 / 7 This guide covers installing, verifying, and running the first commands for five Terraform development tools. Tool…

Read More

HCP Terraform Cloud CLI — Master Command Summary Table

Organization: motoshare | Project: proezi | Workspaces: proezi_dev, proezi_stage, proezi_prod 1. Terraform CLI — Complete Command Reference Category Command Purpose / Usage Installation terraform version Check installed…

Read More

Terraform Lab – Azure Hands-On – Terraform Functions

Beginner to Intermediate · 8 modules · 22 progressively designed labs · 20 local-only labs + 2 optional cloud labs · Updated 14 October 2026 Purpose: learn Terraform…

Read More

Terraform Lab – Azure Hands-On – Terraform Template

Level: Beginner to IntermediateFormat: Tutorial + concept guide + practical lab workbookModules: 6 | Labs: 12 | Cloud emphasis: Azure Linux VM, AWS EC2 comparisonBaseline: Terraform 1.15.9+ (within 1.x); AzureRM 5.9.x; AWS provider 6.xUpdated: 14 October…

Read More

Terraform Lab – Azure Hands-On – Terraform Modules

Course level: Beginner → IntermediateCourse type: Tutorial + runnable hands-on exercises + instructor checkpointsUpdated: 14 October 2026Terraform: >= 1.15.0, < 2.0.0 (lab baseline: 1.15.9)AzureRM provider: ~> 5.9.0 (root; child modules declare >= 5.9.0)Azure baseline: eastus, Ubuntu…

Read More

Terraform Lab – Azure Hands-On – Conditional Expressions and Logic

This workbook teaches the complete set of Terraform conditionals, filtering, validation, null handling, and related functions from the requested syllabus. Every numbered concept includes one standalone AWS EC2…

Read More