Generated banner for Terraform Stacks
Generated logo for Terraform Stacks

Terraform Stacks

HashiCorpOfficialPublished by HashiCorp

  • Skill
  • Tool integration
  • Cloud and DevOps
  • MPL-2.0
  • No issues found

From the author

Comprehensive guide for working with HashiCorp Terraform Stacks. Use when creating, modifying, or validating Terraform Stack configurations (.tfcomponent.hcl, .tfdeploy.hcl files), working with stack components and deployments from local modules, public registry, or private registry sources, managing multi-region or multi-environment infrastructure, or troubleshooting Terraform Stacks syntax and structure.
— the description by HashiCorp

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

Terraform Stacks provides a declarative orchestration layer above traditional Terraform modules, enabling the management of complex infrastructure across multiple environments, regions, and cloud accounts. It introduces a specialized HCL-based configuration language using .tfcomponent.hcl and .tfdeploy.hcl files to define components, providers, and deployment instances. This skill covers the full lifecycle of Stacks, including configuration, dependency management, provider configuration, and deployment monitoring via the CLI or HCP Terraform API.

What it does

  • Defines infrastructure units as components referencing local, registry, or Git-based modules.
  • Orchestrates multi-region and multi-environment deployments within a single Stack.
  • Manages provider configurations with support for for_each and workload identity authentication.
  • Links multiple Stacks together using published outputs and upstream inputs.
  • Automates deployment workflows and monitoring through HCP Terraform integration.
  • Provides patterns for safe component removal and deferred changes.

When to use it

  • When you need to manage complex, multi-component infrastructure at scale.
  • When you require consistent infrastructure deployments across multiple environments or regions.
  • When you want to move beyond individual Terraform modules to a higher-level orchestration layer.
  • When implementing OIDC-based workload identity for secure, temporary cloud credentials.
  • When you need to link separate infrastructure stacks together in a dependency chain.

Advantages

  • Simplifies management of large-scale infrastructure by grouping related components.
  • Reduces reliance on long-lived static credentials through native workload identity support.
  • Provides clear separation between component definitions and deployment-specific inputs.
  • Enables automated deployment pipelines with built-in dependency inference.
  • Supports advanced patterns like multi-region deployments and cross-stack output sharing.

Usage examples

“How do I define a component in a Terraform Stack that uses a module from the public registry?”
The agent provides a component block example using the source argument with the registry path, specifying inputs and mapping providers.
“What is the best way to handle AWS credentials in a Stack without using static keys?”
The agent explains the workload identity pattern, showing how to configure an identity_token block and use assume_role_with_web_identity in the provider config.
“How can I monitor the status of a deployment run programmatically?”
The agent provides the API endpoints for retrieving deployment group summaries and run status, including the necessary headers for authentication.
“How do I remove a component from an existing Stack?”
The agent details the use of the removed block, explaining that it requires the component's providers to be defined to safely process the removal.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/hashicorp/terraform-stacks/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip terraform-stacks.zip -d .agents/skills

Documentation by HashiCorp

Terraform Stacks

Terraform Stacks simplify infrastructure provisioning and management at scale by providing a configuration layer above traditional Terraform modules. Stacks enable declarative orchestration of multiple components across environments, regions, and cloud accounts.

Core Concepts

Stack: A complete unit of infrastructure composed of components and deployments that can be managed together.

Component: An abstraction around a Terraform module that defines infrastructure pieces. Each component specifies a source module, inputs, and providers.

Deployment: An instance of all components in a stack with specific input values. Use deployments for different environments (dev/staging/prod), regions, or cloud accounts.

Stack Language: A separate HCL-based language (not regular Terraform HCL) with distinct blocks and file extensions.

File Structure

Terraform Stacks use specific file extensions:

  • Component configuration: .tfcomponent.hcl

  • Deployment configuration: .tfdeploy.hcl

  • Provider lock file: .terraform.lock.hcl (generated by CLI)

All configuration files must be at the root level of the Stack repository. HCP Terraform processes all files in dependency order.

