Skip to main content
rule CX Codex

terraform · microsoft — Claude Code rule for Terraform

Sets conventions for Terraform files, resource names, modules, and expressions. It applies to .tf, .tfvars, and files under terraform/.

MIT ★ 1,627 updated 2026-10-25

Install into GitHub Copilot · Manually: put the files in place All methods and platforms ↓
.github/instructions/terraform.instructions.md
Open on GitHub

What terraform does

The rule covers Terraform configuration files and the terraform/ directory. It assigns resources and module calls to main.tf, input declarations to variables.tf, and returned values to outputs.tf. A module’s sole resource or data source uses the label this; resource and variable identifiers use snake_case.

Variables and outputs need descriptions without a trailing period, and sensitive values should be marked with sensitive = true. Comments use // or /* */, not #. For optional values, the conventions favor coalesce() and try(); repeated module instances use for_each. One detail matters: coalesce() treats an empty string as empty, so use a ternary expression when that string is a valid value.

The instructions target Terraform 1.6+. For Azure, they call for AzureRM provider 4.0+ or AzAPI. In Claude Code, place the rule at .claude/rules/terraform.md.

What it helps with

  • organize Terraform configuration into standard files
  • align resource and variable names with the conventions
  • document input variables and output values
  • use for_each for repeated module instances
  • handle optional attributes with try() and coalesce()

Example prompts for the agent

  • Refactor main.tf and variables.tf to follow the Terraform conventions in this rule.
  • Add a module for multiple configurations, using for_each with stable keys.
  • Check that variables and outputs have descriptions and that secrets are marked sensitive.

How to install terraform

Manually: put the files in place

.github/instructions/terraform.instructions.md

The applyTo field sets which files it applies to

Step by step, with commands for each platform: AGENTS.md vs CLAUDE.md: what they are and which one to use

Questions about terraform

How do I install terraform in Claude Code?

Add the rule file at .claude/rules/terraform.md.

What does the terraform rule do?

It sets conventions for Terraform file layout, naming, variables, outputs, modules, and expressions.

How does the rule handle optional values?

It favors coalesce() for choosing a fallback and try() for optional attribute access. Use a ternary expression when an empty string is a valid value.

Source text

terraform.instructions.md · MIT
---
applyTo: '**/*.tf, **/*.tfvars, **/terraform/**'
description: 'Terraform infrastructure-as-code authoring conventions'
---
# Terraform Instructions

These instructions define conventions for Terraform Infrastructure as Code (IaC) development in this codebase. Terraform files deploy cloud resources declaratively through the HashiCorp Configuration Language (HCL).

> [!NOTE]
> These instructions target Terraform 1.6+ and include features through January 2026. For Azure deployments, use AzureRM provider 4.0+ or AzAPI for latest resource support.

## Project Structure

Organize Terraform files following a modular architecture:

```text
terraform/
├── modules/                      # Reusable modules for specific resource groupings
│   ├── networking/
│   │   ├── main.tf
│   │   ├── variables.tf
│   │   ├── outputs.tf
│   │   └── versions.tf
│   ├── storage/
│   └── compute/
└── README.md
```

## File Organization

Every Terraform configuration follows a consistent file structure:

| File                   | Purpose                                              |
|------------------------|------------------------------------------------------|
| `main.tf`              | Primary resource definitions and module calls        |
| `variables.tf`         | Input variable declarations                          |
| `outputs.tf`           | Output value declarations                            |
| `versions.tf`          | Required providers and Terraform version constraints |
| `backend.tf`           | State backend configuration (root modules only)      |
| `locals.tf`, `data.tf` | Local values and data sources (when numerous)        |

Within each file, order content as: terraform/provider blocks, variables, locals, data sources, resources, module calls, outputs.

## Naming Conventions

File and folder names use `kebab-case` (e.g., `storage-account.tf`, `modules/web-app/`).

Resource names, variable names, local values, and output names use `snake_case` (e.g., `azurerm_storage_account.data_storage`, `resource_group_name`, `local.computed_name`).

### Resource and Data Source Logical Names

Logical names (the label after the resource or data source type) follow these patterns:

* Singleton of a type: use `"this"` (e.g., `azurerm_resource_group.this`, `data.azurerm_client_config.this`). The Terraform community has coalesced around `"this"` as the dominant symbolic name for the sole resource or data source of a given type within a module.
* Multiple instances with distinct purposes: use descriptive names (e.g., `azurerm_storage_account.data`, `azurerm_storage_account.logs`)
* Dynamic instances: use `for_each` with descriptive keys from `each.key`

```hcl
resource "azurerm_storage_account" "this" {
  // resource parameters here
}

data "azurerm_client_config" "this" {}
```

## Variables and Outputs

