Skip to content

thrashr888/hcptf-cli

Repository files navigation

HCP Terraform CLI (hcptf)

A Go CLI for managing HCP Terraform resources. Built with mitchellh/cli and hashicorp/go-tfe.

Installation

Download Pre-built Binary (Recommended)

Download the latest release for your platform from GitHub Releases:

# Example: macOS (Apple Silicon)
curl -LO https://github.com/thrashr888/hcptf-cli/releases/latest/download/hcptf_VERSION_darwin_arm64.tar.gz
tar -xzf hcptf_VERSION_darwin_arm64.tar.gz
sudo mv hcptf /usr/local/bin/

# Verify installation
hcptf version

Available platforms: Linux (amd64, arm64), macOS (Intel, Apple Silicon), Windows, FreeBSD.

Checksums are published on each GitHub release page.

Build from Source

go build -o hcptf .

# Optional: add to PATH
sudo mv hcptf /usr/local/bin/

Authentication

The fastest way to get started:

hcptf login
hcptf login -show-token                # Print saved token for scripting
hcptf whoami                           # Show current authenticated user

This prompts for an API token, validates it, and stores it in ~/.terraform.d/credentials.tfrc.json (shared with Terraform CLI).

If you've already run terraform login, no setup is needed - hcptf reads those credentials automatically.

Other authentication methods (checked in order):

  1. TFE_TOKEN environment variable
  2. HCPTF_TOKEN environment variable
  3. ~/.hcptfrc configuration file (HCL format)
  4. ~/.terraform.d/credentials.tfrc.json

See docs/AUTH_GUIDE.md for details on CI/CD setup, multiple TFE instances, and troubleshooting.

Configuration

Optional config file at ~/.hcptfrc:

credentials "app.terraform.io" {
  token = "your-token-here"
}

default_organization = "my-org"
output_format = "table"  # or "json"

Override the API endpoint:

export HCPTF_ADDRESS="https://tfe.example.com"  # Preferred
export TFE_ADDRESS="https://tfe.example.com"    # Legacy support

Note: HCPTF_ADDRESS takes precedence over TFE_ADDRESS for compatibility.

Usage

Traditional Command Style

# Canonical nested examples (implicit GET)
# Omit `list` when collection scope is provided.
hcptf workspace -org=my-org
# Explicit form:
hcptf workspace list -org=my-org

# Read workspace by identity (implicit `read`)
hcptf workspace -org=my-org -name=staging
# Explicit form:
hcptf workspace read -org=my-org -name=staging
hcptf workspace create -org=my-org -name=staging -auto-apply=false
hcptf run create -org=my-org -workspace=staging -message="Deploy changes"

# Check run status and apply
hcptf run -id=run-abc123
# Explicit forms:
hcptf run read -id=run-abc123
hcptf run show -id=run-abc123
hcptf run apply -id=run-abc123 -comment="Approved"

# Manage variables
hcptf variable create -org=my-org -workspace=staging -key=region -value=us-east-1
hcptf variable create -org=my-org -workspace=staging \
  -key=AWS_SECRET_KEY -value=secret -category=env -sensitive

# JSON output for scripting
hcptf workspace list -org=my-org -output=json

# Registry commands (hierarchical namespace)
hcptf registry module list -org=my-org
hcptf registry provider create -org=my-org -name=custom-provider
hcptf registry provider version create -org=my-org -name=aws -version=3.1.1 -key-id=GPG_KEY_ID

# Public registry commands (query public Terraform registry)
hcptf publicregistry provider -name=hashicorp/aws
hcptf publicregistry provider versions -name=hashicorp/random
hcptf publicregistry module -name=terraform-aws-modules/vpc/aws
hcptf publicregistry policy list
hcptf publicregistry policy -name=hashicorp/CIS-Policy-Set-for-AWS-Terraform

# Stack commands (hierarchical namespace)
hcptf stack list -org=my-org -project=prj-abc123
hcptf stack configuration list -stack-id=stk-abc123
hcptf stack deployment create -stack-id=stk-abc123

# Explorer API (query resources across organization)
hcptf explorer query -org=my-org -type=providers -sort=-version
hcptf explorer query -org=my-org -type=workspaces -filter="current-run-status:policy_checked"

URL-Style Navigation

For convenience, you can use a URL-like path syntax to access resources.

Important: URL-style commands are read-only (safe navigation). To execute actions like applying runs, use flag-based commands.

# Show organization details
hcptf my-org

# List workspaces in an org
hcptf my-org workspaces

# Show workspace details
hcptf my-org my-workspace

# List runs for a workspace
hcptf my-org my-workspace runs
hcptf my-org my-workspace runs list

# Show a specific run
hcptf my-org my-workspace runs run-abc123

# View plan and apply details (read-only)
hcptf my-org my-workspace runs run-abc123 plan
hcptf my-org my-workspace runs run-abc123 logs
hcptf my-org my-workspace runs run-abc123 apply
hcptf my-org my-workspace runs run-abc123 apply logs

# List workspace variables
hcptf my-org my-workspace variables