my-stack/
├── .terraform-version               # The required Terraform version for this Stack
├── variables.tfcomponent.hcl        # Variable declarations
├── providers.tfcomponent.hcl        # Provider configurations
├── components.tfcomponent.hcl       # Component definitions
├── outputs.tfcomponent.hcl          # Stack outputs
├── deployments.tfdeploy.hcl         # Deployment definitions
├── .terraform.lock.hcl              # Provider lock file (generated)
└── modules/                         # Local modules (optional - only if using local modules)
    ├── s3/
    └── compute/

Note: The modules/ directory is only required when using local module sources. Components can reference modules from:

  • Local file paths: ./modules/vpc

  • Public registry: terraform-aws-modules/vpc/aws

  • Private registry: app.terraform.io/<org-name>/vpc/aws

  • Git: git::https://github.com/org/repo.git//path?ref=v1.0.0

HCP Terraform processes all .tfcomponent.hcl and .tfdeploy.hcl files in dependency order.

Required Terraform version (.terraform-version)

Use Terraform v1.13.x or later to access the Stacks CLI plugin and to run terraform stacks CLI commands. Begin by adding a .terraform-version file to your Stack's root directory to specify the Terraform version required for your Stack. For example, the following file specifies Terraform v1.14.5:

1.14.5

Component Configuration (.tfcomponent.hcl)

Variable Block

Declare input variables for the Stack configuration. Variables must define a type field and do not support the validation argument.

variable "aws_region" {
  type        = string
  description = "AWS region for deployments"
  default     = "us-west-1"
}

variable "identity_token" {
  type        = string
  description = "OIDC identity token"
  ephemeral   = true  # Does not persist to state file
}

variable "instance_count" {
  type     = number
  nullable = false
}

Important: Use ephemeral = true for credentials and tokens (identity tokens, API keys, passwords) to prevent them from persisting in state files. Use stable for longer-lived values like license keys that need to persist across runs.

Required Providers Block
required_providers {
  aws = {
    source  = "hashicorp/aws"
    version = "~> 6.0"
  }
  random = {
    source  = "hashicorp/random"
    version = "~> 3.5.0"
  }
}
Provider Block

Provider blocks differ from traditional Terraform:

  1. Support for_each meta-argument

  2. Define aliases in the block header (not as an argument)

  3. Accept configuration through a config block

Single Provider Configuration:

provider "aws" "this" {
  config {
    region = var.aws_region
    assume_role_with_web_identity {
      role_arn           = var.role_arn
      web_identity_token = var.identity_token
    }
  }
}

Multiple Provider Configurations with for_each:

provider "aws" "configurations" {
  for_each = var.regions

  config {
    region = each.value
    assume_role_with_web_identity {
      role_arn           = var.role_arn
      web_identity_token = var.identity_token
    }
  }
}

Authentication Best Practice: Use workload identity (OIDC) as the preferred authentication method for Stacks. This approach:

  • Avoids long-lived static credentials

  • Provides temporary, scoped credentials per deployment run

  • Integrates with cloud provider IAM (AWS IAM Roles, Azure Managed Identities, GCP Service Accounts)

  • Eliminates need for platform-managed environment variables

Configure workload identity using identity_token blocks and assume_role_with_web_identity in provider configuration. For detailed setup instructions for AWS, Azure, and GCP, see: https://developer.hashicorp.com/terraform/cloud-docs/dynamic-provider-credentials

Component Block

Each Stack requires at least one component block. Add a component for each module to include in the Stack. Components reference modules from local paths, registries, or Git.

component "vpc" {
  source  = "app.terraform.io/my-org/vpc/aws"  # Local, registry, or Git URL
  version = "2.1.0"          # For registry modules

  inputs = {
    cidr_block  = var.vpc_cidr
    name_prefix = var.name_prefix
  }

  providers = {
    aws = provider.aws.this
  }
}

See references/component-blocks.md for examples of dependencies, for_each, public registry modules, Git sources, and more.

Key Points:

  • Reference outputs: component.<name>.<output> or component.<name>[key].<output> for for_each

  • Dependencies inferred automatically from component references

  • Aggregate with for expressions: [for x in component.s3 : x.bucket_name]

  • For components with for_each, reference specific instances: component.<name>[each.value].<output>

  • Provider references are normal values: provider.<type>.<alias> or provider.<type>.<alias>[each.value]

Output Block

Outputs require a type argument and do not support preconditions:

