terraform-style-guide

作者: hashicorp

遵循HashiCorp官方风格约定生成和维护Terraform代码。强制使用双空格缩进、小写下划线命名,并按terraform.tf、providers.tf、main.tf、variables.tf、outputs.tf和locals.tf标准组织文件。要求所有变量和输出包含类型和描述,支持验证规则和敏感标记用于凭证。动态资源优先使用for_each而非count,应用安全加固(加密、私有...)

npx skills add https://github.com/hashicorp/agent-skills --skill terraform-style-guide

Terraform Style Guide

Generate and maintain Terraform code following HashiCorp's official style conventions and best practices.

Reference: HashiCorp Terraform Style Guide

Code Generation Strategy

When generating Terraform code:

  1. Start with provider configuration and version constraints
  2. Create data sources before dependent resources
  3. Build resources in dependency order
  4. Add outputs for key resource attributes
  5. Use variables for all configurable values

File Organization

FilePurpose
terraform.tfTerraform and provider version requirements
providers.tfProvider configurations
main.tfPrimary resources and data sources
variables.tfInput variable declarations (alphabetical)
outputs.tfOutput value declarations (alphabetical)
locals.tfLocal value declarations

Example Structure

# terraform.tf
terraform {
  required_version = ">= 1.14"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}

# variables.tf
variable "environment" {
  description = "Target deployment environment"
  type        = string

  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "Environment must be dev, staging, or prod."
  }
}

# locals.tf
locals {
  common_tags = {
    Environment = var.environment
    ManagedBy   = "Terraform"
  }
}

# main.tf
resource "aws_vpc" "main" {
  cidr_block           = var.vpc_cidr
  enable_dns_hostnames = true

  tags = merge(local.common_tags, {
    Name = "${var.project_name}-${var.environment}-vpc"
  })
}

# outputs.tf
output "vpc_id" {
  description = "ID of the created VPC"
  value       = aws_vpc.main.id
}

Code Formatting

Indentation and Alignment

  • Use two spaces per nesting level (no tabs)
  • Align equals signs for consecutive arguments
resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  subnet_id     = "subnet-12345678"

  tags = {
    Name        = "web-server"
    Environment = "production"
  }
}

Block Organization

Arguments precede blocks, with meta-arguments first:

resource "aws_instance" "example" {
  # Meta-arguments
  count = 3

  # Arguments
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  # Blocks
  root_block_device {
    volume_size = 20
  }

  # Lifecycle last
  lifecycle {
    create_before_destroy = true
  }
}

Naming Conventions

  • Use lowercase with underscores for all names
  • Use descriptive nouns excluding the resource type
  • Be specific and meaningful
  • Resource names must be singular, not plural
  • Default to main for resources where a specific descriptive name is redundant or unavailable, provided only one instance exists
# Bad
resource "aws_instance" "webAPI-aws-instance" {}
resource "aws_instance" "web_apis" {}
variable "name" {}

# Good
resource "aws_instance" "web_api" {}
resource "aws_vpc" "main" {}
variable "application_name" {}

Variables

Every variable must include type and description:

variable "instance_type" {
  description = "EC2 instance type for the web server"
  type        = string
  default     = "t2.micro"

  validation {
    condition     = contains(["t2.micro", "t2.small", "t2.medium"], var.instance_type)
    error_message = "Instance type must be t2.micro, t2.small, or t2.medium."
  }
}

variable "database_password" {
  description = "Password for the database admin user"
  type        = string
  sensitive   = true
}

Outputs

Every output must include description:

output "instance_id" {
  description = "ID of the EC2 instance"
  value       = aws_instance.web.id
}

output "database_password" {
  description = "Database administrator password"
  value       = aws_db_instance.main.password
  sensitive   = true
}

Dynamic Resource Creation

Prefer for_each over count

# Bad - count for multiple resources
resource "aws_instance" "web" {
  count = var.instance_count
  tags  = { Name = "web-${count.index}" }
}

# Good - for_each with named instances
variable "instance_names" {
  type    = set(string)
  default = ["web-1", "web-2", "web-3"]
}

resource "aws_instance" "web" {
  for_each = var.instance_names
  tags     = { Name = each.key }
}

count for Conditional Creation

resource "aws_cloudwatch_metric_alarm" "cpu" {
  count = var.enable_monitoring ? 1 : 0

  alarm_name = "high-cpu-usage"
  threshold  = 80
}

Security Best Practices

Refer to SECURITY.md. It includes guidance on encrypting resources, preventing sensitive data in state, and secure configurations.