# View state
hcptf my-org my-workspace state
hcptf my-org my-workspace state outputs

# Check drift and health assessments
hcptf my-org my-workspace assessments
hcptf my-org my-workspace runs run-abc123 assessment

# View policy checks
hcptf my-org my-workspace runs run-abc123 policychecks

# Other org resources
hcptf my-org projects
hcptf my-org teams
hcptf my-org policies

Actions (Flag-Based Commands)

To execute actions like applying runs or deleting resources, use flag-based commands:

# Execute run apply (requires confirmation)
hcptf run apply -id=run-abc123 -comment="Reviewed and approved"

# Force-execute a pending run
hcptf run force-execute -id=run-abc123

# Discard a run
hcptf run discard -id=run-abc123 -comment="Changes not needed"

# Cancel a run
hcptf run cancel -id=run-abc123

# Lock/unlock workspaces
hcptf workspace lock -org=my-org -name=prod -reason="maintenance window"
hcptf workspace unlock -org=my-org -name=prod
hcptf workspace force-unlock -org=my-org -name=prod

# Create resources
hcptf workspace create -org=my-org -name=new-workspace
hcptf variable create -org=my-org -workspace=staging -key=region -value=us-east-1

# Delete resources (requires confirmation)
hcptf workspace delete -org=my-org -name=staging
hcptf run delete -id=run-abc123

Delete Confirmation

All delete commands are guarded:

  • -y, -f, or -force bypasses confirmation.
  • Without those flags, the command prompts and only proceeds after typing yes.
hcptf workspace delete -org=my-org -name=staging
hcptf workspace delete -org=my-org -name=staging -y
hcptf workspace delete -org=my-org -name=staging -force

Both styles work interchangeably - use whichever you prefer!

Agent-Friendly Features

The CLI includes features designed for AI agent automation:

Schema introspection — discover flags for any command as structured JSON:

hcptf schema workspace create
hcptf schema variable create

Dry run — validate mutations without executing them:

hcptf workspace delete -org=my-org -name=staging -dry-run
hcptf variable create -org=my-org -workspace=prod -key=region -value=us-east-1 -dry-run

JSON input — pass full API payloads instead of individual flags:

hcptf variable create -org=my-org -workspace=prod \
  -json-input='{"key":"region","value":"us-east-1","category":"terraform"}'
hcptf workspace create -org=my-org -json-input=@workspace.json
cat config.json | hcptf workspace create -org=my-org -json-input=-

Field filtering — limit output to specific fields:

hcptf workspace list -org=my-org -fields=Name,ID -output=json
hcptf workspace read -org=my-org -name=prod -fields=ID,Name,Status

Input validation — all mutation commands reject path traversal, query injection, URL-encoded sequences, control characters, and overly long strings.

Hierarchical Command Namespaces

Registry, stack, and public registry commands use a hierarchical namespace structure for better organization:

# Private registry commands
hcptf registry                                    # Show all registry commands
hcptf registry module list -org=my-org           # List private modules
hcptf registry provider create -org=my-org       # Create private provider
hcptf registry provider version create ...        # Create provider version
hcptf registry provider platform create ...       # Add platform binary

# Public registry commands
hcptf publicregistry                             # Show all public registry commands
hcptf publicregistry provider -name=hashicorp/aws        # Get provider info
hcptf publicregistry provider versions -name=hashicorp/aws  # List versions
hcptf publicregistry module -name=terraform-aws-modules/vpc/aws  # Get module info
hcptf publicregistry policy list                 # List public policies
hcptf publicregistry policy -name=hashicorp/CIS-Policy-Set-for-AWS-Terraform  # Get policy info

# Stack commands
hcptf stack                                       # Show all stack commands
hcptf stack list -org=my-org                     # List stacks
hcptf stack configuration list -stack-id=stk-123  # List configurations
hcptf stack deployment create -stack-id=stk-123   # Create deployment
hcptf stack state list -stack-id=stk-123         # List state versions

Commands

231+ commands across 60+ resource types organized in hierarchical namespaces.