output "vpc_id" {
  type        = string
  description = "VPC ID"
  value       = component.vpc.vpc_id
}

output "endpoint_urls" {
  type      = map(string)
  value     = {
    for region, comp in component.api : region => comp.endpoint_url
  }
  sensitive = false
}
Locals Block

Locals blocks work the same in both .tfcomponent.hcl and .tfdeploy.hcl files:

locals {
  common_tags = {
    Environment = var.environment
    ManagedBy   = "Terraform Stacks"
    Project     = var.project_name
  }

  region_config = {
    for region in var.regions : region => {
      name_suffix = "${var.environment}-${region}"
    }
  }
}
Removed Block

Use to safely remove components from a Stack. HCP Terraform requires the component's providers to remove it.

removed {
  from   = component.old_component
  source = "./modules/old-module"

  providers = {
    aws = provider.aws.this
  }
}

Deployment Configuration (.tfdeploy.hcl)

Identity Token Block

Generate JWT tokens for OIDC authentication with cloud providers:

identity_token "aws" {
  audience = ["aws.workload.identity"]
}

identity_token "azure" {
  audience = ["api://AzureADTokenExchange"]
}

Reference tokens in deployments using identity_token.<name>.jwt

Store Block

Access HCP Terraform variable sets within Stack deployments:

store "varset" "aws_credentials" {
  id       = "varset-ABC123"  # Alternatively use: name = "varset_name"
  source   = "tfc-cloud-shared"
  category = "terraform"      # Alternatively use: category = "env" for environment variables
}

deployment "production" {
  inputs = {
    aws_access_key = store.varset.aws_credentials.AWS_ACCESS_KEY_ID
  }
}

Use to centralize credentials and share variables across Stacks. See references/deployment-blocks.md for details.

Deployment Block

Define deployment instances (minimum 1, maximum 20 per Stack):

deployment "production" {
  inputs = {
    aws_region     = "us-west-1"
    instance_count = 3
    role_arn       = local.role_arn
    identity_token = identity_token.aws.jwt
  }
}

# Create multiple deployments for different environments
deployment "development" {
  inputs = {
    aws_region     = "us-east-1"
    instance_count = 1
    name_suffix    = "dev"
    role_arn       = local.role_arn
    identity_token = identity_token.aws.jwt
  }
}

To destroy a deployment: Set destroy = true, upload configuration, approve destroy run, then remove the deployment block. See references/deployment-blocks.md for details.

Deployment Group Block

Group deployments together for shared settings (HCP Terraform Premium tier feature). Free/standard tiers use default groups named {deployment-name}_default.

deployment_group "canary" {
  auto_approve_checks = [deployment_auto_approve.safe_changes]
}

deployment "dev" {
  inputs = { /* ... */ }
  deployment_group = deployment_group.canary
}

Multiple deployments can reference the same group. See references/deployment-blocks.md for details.

Deployment Auto-Approve Block

Define rules to automatically approve deployment plans (HCP Terraform Premium tier feature):

deployment_auto_approve "safe_changes" {
  deployment_group = deployment_group.canary

  check {
    condition = context.plan.changes.remove == 0
    reason    = "Cannot auto-approve plans with resource deletions"
  }
}

Available context variables: context.plan.applyable, context.plan.changes.add/change/remove/total, context.success

Note: orchestrate blocks are deprecated. Use deployment_group and deployment_auto_approve instead.

See references/deployment-blocks.md for all context variables and patterns.

Publish Output and Upstream Input Blocks

Link Stacks together by publishing outputs from one Stack and consuming them in another:

# In network Stack - publish outputs
publish_output "vpc_id_network" {
  type  = string
  value = deployment.network.vpc_id
}

# In application Stack - consume outputs
upstream_input "network_stack" {
  type   = "stack"
  source = "app.terraform.io/my-org/my-project/networking-stack"
}

deployment "app" {
  inputs = {
    vpc_id = upstream_input.network_stack.vpc_id_network
  }
}

See references/linked-stacks.md for complete documentation and examples.

Terraform Stacks CLI

Note: Terraform Stacks is Generally Available (GA) as of Terraform CLI v1.13+. Stacks now count toward Resources Under Management (RUM) for HCP Terraform billing.