Version Pinning

terraform {
  required_version = ">= 1.14"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}

Use the latest major version of each provider and the latest minor version of Terraform, unless otherwise constrained by a dependency lock file or by other modules used by the configuration.

Version constraint operators:

  • = 1.0.0 - Exact version
  • >= 1.0.0 - Greater than or equal
  • ~> 1.0 - Allow rightmost component to increment
  • >= 1.0, < 2.0 - Version range

Provider Configuration

provider "aws" {
  region = "us-west-2"

  default_tags {
    tags = {
      ManagedBy = "Terraform"
      Project   = var.project_name
    }
  }
}

# Aliased provider for multi-region
provider "aws" {
  alias  = "east"
  region = "us-east-1"
}

Version Control

Never commit:

  • terraform.tfstate, terraform.tfstate.backup
  • .terraform/ directory
  • *.tfplan
  • .tfvars files with sensitive data

Always commit:

  • All .tf configuration files
  • .terraform.lock.hcl (dependency lock file)

Validation Tools

Run before committing:

terraform fmt -recursive
terraform validate

Additional tools:

  • tflint - Linting and best practices
  • checkov / tfsec - Security scanning

Code Review Checklist

  • Code formatted with terraform fmt
  • Configuration validated with terraform validate
  • Files organized according to standard structure
  • All variables have type and description
  • All outputs have descriptions
  • Resource names use descriptive nouns with underscores
  • Version constraints pinned explicitly
  • Sensitive values marked with sensitive = true
  • No hardcoded credentials or secrets
  • Security best practices applied

Based on: HashiCorp Terraform Style Guide

来自 hashicorp 的更多技能

provider-actions
hashicorp
使用Plugin Framework实现Terraform Provider操作。在开发于生命周期事件(之前/之后…)执行的命令式操作时使用。
official
new-terraform-provider
hashicorp
在使用 Plugin Framework 搭建新的 Terraform provider 时使用:工作区布局、go module 设置、provider server 的 main.go 和 provider.go…
official
terraform-test
hashicorp
编写和运行Terraform测试的综合指南。在创建测试文件(.tftest.hcl)、使用run块编写测试场景、验证……时使用。
official
terraform-test
hashicorp
关于使用断言、模拟和模块验证编写及运行Terraform测试的全面指南。使用.tftest.hcl语法编写测试文件,通过运行块在计划或应用模式下执行,支持顺序和并行执行,并可选择状态隔离。对资源属性、输出和数据源进行断言条件验证;使用expect_failures确保无效输入被正确拒绝。模拟提供程序(Terraform 1.7.0+)可模拟基础设施行为,无需...
official
provider-actions
hashicorp
使用Plugin Framework在资源生命周期事件中实现命令式Terraform Provider操作。支持创建前/后和更新前/后的生命周期触发器(Terraform 1.14.0中不支持销毁事件)。需要正确的模式定义,包括框架类型、集合的ElementType以及输入验证的验证器。包含进度报告、超时管理和长时间运行操作的全面错误处理。实现轮询和...
official
aws-ami-builder
hashicorp
使用Packer的amazon-ebs构建器创建自定义Amazon Machine Images。通过HCL模板自动化从源AMI创建AMI的过程,并利用配置器(shell脚本、文件上传、配置管理)进行自定义。支持通过ami_regions实现多区域AMI分发,以及按名称、所有者和虚拟化类型灵活过滤源AMI。通过环境变量、AWS凭证文件或IAM实例配置文件进行身份验证;包含模板的验证和构建命令...
official
new-terraform-provider
hashicorp
使用Plugin Framework搭建一个新的Terraform provider。生成一个采用标准"terraform-provider-"命名约定的新Go模块工作区,并初始化所需依赖。提供一个遵循HashiCorp Plugin Framework模式的模板main.go文件,其中包含用于自定义的TODO标记。通过运行构建和测试命令来验证设置,确保provider能够编译并通过初始检查。通过创建新工作区前确认意图来处理工作区管理。
official
azure-verified-modules
hashicorp
针对寻求AVM合规的Azure Terraform模块的认证要求与最佳实践。强制要求提供者版本约束(azurerm >= 4.0, < 5.0;azapi >= 2.0, < 3.0),禁止使用基于Git的模块引用,转而采用固定的Terraform注册表源。所有标识符必须使用小写下划线命名法,变量类型需精确指定,通过防腐层模式实现离散输出属性,本地变量需按字母顺序排列。新增资源需配置功能开关变量...
official