### Variable Declarations

Variable conventions:

* Every variable includes a `description` without trailing periods
* Boolean variables start with `should_` or `is_` (e.g., `should_enable_https`, `is_production`)
* Sensitive variables include `sensitive = true`
* Required variables omit the `default` attribute; optional variables include sensible defaults
* Use `null` for optional defaults instead of empty strings
* Avoid adding `validation` blocks unless explicitly requested

```hcl
variable "storage_account_tier" {
  description = "Performance tier for the storage account"
  type        = string
  default     = "Standard"
  sensitive   = false  // Set true for secrets
}
```

### Output Declarations

Every output includes a meaningful `description` without trailing periods. Sensitive outputs include `sensitive = true`. Conditional resources require conditional output expressions.

```hcl
output "storage_account_id" {
  description = "Resource ID of the deployed storage account"
  value       = var.should_deploy ? azurerm_storage_account.this[0].id : null
  sensitive   = true  // Set true for secrets
}
```

## Comment Style

Use `//` for single-line and `/* */` for multi-line comments. Do not use `#` for comments in this codebase.

Section headers use visual separators for organization:

```hcl
// =====================================================
// Networking Resources
// =====================================================
```

## Module Conventions

Child modules in `modules/{name}/` inherit providers and state from the calling root module.

### Module Calls

Use `count = var.condition ? 1 : 0` for conditional module deployment. Prefer `for_each` over `count` for multiple instances with stable resource addresses:

```hcl
module "workload" {
  source   = "../../modules/workload"
  for_each = var.workload_configurations

  name                = each.key
  resource_group_name = azurerm_resource_group.this.name
  configuration       = each.value
}
```

## Expression Functions

### coalesce()

Returns the first non-null and non-empty value. Prefer over ternary operators for default value selection:

```hcl
location = coalesce(var.override_location, var.primary_location, "eastus")
```

Note: `coalesce()` treats empty strings as falsy. Use ternary when empty string is a valid value.

### try()

Returns the value of an expression or a fallback when the expression fails. Prefer over ternary operators for optional attribute access:

```hcl
endpoint = try(var.network.private_endpoint.ip, null)
database_id = try(module.database[0].id, null)
subnet_id = try(each.value.subnet_id, var.default_subnet_id)
```

### Combining coalesce() and try()

Combine these functions for complex optional configuration patterns:

```hcl
// try() inside coalesce(): safe attribute access with simple fallback
nsg_name = coalesce(try(var.network_security_group.name, null), "${var.subnet_name}-nsg")

// coalesce() inside try(): computed default that might fail (Azure Verified Modules pattern)
nsg_name = try(coalesce(var.new_nsg.name, "${var.subnet_name}-nsg"), "${var.subnet_name}-nsg")
```

### When to Use Ternary Operators

Ternary operators remain appropriate for boolean conditions (`var.is_production ? "Premium" : "Standard"`), conditional counts (`count = var.enable_feature ? 1 : 0`), and complex multi-factor logic.

## Data Sources and Deferred Lookups

Use standard Terraform data source syntax for existing resource lookups (e.g., `data "azurerm_resource_group"`, `data "azurerm_client_config"`). Apply the same logical-name convention as resources: a singleton data source uses `"this"`, while multiple data sources of the same type use descriptive names or `for_each` keys.

### Deferred Data Resources

Use `terraform_data` for values computed at apply time or CI compatibility:

```hcl
resource "terraform_data" "deployment_timestamp" {
  triggers_replace = [var.storage_account_name]
  input            = timestamp()

  provisioner "local-exec" {
    command = "az storage account show --name ${var.storage_account_name} --query id -o tsv"
  }
}
```

## Resource Naming