Initialize and Validate
terraform stacks init              # Download providers, modules, generate lock file
terraform stacks providers-lock    # Regenerate lock file (add platforms if needed)
terraform stacks validate          # Check syntax without uploading
Deployment Workflow

Important: No plan or apply commands. Upload configuration triggers deployment runs automatically.

# 1. Upload configuration (triggers deployment runs)
terraform stacks configuration upload

# 2. Monitor deployments
terraform stacks deployment-run list                          # List runs (non-interactive)
terraform stacks deployment-group watch -deployment-group=... # Stream status updates

# 3. Approve deployments (if auto-approve not configured)
terraform stacks deployment-run approve-all-plans -deployment-run-id=...
terraform stacks deployment-group approve-all-plans -deployment-group=...
terraform stacks deployment-run cancel -deployment-run-id=...  # Cancel if needed
Configuration Management
terraform stacks configuration list                    # List configuration versions
terraform stacks configuration fetch -configuration-id=...  # Download configuration
terraform stacks configuration watch                   # Monitor upload status
Other Commands
terraform stacks create              # Create new Stack (interactive)
terraform stacks fmt                 # Format Stack files
terraform stacks list                # Show all Stacks
terraform stacks version             # Display version
terraform stacks deployment-group rerun -deployment-group=...  # Rerun deployment

Monitoring Deployments with HCP Terraform API

For programmatic monitoring in automation, CI/CD, or non-interactive environments (like AI agents), use the HCP Terraform API instead of CLI watch commands. The API provides endpoints for:

  • Configuration status and validation

  • Deployment group summaries

  • Deployment run status

  • Deployment step details (plan/apply)

  • Error diagnostics with file locations and code snippets

  • Stack outputs via artifacts endpoint

Key points:

  • CLI watch commands stream indefinitely and don't work in automation

  • Use artifacts endpoint to retrieve Stack outputs: GET /api/v2/stack-deployment-steps/{step-id}/artifacts?name=apply-description

  • Diagnostics endpoint requires stack_deployment_step_id query parameter

  • Artifacts endpoint returns HTTP 307 redirect (use curl -L)

For complete API workflow, authentication, polling best practices, and example scripts, see references/api-monitoring.md.

Common Patterns

Component Dependencies: Dependencies are automatically inferred when one component references another's output (e.g., subnet_ids = component.vpc.private_subnet_ids).

Multi-Region Deployment: Use for_each on providers and components to deploy across multiple regions. Each region gets its own provider configuration and component instances.

Deferred Changes: Stacks support deferred changes to handle dependencies where values are only known after apply. This enables complex multi-component deployments where some resources depend on runtime values from other components (cluster endpoints, generated passwords, etc.).

For complete examples including multi-region deployments, component dependencies, deferred changes patterns, and linked Stacks, see references/examples.md.

Best Practices

  1. Component Granularity: Create components for logical infrastructure units that share a lifecycle

  2. Module Compatibility:

    • Modules used with Stacks cannot include provider blocks (configure providers in Stack configuration)

    • Test public registry modules before using in production Stacks - some modules may have compatibility issues

    • Consider using raw resources for critical infrastructure if module compatibility is uncertain

    • Example: Some terraform-aws-modules versions have been found to have compatibility issues with Stacks (e.g., ALB and ECS modules)

  3. State Isolation: Each deployment has its own isolated state

  4. Input Variables: Use variables for values that differ across deployments; use locals for shared values

  5. Provider Lock Files: Always generate and commit .terraform.lock.hcl to version control

  6. Naming Conventions: Use descriptive names for components and deployments

  7. Deployment Groups: You can organize deployments into deployment groups. Deployment groups enable auto-approval rules, logical organization, and provide a foundation for scaling. Deployment groups are an HCP Terraform Premium tier feature

  8. Testing: Test Stack configurations in dev/staging deployments before production

Troubleshooting

Circular Dependencies: Refactor to break circular references or use intermediate components.

Deployment Destruction: Cannot destroy from UI. Set destroy = true in deployment block, upload configuration, and HCP Terraform creates a destroy run.

Empty Diagnostics: Add required stack_deployment_step_id query parameter to diagnostics API requests.

Module Compatibility: Test public registry modules before production use. Some modules may have compatibility issues with Stacks.

References