Group Commands Description
whoami 1 Show current authenticated user
login / logout 2 Credential management
account 3 User account CRUD
workspace 8 Workspace management
run 7 Run lifecycle
organization 5 Organization management
variable 4 Workspace variables
team 6 Teams and membership
project 5 Project organization
state 3 State versions and outputs
policy 5 Sentinel/OPA policies
policyset 7 Policy set management
policycheck 3 Policy check results
policyevaluation 1 Policy evaluations
policyset outcome 2 Policy set outcomes
policyset parameter 4 Policy set parameters
sshkey 5 SSH keys for VCS
notification 6 Run notifications
variableset 10 Reusable variable sets
agentpool 8 Self-hosted agent pools
agent 2 Agent monitoring
runtask 7 Run task integrations
oauthclient 5 VCS OAuth clients
oauthtoken 3 OAuth tokens
runtrigger 4 Workspace orchestration
plan 2 Plan details and logs
apply 2 Apply details and logs
planexport 3 Plan exports
configversion 4 Configuration versions
team access 5 Team workspace permissions
project teamaccess 5 Team project permissions
registry 1 Private registry parent
registry module 6 Private registry modules
registry provider 4 Private registry providers
registry provider version 3 Provider versions
registry provider platform 3 Provider platforms
publicregistry 1 Public registry parent
publicregistry provider 2 Public provider info/versions
publicregistry module 1 Public module info
publicregistry policy 2 Public policy info/list
gpgkey 5 GPG keys for providers
stack 6 Terraform Stacks management
stack configuration 5 Stack configurations
stack deployment 3 Stack deployments
stack state 2 Stack states
audittrail 2 Audit trail events
audittrail token 4 Audit trail tokens
organization token 4 Organization API tokens
user token 4 User API tokens
team token 4 Team API tokens
organization membership 4 Organization memberships
organization member 1 Organization member details
organization tag 2 Organization tags
workspace tag 3 Workspace tags
reservedtagkey 3 Reserved tag keys
comment 3 Run comments
awsoidc 4 AWS OIDC integration
azureoidc 4 Azure OIDC integration
gcpoidc 4 GCP OIDC integration
vaultoidc 4 Vault OIDC integration
workspace resource 2 Managed resources
queryrun 1 Search runs
queryworkspace 1 Search workspaces
changerequest 4 Change requests
assessmentresult 2 Drift detection/health
hyok 5 Hold Your Own Key config
hyokkey 3 HYOK key versions
vcsevent 2 VCS integration events
explorer 1 Query resources across org
schema 1 Machine-readable command flag introspection
version 1 CLI version

Common flags

Flag Alias Description
-organization -org Organization name
-output table (default) or json
-force -f, -y Skip confirmation prompts
-dry-run Validate without making API calls
-fields Comma-separated output field filter
-json-input JSON payload (inline, @file, or - for stdin)

Help

hcptf --help
hcptf workspace --help
hcptf workspace create --help

Agent Skills

This project includes Agent Skills that help AI agents use the CLI effectively. Skills are automatically discovered by compatible agents (Claude Code, Cursor, GitHub Copilot, etc.).

Installing Skills

# Install all skills (recommended)
npx skills add thrashr888/hcptf-cli

# Install a specific skill
npx skills add thrashr888/hcptf-cli@drift
npx skills add thrashr888/hcptf-cli@greenfield-deploy

# Install to a specific agent
npx skills add thrashr888/hcptf-cli -a claude-code
npx skills add thrashr888/hcptf-cli -a cursor

Or manually copy skills into your project:

git clone https://github.com/thrashr888/hcptf-cli.git
cp -r hcptf-cli/.skills /path/to/your/project/.skills

Compatible agents will automatically discover skills in the .skills/ directory.

Available Skills

  • hcptf-cli: Comprehensive guide covering authentication, commands, workflows, and best practices
  • drift: Investigate and resolve infrastructure drift (detect drifted workspaces, view changes, fix violations)
  • version-upgrades: Upgrade Terraform, provider, module, and policy versions (find latest versions, update code, test changes)
  • policy-compliance: Investigate and resolve policy check failures (understand violations, fix code, override policies)
  • workspace-to-stack: Refactor existing workspaces into Terraform Stacks (audit, design, migrate, validate)
  • greenfield-deploy: Set up a new project from scratch with HCP Terraform (create workspace, configure, deploy, verify)

The .skills/ directory contains structured instructions that agents can load to:

  • Understand hierarchical command structure and URL-style navigation
  • Learn common workflows (drift investigation, version upgrades, policy compliance)
  • Set up greenfield projects and migrate workspaces to stacks
  • Use public registry commands to discover providers, modules, and policies
  • Follow best practices for remediation and automation
  • Handle errors and troubleshooting

See .skills/README.md for details.

Project Structure

hcptf-cli/
├── main.go                  # Entry point
├── command/                 # CLI commands
│   ├── commands.go          # Command registry
│   ├── meta.go              # Shared command base (dry-run, fields, json-input)
│   ├── schema.go            # Schema introspection command
│   └── <resource>_<action>.go
├── internal/
│   ├── client/              # go-tfe API client wrapper
│   ├── config/              # Configuration loading
│   ├── output/              # Table/JSON formatting with field filtering
│   └── validate/            # Input validation (IDs, names, strings)
├── docs/                    # Documentation
└── go.mod

Development

go build -o hcptf .
go test ./...
./hcptf --help

Dependencies

  • github.com/hashicorp/go-tfe - HCP Terraform API client
  • github.com/mitchellh/cli - CLI framework
  • github.com/hashicorp/hcl/v2 - Configuration parsing
  • github.com/olekukonko/tablewriter - Table output
  • github.com/fatih/color - Terminal colors

Exit codes

  • 0 - Success
  • 1 - API or runtime error
  • 2 - Usage or validation error

License

Designed for use with HCP Terraform and Terraform Enterprise.

About

Comprehensive Go CLI for HCP Terraform with >100% API coverage. Built for AI agent use.

Topics

Resources

License

Stars

Watchers

Forks

Languages