Resource names follow [Azure naming conventions](https://learn.microsoft.com/azure/cloud-adoption-framework/ready/azure-best-practices/resource-naming):

* Hyphens allowed: `${var.prefix}-{abbrev}-${var.environment}-${var.instance}`
* No hyphens: `${var.prefix}{abbrev}${var.environment}${var.instance}`
* Length restricted: `substr("${var.prefix}{abbrev}${random_id.suffix.hex}", 0, 24)`

## Provider Configuration

### Required Providers Block

Every module includes a `versions.tf` with required providers:

```hcl
terraform {
  required_version = ">= 1.6.0"

  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = ">= 4.0"
    }
    azapi = {
      source  = "azure/azapi"
      version = ">= 2.0"
    }
    random = {
      source  = "hashicorp/random"
      version = ">= 3.6"
    }
  }
}
```

### Provider Features

Root modules configure provider features explicitly:

```hcl
provider "azurerm" {
  features {
    resource_group {
      prevent_deletion_if_contains_resources = true
    }
    key_vault {
      purge_soft_delete_on_destroy = false
    }
  }
}
```

## State Management

### Backend Configuration

Root modules include explicit backend configuration:

```hcl
terraform {
  backend "azurerm" {
    resource_group_name  = "tfstate-rg"
    storage_account_name = "tfstateaccount"
    container_name       = "tfstate"
    key                  = "dev/terraform.tfstate"
  }
}
```

### State Management Practices

State files can be stored locally or in remote backends. Do not commit state files to the repository. When using remote backends, enable state locking and protect sensitive values through backend encryption.

## Validation and Formatting

### Pre-commit Checks

Run `terraform fmt -recursive`, `terraform validate`, and `terraform plan` before commits.

### Linting Tools

Use `terraform fmt` for formatting, `terraform validate` for configuration validation, `tflint` for extended linting, and `checkov` or `tfsec` for security scanning.

## Lifecycle Management

Use lifecycle blocks for resources requiring special handling:

```hcl
resource "azurerm_storage_account" "this" {
  // ...

  lifecycle {
    prevent_destroy       = true   // Protect critical resources
    create_before_destroy = true   // Zero-downtime replacement
    ignore_changes        = [tags] // Ignore external tag changes
  }
}
```

## Documentation Requirements

Every Terraform module includes a README.md documenting module purpose, required and optional inputs, outputs, usage examples, and prerequisites.

© microsoft · MIT · microsoft/hve-core

Similar IDE rules

All IDE rules for DevOps and infrastructure →

terraform by other authors comes first.

terraform official github terraform sets standards for writing **/*.tf manifests in GitHub Copilot. It enforces secure AWS secret handling, clean module layout, and strict formatting. CX Codex +1 ★ 41,430repo stars terraform sanjeed5 Enforces opinionated Terraform guidelines in Cursor for project layout, resource naming, remote state locking, and modular design. CX Codex +1 ★ 3,589repo stars terraform-generator akin-ozer The terraform-generator skill writes Terraform configs: resources, modules, providers, variables and outputs. Useful when you want infrastructure as code without hand-writing HCL. CX Codex +1 713installs terraform-test hashicorp terraform-test — a skill for Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI and OpenCode: writes .tftest.hcl files with assertions, runs infrastructure tests against temporary resources. CX Codex +1 9,500installs terraform-infrastructure manutej terraform-infrastructure guides the AI agent in writing HashiCorp Configuration Language code for AWS, Azure, and GCP, covering reusable modules, variable validation, and multi-environment state. CX Codex +1 439installs terraform-tasks JosiahSiegel terraform-tasks — a skill for autonomous Terraform work: generates infrastructure code, builds CI/CD pipelines, migrates resources to state, fixes version issues. CX Codex +1 155installs terraform-best-practices NickCrew terraform-best-practices adds enterprise Terraform guidelines covering module layout, secure remote state, workspace isolation, and CI/CD security scanning. CX Codex +1 109installs terraform-skill Anton Babenko Guides Terraform and OpenTofu refactoring, state migrations, and CI workflows. Diagnoses risks like identity churn and blast radius before generating HCL. CX Codex +1 8,200installs

From the same set148

The whole set →
engagement-reporting engagement-reporting generates source-backed weekly project engagement reports and prepares optional Outlook email drafts. CX Codex +1 ★ 1,627repo stars hve-builder hve-builder is a Claude Code skill for creating or revising prompts, instructions, agents, and skills, or for read-only reviews and mechanical validation without changing files. CX Codex +1 ★ 1,627repo stars bash A rule enforcing consistent Bash script structure: strict mode, main() pattern, formatting, error handling, and Microsoft copyright headers. CX Codex +1 ★ 1,627repo stars incident-response incident-response guides SRE and operations teams through Azure incident triage, diagnostic query writing, mitigation plans, and root cause documentation. CX Codex +1 ★ 1,627repo stars adr-byo-template adr-byo-template defines the contract for bring-your-own ADR templates: how project config resolves and what fields a template must declare for the ADR Creator to accept it. CX Codex +1 ★ 1,627repo stars pptx pptx defines directory structure, YAML schemas, and layout constraints for building PowerPoint slide decks with AI agents. CX Codex +1 ★ 1,627repo stars coaching-patterns The coaching-patterns rule guides planning agents through open-ended discovery before classification or analysis. It helps uncover a system’s context, stakeholders, and potential effects through conversation. CX Codex +1 ★ 1,627repo stars BRD Quality Reviewer BRD Quality Reviewer is a subagent that checks BRD requirements against ISO/IEC/IEEE 29148 and ISO/IEC 25010, producing a structured report and recommendations without modifying files. CX Codex +1 ★ 1,627repo stars

Project sponsors

Companies that keep this analytics open