For detailed documentation, see:

  • references/component-blocks.md - Complete component block reference with all arguments and syntax

  • references/deployment-blocks.md - Complete deployment block reference with all configuration options

  • references/linked-stacks.md - Publish outputs and upstream inputs for linking Stacks together

  • references/examples.md - Complete working examples for multi-region and component dependencies

  • references/api-monitoring.md - Full API workflow for programmatic monitoring and automation

  • references/troubleshooting.md - Detailed troubleshooting guide for common issues and solutions

Files

references/api-monitoring.md

API Monitoring Reference

Complete guide for monitoring Terraform Stack deployments using the HCP Terraform API. Use this approach for automation, CI/CD pipelines, and non-interactive environments like AI agents.

Table of Contents

  1. When to Use the API

  2. Authentication

  3. API Monitoring Workflow

  4. Detailed Endpoint Reference

  5. Notes for AI Agents and Automation

When to Use the API

Use the HCP Terraform API instead of CLI commands when:

  • Running in non-interactive environments (CI/CD, automation scripts)

  • Building tools or integrations that need programmatic access

  • Monitoring multiple Stacks simultaneously

  • Implementing custom retry logic or error handling

  • Working in environments where streaming CLI commands don't work

CLI commands that don't work in automation:

  • terraform stacks deployment-run watch - Streams output, blocks indefinitely

  • terraform stacks deployment-group watch - Streams output, blocks indefinitely

  • terraform stacks configuration watch - Streams output, blocks indefinitely

Authentication

Extract API Token from Credentials File
TOKEN=$(jq -r '.credentials["app.terraform.io"].token' ~/.terraform.d/credentials.tfrc.json)
Alternative: Use Environment Variable
export TFC_TOKEN="your-token-here"
TOKEN=$TFC_TOKEN
API Request Headers

All API requests require these headers:

-H "Authorization: Bearer $TOKEN"
-H "Content-Type: application/vnd.api+json"

API Monitoring Workflow

After uploading a configuration with terraform stacks configuration upload, follow this sequence to monitor deployment progress:

Step 1: Get Configuration Status

Endpoint: GET /api/v2/stack-configurations/{configuration-id}

Purpose: Verify configuration upload completed successfully and get the configuration details.

Request:

curl -s -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/vnd.api+json" \
  "https://app.terraform.io/api/v2/stack-configurations/{configuration-id}" | jq '.'

Response Fields:

  • attributes.status - Configuration processing status (pending/completed)

  • attributes.sequence-number - Version number of this configuration

  • attributes.components-detected - Number of components found

  • attributes.deployments-detected - Number of deployments found

Example Response:

{
  "data": {
    "id": "stc-ABC123",
    "type": "stack-configurations",
    "attributes": {
      "status": "completed",
      "sequence-number": 5,
      "components-detected": 3,
      "deployments-detected": 2,
      "created-at": "2024-01-15T10:30:00.000Z",
      "updated-at": "2024-01-15T10:30:45.000Z"
    }
  }
}
Step 2: Get Deployment Group Summaries

Endpoint: GET /api/v2/stack-configurations/{configuration-id}/stack-deployment-group-summaries

Purpose: Get list of deployment groups, their IDs, and current status summary.

Request:

curl -s -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/vnd.api+json" \
  "https://app.terraform.io/api/v2/stack-configurations/{configuration-id}/stack-deployment-group-summaries" | jq '.'

Response Fields:

  • id - Deployment group ID (needed for next step)

  • attributes.name - Deployment group name (e.g., dev_default)

  • attributes.status - Overall status (running/succeeded/failed)

  • attributes.status-counts - Breakdown of deployment statuses

Example Response:

{
  "data": [
    {
      "id": "sdg-XYZ789",
      "type": "stack-deployment-group-summaries",
      "attributes": {
        "name": "dev_default",
        "status": "running",
        "status-counts": {
          "pending": 0,
          "running": 1,
          "succeeded": 1,
          "failed": 0
        }
      }
    }
  ]
}
Step 3: Get Deployment Runs

Endpoint: GET /api/v2/stack-deployment-groups/{group-id}/stack-deployment-runs

Purpose: Get list of deployment runs for a specific group with their current status.

Request:

curl -s -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/vnd.api+json" \
  "https://app.terraform.io/api/v2/stack-deployment-groups/{group-id}/stack-deployment-runs" | jq '.'

