{"id":"terraform","kind":"sdk","name":"Terraform Provider SDK","slug":"terraform","description":"Plugin Framework and SDKs for building Terraform providers.","vendor":"HashiCorp","languages":["go"],"categories":["infrastructure","devtools"],"homepage":"https://developer.hashicorp.com/terraform/plugin","docsUrl":"https://developer.hashicorp.com/terraform/plugin/framework","githubUrl":"https://github.com/hashicorp/terraform-plugin-framework","packages":[{"registry":"go","name":"github.com/hashicorp/terraform-plugin-framework","url":"https://pkg.go.dev/github.com/hashicorp/terraform-plugin-framework"},{"registry":"go","name":"github.com/hashicorp/terraform-plugin-sdk/v2","url":"https://pkg.go.dev/github.com/hashicorp/terraform-plugin-sdk/v2"}],"tags":["iac","providers"],"skills":[{"name":"terraform-test","url":"https://skills.sh/hashicorp/agent-skills/terraform-test","install":"npx skills add hashicorp/agent-skills --skill terraform-test","sdk":"terraform","key":"terraform/terraform-test","description":"Comprehensive guide for writing and running Terraform tests. Use when creating test files (.tftest.hcl), writing test scenarios with run blocks, validating infrastructure behavior with assertions, mocking providers and data sources, testing module outputs and resource configurations, or troubleshooting Terraform test syntax and execution.","hasContent":true,"content":"---\nname: terraform-test\ndescription: Comprehensive guide for writing and running Terraform tests. Use when creating test files (.tftest.hcl), writing test scenarios with run blocks, validating infrastructure behavior with assertions, mocking providers and data sources, testing module outputs and resource configurations, or troubleshooting Terraform test syntax and execution.\nmetadata:\n  copyright: Copyright IBM Corp. 2026\n  version: \"0.0.2\"\n---\n\n# Terraform Test\n\nTerraform's built-in testing framework validates that configuration updates don't introduce breaking changes. Tests run against temporary resources, protecting existing infrastructure and state files.\n\n## Reference Files\n\n- `references/MOCK_PROVIDERS.md` — Mock provider syntax, common defaults, when to use mocks (Terraform 1.7.0+ only — skip if the user's version is below 1.7)\n- `references/CI_CD.md` — GitHub Actions and GitLab CI pipeline examples\n- `references/EXAMPLES.md` — Complete example test suite (unit, integration, and mock tests for a VPC module)\n\nRead the relevant reference file when the user asks about mocking, CI/CD integration, or wants a full example.\n\n## Core Concepts\n\n- **Test file** (`.tftest.hcl` / `.tftest.json`): Contains `run` blocks that validate your configuration\n- **Run block**: A single test scenario with optional variables, providers, and assertions\n- **Assert block**: Conditions that must be true for the test to pass\n- **Mock provider**: Simulates provider behavior without real infrastructure (Terraform 1.7.0+)\n- **Test modes**: `apply` (default, creates real resources) or `plan` (validates logic only)\n\n## File Structure\n\n```\nmy-module/\n├── main.tf\n├── variables.tf\n├── outputs.tf\n└── tests/\n    ├── defaults_unit_test.tftest.hcl         # plan mode — fast, no resources\n    ├── validation_unit_test.tftest.hcl        # plan mode\n    └── full_stack_integration_test.tftest.hcl # apply mode — creates real resources\n```\n\nUse `*_unit_test.tftest.hcl` for plan-mode tests and `*_integration_test.tftest.hcl` for apply-mode tests so they can be filtered separately in CI.\n\n## Test File Structure\n\n```hcl\n# Optional: test-wide settings\ntest {\n  parallel = true  # Enable parallel execution for all run blocks (default: false)\n}\n\n# Optional: file-level variables (highest precedence, override all other sources)\nvariables {\n  aws_region    = \"us-west-2\"\n  instance_type = \"t2.micro\"\n}\n\n# Optional: provider configuration\nprovider \"aws\" {\n  region = var.aws_region\n}\n\n# Required: at least one run block\nrun \"test_default_configuration\" {\n  command = plan\n\n  assert {\n    condition     = aws_instance.example.instance_type == \"t2.micro\"\n    error_message = \"Instance type should be t2.micro by default\"\n  }\n}\n```\n\n## Run Block\n\n```hcl\nrun \"test_name\" {\n  command  = plan  # or apply (default)\n  parallel = true  # optional, since v1.9.0\n\n  # Override file-level variables\n  variables {\n    instance_type = \"t3.large\"\n  }\n\n  # Reference a specific module\n  module {\n    source  = \"./modules/vpc\"  # local or registry only (not git/http)\n    version = \"5.0.0\"          # registry modules only\n  }\n\n  # Control state isolation\n  state_key = \"shared_state\"  # since v1.9.0\n\n  # Plan behavior\n  plan_options {\n    mode    = refresh-only  # or normal (default)\n    refresh = true\n    replace = [aws_instance.example]\n    target  = [aws_instance.example]\n  }\n\n  # Assertions\n  assert {\n    condition     = aws_instance.example.id != \"\"\n    error_message = \"Instance should have a valid ID\"\n  }\n\n  # Expected failures (test passes if these fail)\n  expect_failures = [\n    var.instance_count\n  ]\n}\n```\n\n## Common Test Patterns\n\n### Validate outputs\n\n```hcl\nrun \"test_outputs\" {\n  command = plan\n\n  assert {\n    condition     = output.vpc_id != null\n    error_message = \"VPC ID output must be defined\"\n  }\n\n  assert {\n    condition     = can(regex(\"^vpc-\", output.vpc_id))\n    error_message = \"VPC ID should start with 'vpc-'\"\n  }\n}\n```\n\n### Conditional resources\n\n```hcl\nrun \"test_nat_gateway_disabled\" {\n  command = plan\n\n  variables {\n    create_nat_gateway = false\n  }\n\n  assert {\n    condition     = length(aws_nat_gateway.main) == 0\n    error_message = \"NAT gateway should not be created when disabled\"\n  }\n}\n```\n\n### Resource counts\n\n```hcl\nrun \"test_resource_count\" {\n  command = plan\n\n  variables {\n    instance_count = 3\n  }\n\n  assert {\n    condition     = length(aws_instance.workers) == 3\n    error_message = \"Should create exactly 3 worker instances\"\n  }\n}\n```\n\n### Tags\n\n```hcl\nrun \"test_resource_tags\" {\n  command = plan\n\n  variables {\n    common_tags = {\n      Environment = \"production\"\n      ManagedBy   = \"Terraform\"\n    }\n  }\n\n  assert {\n    condition     = aws_instance.example.tags[\"Environment\"] == \"production\"\n    error_message = \"Environment tag should be set correctly\"\n  }\n\n  assert {\n    condition     = aws_instance.example.tags[\"ManagedBy\"] == \"Terraform\"\n    error_message = \"ManagedBy tag should be set correctly\"\n  }\n}\n```\n\n### Data sources\n\n```hcl\nrun \"test_data_source_lookup\" {\n  command = plan\n\n  assert {\n    condition     = data.aws_ami.ubuntu.id != \"\"\n    error_message = \"Should find a valid Ubuntu AMI\"\n  }\n\n  assert {\n    condition     = can(regex(\"^ami-\", data.aws_ami.ubuntu.id))\n    error_message = \"AMI ID should be in correct format\"\n  }\n}\n```\n\n### Validation rules\n\n```hcl\nrun \"test_invalid_environment\" {\n  command = plan\n\n  variables {\n    environment = \"invalid\"\n  }\n\n  expect_failures = [\n    var.environment\n  ]\n}\n```\n\n### Sequential tests with dependencies\n\n```hcl\nrun \"setup_vpc\" {\n  command = apply\n\n  assert {\n    condition     = output.vpc_id != \"\"\n    error_message = \"VPC should be created\"\n  }\n}\n\nrun \"test_subnet_in_vpc\" {\n  command = plan\n\n  variables {\n    vpc_id = run.setup_vpc.vpc_id\n  }\n\n  assert {\n    condition     = aws_subnet.example.vpc_id == run.setup_vpc.vpc_id\n    error_message = \"Subnet should be in the VPC from setup_vpc\"\n  }\n}\n```\n\n### Plan options (refresh-only, targeted)\n\n```hcl\nrun \"test_refresh_only\" {\n  command = plan\n\n  plan_options {\n    mode = refresh-only\n  }\n\n  assert {\n    condition     = aws_instance.example.tags[\"Environment\"] == \"production\"\n    error_message = \"Tags should be refreshed correctly\"\n  }\n}\n\nrun \"test_specific_resource\" {\n  command = plan\n\n  plan_options {\n    target = [aws_instance.example]\n  }\n\n  assert {\n    condition     = aws_instance.example.instance_type == \"t2.micro\"\n    error_message = \"Targeted resource should be planned\"\n  }\n}\n```\n\n### Parallel modules\n\n```hcl\nrun \"test_networking_module\" {\n  command  = plan\n  parallel = true\n\n  module {\n    source = \"./modules/networking\"\n  }\n\n  assert {\n    condition     = output.vpc_id != \"\"\n    error_message = \"VPC should be created\"\n  }\n}\n\nrun \"test_compute_module\" {\n  command  = plan\n  parallel = true\n\n  module {\n    source = \"./modules/compute\"\n  }\n\n  assert {\n    condition     = output.instance_id != \"\"\n    error_message = \"Instance should be created\"\n  }\n}\n```\n\n### State key sharing\n\n```hcl\nrun \"create_foundation\" {\n  command   = apply\n  state_key = \"foundation\"\n\n  assert {\n    condition     = aws_vpc.main.id != \"\"\n    error_message = \"Foundation VPC should be created\"\n  }\n}\n\nrun \"create_application\" {\n  command   = apply\n  state_key = \"foundation\"\n\n  variables {\n    vpc_id = run.create_foundation.vpc_id\n  }\n\n  assert {\n    condition     = aws_instance.app.vpc_id == run.create_foundation.vpc_id\n    error_message = \"Application should use foundation VPC\"\n  }\n}\n```\n\n### Cleanup ordering (S3 objects before bucket)\n\n```hcl\nrun \"create_bucket\" {\n  command = apply\n\n  assert {\n    condition     = aws_s3_bucket.example.id != \"\"\n    error_message = \"Bucket should be created\"\n  }\n}\n\nrun \"add_objects\" {\n  command = apply\n\n  assert {\n    condition     = length(aws_s3_object.files) > 0\n    error_message = \"Objects should be added\"\n  }\n}\n\n# Cleanup destroys in reverse: objects first, then bucket\n```\n\n### Multiple aliased providers\n\n```hcl\nprovider \"aws\" {\n  alias  = \"primary\"\n  region = \"us-west-2\"\n}\n\nprovider \"aws\" {\n  alias  = \"secondary\"\n  region = \"us-east-1\"\n}\n\nrun \"test_with_specific_provider\" {\n  command = plan\n\n  providers = {\n    aws = provider.aws.secondary\n  }\n\n  assert {\n    condition     = aws_instance.example.availability_zone == \"us-east-1a\"\n    error_message = \"Instance should be in us-east-1 region\"\n  }\n}\n```\n\n### Complex conditions\n\n```hcl\nassert {\n  condition = alltrue([\n    for subnet in aws_subnet.private :\n    can(regex(\"^10\\\\.0\\\\.\", subnet.cidr_block))\n  ])\n  error_message = \"All private subnets should use 10.0.0.0/8 CIDR range\"\n}\n```\n\n## Cleanup\n\nResources are destroyed in **reverse run block order** after test completion. This matters for dependencies (e.g., S3 objects before bucket). Use `terraform test -no-cleanup` to skip cleanup for debugging.\n\n## Running Tests\n\n```bash\nterraform test                                        # all tests\nterraform test tests/defaults.tftest.hcl             # specific file\nterraform test -filter=test_vpc_configuration        # by run block name\nterraform test -test-directory=integration-tests     # custom directory\nterraform test -verbose                              # detailed output\nterraform test -no-cleanup                           # skip resource cleanup\n```\n\n## Best Practices\n\n1. **Naming**: `*_unit_test.tftest.hcl` for plan mode, `*_integration_test.tftest.hcl` for apply mode\n2. **Test naming**: Use descriptive run block names that explain the scenario being tested\n3. **Default to plan**: Use `command = plan` unless you need to test real resource behavior\n4. **Use mocks** for external dependencies — faster and no credentials needed (see `references/MOCK_PROVIDERS.md`)\n5. **Error messages**: Make them specific enough to diagnose failures without running the test again\n6. **Negative tests**: Use `expect_failures` to verify validation rules reject bad inputs\n7. **Variable coverage**: Test different variable combinations to validate all code paths — test variables have the highest precedence and override all other sources\n8. **Module sources**: Test files only support local paths and registry modules — not git or HTTP URLs\n9. **Parallel execution**: Use `parallel = true` for independent tests with different state files\n10. **Cleanup**: Integration tests destroy resources in reverse run block order automatically; use `-no-cleanup` for debugging\n11. **CI/CD**: Run unit tests on every PR, integration tests on merge (see `references/CI_CD.md`)\n\n## Troubleshooting\n\n| Issue | Solution |\n|-------|----------|\n| Assertion failures | Use `-verbose` to see actual vs expected values |\n| Missing credentials | Use mock providers for unit tests |\n| Unsupported module source | Convert git/HTTP sources to local modules |\n| Tests interfering | Use `state_key` or separate modules for isolation |\n| Slow tests | Use `command = plan` and mocks; run integration tests separately |\n\n## References\n\n- [Terraform Testing Documentation](https://developer.hashicorp.com/terraform/language/tests)\n- [Terraform Test Command](https://developer.hashicorp.com/terraform/cli/commands/test)\n- [Testing Best Practices](https://developer.hashicorp.com/terraform/language/tests/best-practices)\n","contentSource":"skills.sh/api/download/hashicorp/agent-skills/terraform-test","contentFetchedAt":"2026-07-27T08:59:33.699Z"},{"name":"terraform-stacks","url":"https://skills.sh/hashicorp/agent-skills/terraform-stacks","install":"npx skills add hashicorp/agent-skills --skill terraform-stacks","sdk":"terraform","key":"terraform/terraform-stacks","description":"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.","hasContent":true,"content":"---\nname: terraform-stacks\ndescription: 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.\nmetadata:\n  copyright: Copyright IBM Corp. 2026\n  version: \"0.0.1\"\n---\n\n# Terraform Stacks\n\nTerraform 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.\n\n## Core Concepts\n\n**Stack**: A complete unit of infrastructure composed of components and deployments that can be managed together.\n\n**Component**: An abstraction around a Terraform module that defines infrastructure pieces. Each component specifies a source module, inputs, and providers.\n\n**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.\n\n**Stack Language**: A separate HCL-based language (not regular Terraform HCL) with distinct blocks and file extensions.\n\n## File Structure\n\nTerraform Stacks use specific file extensions:\n\n- **Component configuration**: `.tfcomponent.hcl`\n- **Deployment configuration**: `.tfdeploy.hcl`\n- **Provider lock file**: `.terraform.lock.hcl` (generated by CLI)\n\nAll configuration files must be at the root level of the Stack repository. HCP Terraform processes all files in dependency order.\n\n### Recommended File Organization\n\n```\nmy-stack/\n├── .terraform-version               # The required Terraform version for this Stack\n├── variables.tfcomponent.hcl        # Variable declarations\n├── providers.tfcomponent.hcl        # Provider configurations\n├── components.tfcomponent.hcl       # Component definitions\n├── outputs.tfcomponent.hcl          # Stack outputs\n├── deployments.tfdeploy.hcl         # Deployment definitions\n├── .terraform.lock.hcl              # Provider lock file (generated)\n└── modules/                         # Local modules (optional - only if using local modules)\n    ├── s3/\n    └── compute/\n```\n\n**Note**: The `modules/` directory is only required when using local module sources. Components can reference modules from:\n- Local file paths: `./modules/vpc`\n- Public registry: `terraform-aws-modules/vpc/aws`\n- Private registry: `app.terraform.io/<org-name>/vpc/aws`\n- Git: `git::https://github.com/org/repo.git//path?ref=v1.0.0`\n\nHCP Terraform processes all `.tfcomponent.hcl` and `.tfdeploy.hcl` files in dependency order.\n\n## Required Terraform version (.terraform-version)\n\nUse Terraform v1.13.x or later to access the Stacks CLI plugin and to run\nterraform stacks CLI commands. Begin by adding a .terraform-version file to\nyour Stack's root directory to specify the Terraform version required for your\nStack. For example, the following file specifies Terraform v1.14.5:\n\n```\n1.14.5\n```\n\n## Component Configuration (.tfcomponent.hcl)\n\n### Variable Block\n\nDeclare input variables for the Stack configuration. Variables must define a `type` field and do not support the `validation` argument.\n\n```hcl\nvariable \"aws_region\" {\n  type        = string\n  description = \"AWS region for deployments\"\n  default     = \"us-west-1\"\n}\n\nvariable \"identity_token\" {\n  type        = string\n  description = \"OIDC identity token\"\n  ephemeral   = true  # Does not persist to state file\n}\n\nvariable \"instance_count\" {\n  type     = number\n  nullable = false\n}\n```\n\n**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.\n\n### Required Providers Block\n\n```hcl\nrequired_providers {\n  aws = {\n    source  = \"hashicorp/aws\"\n    version = \"~> 6.0\"\n  }\n  random = {\n    source  = \"hashicorp/random\"\n    version = \"~> 3.5.0\"\n  }\n}\n```\n\n### Provider Block\n\nProvider blocks differ from traditional Terraform:\n\n1. Support `for_each` meta-argument\n2. Define aliases in the block header (not as an argument)\n3. Accept configuration through a `config` block\n\n**Single Provider Configuration:**\n\n```hcl\nprovider \"aws\" \"this\" {\n  config {\n    region = var.aws_region\n    assume_role_with_web_identity {\n      role_arn           = var.role_arn\n      web_identity_token = var.identity_token\n    }\n  }\n}\n```\n\n**Multiple Provider Configurations with for_each:**\n\n```hcl\nprovider \"aws\" \"configurations\" {\n  for_each = var.regions\n\n  config {\n    region = each.value\n    assume_role_with_web_identity {\n      role_arn           = var.role_arn\n      web_identity_token = var.identity_token\n    }\n  }\n}\n```\n\n**Authentication Best Practice**: Use **workload identity** (OIDC) as the preferred authentication method for Stacks. This approach:\n- Avoids long-lived static credentials\n- Provides temporary, scoped credentials per deployment run\n- Integrates with cloud provider IAM (AWS IAM Roles, Azure Managed Identities, GCP Service Accounts)\n- Eliminates need for platform-managed environment variables\n\nConfigure 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\n\n### Component Block\n\nEach 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.\n\n```hcl\ncomponent \"vpc\" {\n  source  = \"app.terraform.io/my-org/vpc/aws\"  # Local, registry, or Git URL\n  version = \"2.1.0\"          # For registry modules\n\n  inputs = {\n    cidr_block  = var.vpc_cidr\n    name_prefix = var.name_prefix\n  }\n\n  providers = {\n    aws = provider.aws.this\n  }\n}\n```\n\nSee `references/component-blocks.md` for examples of dependencies, for_each, public registry modules, Git sources, and more.\n\n**Key Points:**\n- Reference outputs: `component.<name>.<output>` or `component.<name>[key].<output>` for for_each\n- Dependencies inferred automatically from component references\n- Aggregate with for expressions: `[for x in component.s3 : x.bucket_name]`\n- For components with `for_each`, reference specific instances: `component.<name>[each.value].<output>`\n- Provider references are normal values: `provider.<type>.<alias>` or `provider.<type>.<alias>[each.value]`\n\n### Output Block\n\nOutputs require a `type` argument and do not support `preconditions`:\n\n```hcl\noutput \"vpc_id\" {\n  type        = string\n  description = \"VPC ID\"\n  value       = component.vpc.vpc_id\n}\n\noutput \"endpoint_urls\" {\n  type      = map(string)\n  value     = {\n    for region, comp in component.api : region => comp.endpoint_url\n  }\n  sensitive = false\n}\n```\n\n### Locals Block\n\nLocals blocks work the same in both `.tfcomponent.hcl` and `.tfdeploy.hcl` files:\n\n```hcl\nlocals {\n  common_tags = {\n    Environment = var.environment\n    ManagedBy   = \"Terraform Stacks\"\n    Project     = var.project_name\n  }\n\n  region_config = {\n    for region in var.regions : region => {\n      name_suffix = \"${var.environment}-${region}\"\n    }\n  }\n}\n```\n\n### Removed Block\n\nUse to safely remove components from a Stack. HCP Terraform requires the component's providers to remove it.\n\n```hcl\nremoved {\n  from   = component.old_component\n  source = \"./modules/old-module\"\n\n  providers = {\n    aws = provider.aws.this\n  }\n}\n```\n\n## Deployment Configuration (.tfdeploy.hcl)\n\n### Identity Token Block\n\nGenerate JWT tokens for OIDC authentication with cloud providers:\n\n```hcl\nidentity_token \"aws\" {\n  audience = [\"aws.workload.identity\"]\n}\n\nidentity_token \"azure\" {\n  audience = [\"api://AzureADTokenExchange\"]\n}\n```\n\nReference tokens in deployments using `identity_token.<name>.jwt`\n\n### Store Block\n\nAccess HCP Terraform variable sets within Stack deployments:\n\n```hcl\nstore \"varset\" \"aws_credentials\" {\n  id       = \"varset-ABC123\"  # Alternatively use: name = \"varset_name\"\n  source   = \"tfc-cloud-shared\"\n  category = \"terraform\"      # Alternatively use: category = \"env\" for environment variables\n}\n\ndeployment \"production\" {\n  inputs = {\n    aws_access_key = store.varset.aws_credentials.AWS_ACCESS_KEY_ID\n  }\n}\n```\n\nUse to centralize credentials and share variables across Stacks. See `references/deployment-blocks.md` for details.\n\n### Deployment Block\n\nDefine deployment instances (minimum 1, maximum 20 per Stack):\n\n```hcl\ndeployment \"production\" {\n  inputs = {\n    aws_region     = \"us-west-1\"\n    instance_count = 3\n    role_arn       = local.role_arn\n    identity_token = identity_token.aws.jwt\n  }\n}\n\n# Create multiple deployments for different environments\ndeployment \"development\" {\n  inputs = {\n    aws_region     = \"us-east-1\"\n    instance_count = 1\n    name_suffix    = \"dev\"\n    role_arn       = local.role_arn\n    identity_token = identity_token.aws.jwt\n  }\n}\n```\n\n**To destroy a deployment**: Set `destroy = true`, upload configuration, approve destroy run, then remove the deployment block. See `references/deployment-blocks.md` for details.\n\n### Deployment Group Block\n\nGroup deployments together for shared settings (HCP Terraform Premium tier feature). Free/standard tiers use default groups named `{deployment-name}_default`.\n\n```hcl\ndeployment_group \"canary\" {\n  auto_approve_checks = [deployment_auto_approve.safe_changes]\n}\n\ndeployment \"dev\" {\n  inputs = { /* ... */ }\n  deployment_group = deployment_group.canary\n}\n```\n\nMultiple deployments can reference the same group. See `references/deployment-blocks.md` for details.\n\n### Deployment Auto-Approve Block\n\nDefine rules to automatically approve deployment plans (HCP Terraform Premium tier feature):\n\n```hcl\ndeployment_auto_approve \"safe_changes\" {\n  deployment_group = deployment_group.canary\n\n  check {\n    condition = context.plan.changes.remove == 0\n    reason    = \"Cannot auto-approve plans with resource deletions\"\n  }\n}\n```\n\n**Available context variables**: `context.plan.applyable`, `context.plan.changes.add/change/remove/total`, `context.success`\n\n**Note:** `orchestrate` blocks are deprecated. Use `deployment_group` and `deployment_auto_approve` instead.\n\nSee `references/deployment-blocks.md` for all context variables and patterns.\n\n### Publish Output and Upstream Input Blocks\n\nLink Stacks together by publishing outputs from one Stack and consuming them in another:\n\n```hcl\n# In network Stack - publish outputs\npublish_output \"vpc_id_network\" {\n  type  = string\n  value = deployment.network.vpc_id\n}\n\n# In application Stack - consume outputs\nupstream_input \"network_stack\" {\n  type   = \"stack\"\n  source = \"app.terraform.io/my-org/my-project/networking-stack\"\n}\n\ndeployment \"app\" {\n  inputs = {\n    vpc_id = upstream_input.network_stack.vpc_id_network\n  }\n}\n```\n\nSee `references/linked-stacks.md` for complete documentation and examples.\n\n## Terraform Stacks CLI\n\n**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.\n\n### Initialize and Validate\n\n```bash\nterraform stacks init              # Download providers, modules, generate lock file\nterraform stacks providers-lock    # Regenerate lock file (add platforms if needed)\nterraform stacks validate          # Check syntax without uploading\n```\n\n### Deployment Workflow\n\n**Important**: No `plan` or `apply` commands. Upload configuration triggers deployment runs automatically.\n\n```bash\n# 1. Upload configuration (triggers deployment runs)\nterraform stacks configuration upload\n\n# 2. Monitor deployments\nterraform stacks deployment-run list                          # List runs (non-interactive)\nterraform stacks deployment-group watch -deployment-group=... # Stream status updates\n\n# 3. Approve deployments (if auto-approve not configured)\nterraform stacks deployment-run approve-all-plans -deployment-run-id=...\nterraform stacks deployment-group approve-all-plans -deployment-group=...\nterraform stacks deployment-run cancel -deployment-run-id=...  # Cancel if needed\n```\n\n### Configuration Management\n\n```bash\nterraform stacks configuration list                    # List configuration versions\nterraform stacks configuration fetch -configuration-id=...  # Download configuration\nterraform stacks configuration watch                   # Monitor upload status\n```\n\n### Other Commands\n\n```bash\nterraform stacks create              # Create new Stack (interactive)\nterraform stacks fmt                 # Format Stack files\nterraform stacks list                # Show all Stacks\nterraform stacks version             # Display version\nterraform stacks deployment-group rerun -deployment-group=...  # Rerun deployment\n```\n\n## Monitoring Deployments with HCP Terraform API\n\nFor 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:\n\n- Configuration status and validation\n- Deployment group summaries\n- Deployment run status\n- Deployment step details (plan/apply)\n- Error diagnostics with file locations and code snippets\n- Stack outputs via artifacts endpoint\n\n**Key points:**\n- CLI watch commands stream indefinitely and don't work in automation\n- Use artifacts endpoint to retrieve Stack outputs: `GET /api/v2/stack-deployment-steps/{step-id}/artifacts?name=apply-description`\n- Diagnostics endpoint requires `stack_deployment_step_id` query parameter\n- Artifacts endpoint returns HTTP 307 redirect (use `curl -L`)\n\nFor complete API workflow, authentication, polling best practices, and example scripts, see `references/api-monitoring.md`.\n\n## Common Patterns\n\n**Component Dependencies**: Dependencies are automatically inferred when one component references another's output (e.g., `subnet_ids = component.vpc.private_subnet_ids`).\n\n**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.\n\n**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.).\n\nFor complete examples including multi-region deployments, component dependencies, deferred changes patterns, and linked Stacks, see `references/examples.md`.\n\n## Best Practices\n\n1. **Component Granularity**: Create components for logical infrastructure units that share a lifecycle\n2. **Module Compatibility**:\n   - Modules used with Stacks cannot include provider blocks (configure providers in Stack configuration)\n   - **Test public registry modules** before using in production Stacks - some modules may have compatibility issues\n   - Consider using raw resources for critical infrastructure if module compatibility is uncertain\n   - Example: Some terraform-aws-modules versions have been found to have compatibility issues with Stacks (e.g., ALB and ECS modules)\n3. **State Isolation**: Each deployment has its own isolated state\n4. **Input Variables**: Use variables for values that differ across deployments; use locals for shared values\n5. **Provider Lock Files**: Always generate and commit `.terraform.lock.hcl` to version control\n6. **Naming Conventions**: Use descriptive names for components and deployments\n7. **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\n8. **Testing**: Test Stack configurations in dev/staging deployments before production\n\n## Troubleshooting\n\n**Circular Dependencies**: Refactor to break circular references or use intermediate components.\n\n**Deployment Destruction**: Cannot destroy from UI. Set `destroy = true` in deployment block, upload configuration, and HCP Terraform creates a destroy run.\n\n**Empty Diagnostics**: Add required `stack_deployment_step_id` query parameter to diagnostics API requests.\n\n**Module Compatibility**: Test public registry modules before production use. Some modules may have compatibility issues with Stacks.\n\n## References\n\nFor detailed documentation, see:\n- `references/component-blocks.md` - Complete component block reference with all arguments and syntax\n- `references/deployment-blocks.md` - Complete deployment block reference with all configuration options\n- `references/linked-stacks.md` - Publish outputs and upstream inputs for linking Stacks together\n- `references/examples.md` - Complete working examples for multi-region and component dependencies\n- `references/api-monitoring.md` - Full API workflow for programmatic monitoring and automation\n- `references/troubleshooting.md` - Detailed troubleshooting guide for common issues and solutions\n","contentSource":"skills.sh/api/download/hashicorp/agent-skills/terraform-stacks","contentFetchedAt":"2026-07-27T08:59:33.749Z"},{"name":"terraform-style-guide","url":"https://skills.sh/hashicorp/terraform-agent-kit/terraform-style-guide","install":"npx skills add hashicorp/terraform-agent-kit --skill terraform-style-guide","sdk":"terraform","key":"terraform/terraform-style-guide","description":"Generate Terraform HCL code following HashiCorp's official style conventions and best practices. Use when writing, reviewing, or generating Terraform configurations.","hasContent":true,"content":"---\nname: terraform-style-guide\ndescription: Generate Terraform HCL code following HashiCorp's official style conventions and best practices. Use when writing, reviewing, or generating Terraform configurations.\n---\n\n# Terraform Style Guide\n\nGenerate and maintain Terraform code following HashiCorp's official style conventions and best practices.\n\n**Reference:** [HashiCorp Terraform Style Guide](https://developer.hashicorp.com/terraform/language/style)\n\n## Code Generation Strategy\n\nWhen generating Terraform code:\n\n1. Start with provider configuration and version constraints\n2. Create data sources before dependent resources\n3. Build resources in dependency order\n4. Add outputs for key resource attributes\n5. Use variables for all configurable values\n\n## File Organization\n\n| File | Purpose |\n|------|---------|\n| `terraform.tf` | Terraform and provider version requirements |\n| `providers.tf` | Provider configurations |\n| `main.tf` | Primary resources and data sources |\n| `variables.tf` | Input variable declarations (alphabetical) |\n| `outputs.tf` | Output value declarations (alphabetical) |\n| `locals.tf` | Local value declarations |\n\n### Example Structure\n\n```hcl\n# terraform.tf\nterraform {\n  required_version = \">= 1.14\"\n\n  required_providers {\n    aws = {\n      source  = \"hashicorp/aws\"\n      version = \"~> 6.0\"\n    }\n  }\n}\n\n# variables.tf\nvariable \"environment\" {\n  description = \"Target deployment environment\"\n  type        = string\n\n  validation {\n    condition     = contains([\"dev\", \"staging\", \"prod\"], var.environment)\n    error_message = \"Environment must be dev, staging, or prod.\"\n  }\n}\n\n# locals.tf\nlocals {\n  common_tags = {\n    Environment = var.environment\n    ManagedBy   = \"Terraform\"\n  }\n}\n\n# main.tf\nresource \"aws_vpc\" \"main\" {\n  cidr_block           = var.vpc_cidr\n  enable_dns_hostnames = true\n\n  tags = merge(local.common_tags, {\n    Name = \"${var.project_name}-${var.environment}-vpc\"\n  })\n}\n\n# outputs.tf\noutput \"vpc_id\" {\n  description = \"ID of the created VPC\"\n  value       = aws_vpc.main.id\n}\n```\n\n## Code Formatting\n\n### Indentation and Alignment\n\n- Use **two spaces** per nesting level (no tabs)\n- Align equals signs for consecutive arguments\n\n```hcl\nresource \"aws_instance\" \"web\" {\n  ami           = \"ami-0c55b159cbfafe1f0\"\n  instance_type = \"t2.micro\"\n  subnet_id     = \"subnet-12345678\"\n\n  tags = {\n    Name        = \"web-server\"\n    Environment = \"production\"\n  }\n}\n```\n\n### Block Organization\n\nArguments precede blocks, with meta-arguments first:\n\n```hcl\nresource \"aws_instance\" \"example\" {\n  # Meta-arguments\n  count = 3\n\n  # Arguments\n  ami           = \"ami-0c55b159cbfafe1f0\"\n  instance_type = \"t2.micro\"\n\n  # Blocks\n  root_block_device {\n    volume_size = 20\n  }\n\n  # Lifecycle last\n  lifecycle {\n    create_before_destroy = true\n  }\n}\n```\n\n## Naming Conventions\n\n- Use **lowercase with underscores** for all names\n- Use **descriptive nouns** excluding the resource type\n- Be specific and meaningful\n- Resource names must be singular, not plural\n- Default to `main` for resources where a specific descriptive name is redundant or unavailable, provided only one instance exists\n\n```hcl\n# Bad\nresource \"aws_instance\" \"webAPI-aws-instance\" {}\nresource \"aws_instance\" \"web_apis\" {}\nvariable \"name\" {}\n\n# Good\nresource \"aws_instance\" \"web_api\" {}\nresource \"aws_vpc\" \"main\" {}\nvariable \"application_name\" {}\n```\n\n## Variables\n\nEvery variable must include `type` and `description`:\n\n```hcl\nvariable \"instance_type\" {\n  description = \"EC2 instance type for the web server\"\n  type        = string\n  default     = \"t2.micro\"\n\n  validation {\n    condition     = contains([\"t2.micro\", \"t2.small\", \"t2.medium\"], var.instance_type)\n    error_message = \"Instance type must be t2.micro, t2.small, or t2.medium.\"\n  }\n}\n\nvariable \"database_password\" {\n  description = \"Password for the database admin user\"\n  type        = string\n  sensitive   = true\n}\n```\n\n## Outputs\n\nEvery output must include `description`:\n\n```hcl\noutput \"instance_id\" {\n  description = \"ID of the EC2 instance\"\n  value       = aws_instance.web.id\n}\n\noutput \"database_password\" {\n  description = \"Database administrator password\"\n  value       = aws_db_instance.main.password\n  sensitive   = true\n}\n```\n\n## Dynamic Resource Creation\n\n### Prefer for_each over count\n\n```hcl\n# Bad - count for multiple resources\nresource \"aws_instance\" \"web\" {\n  count = var.instance_count\n  tags  = { Name = \"web-${count.index}\" }\n}\n\n# Good - for_each with named instances\nvariable \"instance_names\" {\n  type    = set(string)\n  default = [\"web-1\", \"web-2\", \"web-3\"]\n}\n\nresource \"aws_instance\" \"web\" {\n  for_each = var.instance_names\n  tags     = { Name = each.key }\n}\n```\n\n### count for Conditional Creation\n\n```hcl\nresource \"aws_cloudwatch_metric_alarm\" \"cpu\" {\n  count = var.enable_monitoring ? 1 : 0\n\n  alarm_name = \"high-cpu-usage\"\n  threshold  = 80\n}\n```\n\n## Security Best Practices\n\nRefer to SECURITY.md. It includes guidance on encrypting resources,\npreventing sensitive data in state, and secure configurations.\n\n## Version Pinning\n\n```hcl\nterraform {\n  required_version = \">= 1.14\"\n\n  required_providers {\n    aws = {\n      source  = \"hashicorp/aws\"\n      version = \"~> 6.0\"\n    }\n  }\n}\n```\n\nUse the latest major version of each provider and the latest minor version of\nTerraform, unless otherwise constrained by a dependency lock file or by other\nmodules used by the configuration.\n\n**Version constraint operators:**\n- `= 1.0.0` - Exact version\n- `>= 1.0.0` - Greater than or equal\n- `~> 1.0` - Allow rightmost component to increment\n- `>= 1.0, < 2.0` - Version range\n\n## Provider Configuration\n\n```hcl\nprovider \"aws\" {\n  region = \"us-west-2\"\n\n  default_tags {\n    tags = {\n      ManagedBy = \"Terraform\"\n      Project   = var.project_name\n    }\n  }\n}\n\n# Aliased provider for multi-region\nprovider \"aws\" {\n  alias  = \"east\"\n  region = \"us-east-1\"\n}\n```\n\n## Version Control\n\n**Never commit:**\n- `terraform.tfstate`, `terraform.tfstate.backup`\n- `.terraform/` directory\n- `*.tfplan`\n- `.tfvars` files with sensitive data\n\n**Always commit:**\n- All `.tf` configuration files\n- `.terraform.lock.hcl` (dependency lock file)\n\n## Validation Tools\n\nRun before committing:\n\n```bash\nterraform fmt -recursive\nterraform validate\n```\n\nAdditional tools:\n- `tflint` - Linting and best practices\n- `checkov` / `tfsec` - Security scanning\n\n## Code Review Checklist\n\n- [ ] Code formatted with `terraform fmt`\n- [ ] Configuration validated with `terraform validate`\n- [ ] Files organized according to standard structure\n- [ ] All variables have type and description\n- [ ] All outputs have descriptions\n- [ ] Resource names use descriptive nouns with underscores\n- [ ] Version constraints pinned explicitly\n- [ ] Sensitive values marked with `sensitive = true`\n- [ ] No hardcoded credentials or secrets\n- [ ] Security best practices applied\n\n---\n\n*Based on: [HashiCorp Terraform Style Guide](https://developer.hashicorp.com/terraform/language/style)*\n","contentSource":"skills.sh/api/download/hashicorp/terraform-agent-kit/terraform-style-guide","contentFetchedAt":"2026-07-27T08:59:33.848Z"}],"official":true,"generatedAt":"2026-07-27T09:02:29.956Z"}