Response Fields:

  • id - Deployment run ID (needed for next step)

  • attributes.status - Current status (planning/planned/applying/applied/failed)

  • attributes.created-at - Run start time

  • attributes.updated-at - Last update time

Example Response:

{
  "data": [
    {
      "id": "sdr-123ABC",
      "type": "stack-deployment-runs",
      "attributes": {
        "status": "planning",
        "created-at": "2024-01-15T10:31:00.000Z",
        "updated-at": "2024-01-15T10:31:15.000Z"
      }
    }
  ]
}
Step 4: Get Deployment Steps

Endpoint: GET /api/v2/stack-deployment-runs/{run-id}/stack-deployment-steps

Purpose: Get detailed information about individual plan and apply steps.

Request:

curl -s -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/vnd.api+json" \
  "https://app.terraform.io/api/v2/stack-deployment-runs/{run-id}/stack-deployment-steps" | jq '.'

Response Fields:

  • id - Step ID (needed for diagnostics and outputs)

  • attributes.operation-type - Type of operation (plan/apply)

  • attributes.status - Step status (running/completed/failed)

  • attributes.component-name - Which component is being processed

Example Response:

{
  "data": [
    {
      "id": "sds-PlanStep123",
      "type": "stack-deployment-steps",
      "attributes": {
        "operation-type": "plan",
        "status": "completed",
        "component-name": "vpc",
        "created-at": "2024-01-15T10:31:05.000Z",
        "completed-at": "2024-01-15T10:31:30.000Z"
      }
    },
    {
      "id": "sds-ApplyStep456",
      "type": "stack-deployment-steps",
      "attributes": {
        "operation-type": "apply",
        "status": "running",
        "component-name": "vpc",
        "created-at": "2024-01-15T10:32:00.000Z"
      }
    }
  ]
}
Step 5: Get Error Diagnostics (When Deployment Fails)

Endpoint: GET /api/v2/stack-deployment-steps/{step-id}/stack-diagnostics

Purpose: Retrieve detailed error messages when a deployment step fails.

Critical: The stack_deployment_step_id query parameter is required. Without it, the API returns empty results.

Request:

curl -s -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/vnd.api+json" \
  "https://app.terraform.io/api/v2/stack-deployment-steps/{step-id}/stack-diagnostics?stack_deployment_step_id={step-id}" | jq '.'

Response Fields:

  • attributes.severity - Diagnostic level (error/warning)

  • attributes.summary - Brief error description

  • attributes.detail - Detailed error message

  • attributes.diags - Array of diagnostic objects with file locations and code snippets

Example Response (Error with Details):

{
  "data": [
    {
      "id": "stf-ErrorExampleId",
      "type": "stack-diagnostics",
      "attributes": {
        "severity": "error",
        "summary": "Diagnostics reported",
        "detail": "2 errors",
        "diags": [
          {
            "summary": "Unsupported attribute",
            "detail": "This object does not have an attribute named \"target_id\".",
            "range": {
              "filename": "main.tf",
              "start": {
                "line": 634,
                "column": 33
              },
              "end": {
                "line": 634,
                "column": 43
              },
              "source": "registry.terraform.io/terraform-aws-modules/alb/[email protected]//main.tf"
            },
            "snippet": {
              "code": "  target_id         = each.value.target_id",
              "context": "resource \"aws_lb_target_group_attachment\" \"this\""
            }
          },
          {
            "summary": "Invalid reference",
            "detail": "A reference to a resource type must be followed by at least one attribute access.",
            "range": {
              "filename": "main.tf",
              "start": {
                "line": 142,
                "column": 15
              },
              "end": {
                "line": 142,
                "column": 28
              },
              "source": "local-module//main.tf"
            },
            "snippet": {
              "code": "  vpc_id = aws_vpc.main",
              "context": "resource \"aws_subnet\" \"private\""
            }
          }
        ],
        "acknowledged": false,
        "created-at": "2024-01-15T10:32:15.000Z"
      }
    }
  ]
}

Parsing Diagnostics:

Extract error information with jq:

# Get error summaries
curl -s -H "Authorization: Bearer $TOKEN" \
  "https://app.terraform.io/api/v2/stack-deployment-steps/{step-id}/stack-diagnostics?stack_deployment_step_id={step-id}" | \
  jq -r '.data[].attributes.diags[]? | "\(.summary): \(.detail)"'

# Get file locations
curl -s -H "Authorization: Bearer $TOKEN" \
  "https://app.terraform.io/api/v2/stack-deployment-steps/{step-id}/stack-diagnostics?stack_deployment_step_id={step-id}" | \
  jq -r '.data[].attributes.diags[]? | "\(.range.filename):\(.range.start.line)"'
Step 6: Get Stack Outputs (After Successful Deployment)

Endpoint: GET /api/v2/stack-deployment-steps/{final-apply-step-id}/artifacts?name=apply-description

Purpose: Retrieve Stack outputs after a successful deployment completes.

Important Notes:

  • This endpoint returns HTTP 307 redirect - use curl -L to follow redirects automatically

  • This is currently the only way to retrieve Stack outputs programmatically

  • This endpoint is not documented in public API documentation

  • You need the final apply step ID from Step 4

Request:

curl -L -s -H "Authorization: Bearer $TOKEN" \
  "https://app.terraform.io/api/v2/stack-deployment-steps/{final-apply-step-id}/artifacts?name=apply-description"

Response Structure:

The artifact response includes an .outputs object where each output contains a change.after property with the actual output value:

{
  "outputs": {
    "alb_url": {
      "change": {
        "actions": ["no-op"],
        "before": "http://my-alb-123456789.us-west-2.elb.amazonaws.com",
        "after": "http://my-alb-123456789.us-west-2.elb.amazonaws.com",
        "after_unknown": false,
        "before_sensitive": false,
        "after_sensitive": false
      },
      "type": "string"
    },
    "ecr_repository_url": {
      "change": {
        "actions": ["no-op"],
        "before": "123456789.dkr.ecr.us-west-2.amazonaws.com/my-repo",
        "after": "123456789.dkr.ecr.us-west-2.amazonaws.com/my-repo",
        "after_unknown": false,
        "before_sensitive": false,
        "after_sensitive": false
      },
      "type": "string"
    }
  }
}

Extract Only Output Values:

curl -L -s --header "Authorization: Bearer $TOKEN" \
  "https://app.terraform.io/api/v2/stack-deployment-steps/{final-apply-step-id}/artifacts?name=apply-description" | \
  jq -r '.outputs | to_entries | .[] | "\(.key): \(.value.change.after)"'

Example Output:

alb_url: http://my-alb-123456789.us-west-2.elb.amazonaws.com
ecr_repository_url: 123456789.dkr.ecr.us-west-2.amazonaws.com/my-repo

Detailed Endpoint Reference

Available Artifact Types

The artifacts endpoint accepts these name parameter values:

  • plan-description - Terraform plan output in JSON format

  • plan-debug-log - Detailed debug logs from plan operation

  • apply-description - Terraform apply output including outputs (JSON format)

  • apply-debug-log - Detailed debug logs from apply operation

Polling Best Practices

Recommended polling intervals:

  • Configuration status: Check every 5 seconds until status is "completed"

  • Deployment runs: Check every 10 seconds during active deployment

  • Deployment steps: Check every 10 seconds for individual step status

Implement exponential backoff:

# Example polling script with backoff
RETRY_COUNT=0
MAX_RETRIES=30
BACKOFF=5

while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
  STATUS=$(curl -s -H "Authorization: Bearer $TOKEN" \
    "https://app.terraform.io/api/v2/stack-deployment-runs/{run-id}" | \
    jq -r '.data.attributes.status')

  if [ "$STATUS" = "applied" ] || [ "$STATUS" = "failed" ]; then
    echo "Deployment finished with status: $STATUS"
    break
  fi

  echo "Current status: $STATUS. Waiting ${BACKOFF}s..."
  sleep $BACKOFF
  RETRY_COUNT=$((RETRY_COUNT + 1))
done

Notes for AI Agents and Automation

CLI Command Limitations

These CLI commands DO NOT work in automation:

  • terraform stacks deployment-run watch - Streams output, blocks indefinitely

  • terraform stacks deployment-group watch - Streams output, blocks indefinitely

  • terraform stacks configuration watch - Streams output, blocks indefinitely

Solution: Use API polling instead of watch commands.

No Direct Output Command

There is currently no CLI command to retrieve Stack outputs. You must:

  1. Use API to get deployment steps

  2. Find the final apply step ID

  3. Request the apply-description artifact

  4. Parse JSON to extract outputs

Handling Redirects

The artifacts endpoint returns HTTP 307 redirect to the actual artifact location. Ensure your HTTP client follows redirects:

curl: Use -L flag Python requests: Set allow_redirects=True (default) Node.js fetch: Set redirect: 'follow' (default)

Error Handling

Common API errors:

  • 401 Unauthorized: Invalid or expired token - refresh credentials

  • 404 Not Found: Invalid ID or resource doesn't exist yet - retry with backoff

  • 429 Too Many Requests: Rate limited - implement exponential backoff

  • Empty diagnostics: Missing required stack_deployment_step_id query parameter

Complete Monitoring Script Example
#!/bin/bash

# Configuration
TOKEN=$(jq -r '.credentials["app.terraform.io"].token' ~/.terraform.d/credentials.tfrc.json)
CONFIG_ID="stc-ABC123"
BASE_URL="https://app.terraform.io/api/v2"

# Helper function
api_get() {
  curl -s -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/vnd.api+json" \
    "$1"
}

# 1. Wait for configuration to complete
echo "Checking configuration status..."
while true; do
  STATUS=$(api_get "$BASE_URL/stack-configurations/$CONFIG_ID" | jq -r '.data.attributes.status')
  [ "$STATUS" = "completed" ] && break
  echo "Configuration status: $STATUS. Waiting..."
  sleep 5
done

# 2. Get deployment groups
echo "Getting deployment groups..."
GROUP_ID=$(api_get "$BASE_URL/stack-configurations/$CONFIG_ID/stack-deployment-group-summaries" | \
  jq -r '.data[0].id')

# 3. Get deployment run
echo "Getting deployment run..."
RUN_ID=$(api_get "$BASE_URL/stack-deployment-groups/$GROUP_ID/stack-deployment-runs" | \
  jq -r '.data[0].id')

# 4. Monitor deployment run
echo "Monitoring deployment run: $RUN_ID"
while true; do
  STATUS=$(api_get "$BASE_URL/stack-deployment-runs/$RUN_ID" | jq -r '.data.attributes.status')
  echo "Deployment status: $STATUS"

  if [ "$STATUS" = "applied" ]; then
    echo "Deployment succeeded!"

    # 5. Get outputs from final apply step
    APPLY_STEP=$(api_get "$BASE_URL/stack-deployment-runs/$RUN_ID/stack-deployment-steps" | \
      jq -r '.data[] | select(.attributes["operation-type"] == "apply") | .id' | tail -1)

    echo "Retrieving outputs from step: $APPLY_STEP"
    curl -L -s -H "Authorization: Bearer $TOKEN" \
      "$BASE_URL/stack-deployment-steps/$APPLY_STEP/artifacts?name=apply-description" | \
      jq -r '.outputs | to_entries | .[] | "\(.key): \(.value.change.after)"'
    break
  fi

  if [ "$STATUS" = "failed" ]; then
    echo "Deployment failed!"

    # Get error diagnostics
    FAILED_STEP=$(api_get "$BASE_URL/stack-deployment-runs/$RUN_ID/stack-deployment-steps" | \
      jq -r '.data[] | select(.attributes.status == "failed") | .id' | head -1)

    echo "Error diagnostics from step: $FAILED_STEP"
    api_get "$BASE_URL/stack-deployment-steps/$FAILED_STEP/stack-diagnostics?stack_deployment_step_id=$FAILED_STEP" | \
      jq -r '.data[].attributes.diags[]? | "\(.summary): \(.detail)"'
    exit 1
  fi

  sleep 10
done

This script demonstrates a complete monitoring workflow from configuration upload to output retrieval with error handling.

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs an API key, Needs a command-line tool

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
HashiCorp
Publisher
HashiCorp (Official)
Source
hashicorp/agent-skills · plugins/terraform/skills/terraform-stacks · commit 5e30fa5
Licence
Mozilla Public License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by HashiCorp or HashiCorp.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download terraform-stacks.zip