terraform-style-guide

โดย hashicorp

สร้างและบำรุงรักษาโค้ด Terraform ตามรูปแบบมาตรฐานทางการของ HashiCorp บังคับใช้การเยื้องสองช่องว่าง การตั้งชื่อด้วยตัวพิมพ์เล็กและขีดล่าง และการจัดระเบียบไฟล์มาตรฐานใน terraform.tf, providers.tf, main.tf, variables.tf, outputs.tf และ locals.tf กำหนดให้มี type และ description ในตัวแปรและเอาต์พุตทั้งหมด พร้อมกฎการตรวจสอบและการสนับสนุนแฟล็ก sensitive สำหรับข้อมูลรับรอง ให้ความสำคัญกับ 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

Skills เพิ่มเติมจาก hashicorp

provider-actions
hashicorp
Implement การทำงานของ Terraform Provider โดยใช้ Plugin Framework ใช้เมื่อพัฒนาการดำเนินการแบบ imperative ที่ทำงานในเหตุการณ์ lifecycle (ก่อน/หลัง…
official
new-terraform-provider
hashicorp
ใช้สิ่งนี้เมื่อสร้าง Terraform provider ใหม่ด้วย Plugin Framework: โครงสร้าง workspace, การตั้งค่า go module, provider server main.go และ provider.go…
official
terraform-test
hashicorp
คู่มือที่ครอบคลุมสำหรับการเขียนและรันการทดสอบ Terraform ใช้เมื่อสร้างไฟล์ทดสอบ (.tftest.hcl) เขียนสถานการณ์ทดสอบด้วย run blocks ตรวจสอบความถูกต้อง…
official
terraform-test
hashicorp
คู่มือที่ครอบคลุมสำหรับการเขียนและรันการทดสอบ Terraform พร้อมการยืนยันผล การจำลอง และการตรวจสอบโมดูล เขียนไฟล์ทดสอบโดยใช้ไวยากรณ์ .tftest.hcl พร้อมบล็อก run ที่ทำงานในโหมด plan หรือ apply รองรับการทำงานแบบลำดับและแบบขนานพร้อมการแยกสถานะที่เป็นทางเลือก ยืนยันเงื่อนไขบนแอตทริบิวต์ของทรัพยากร เอาต์พุต และแหล่งข้อมูล ใช้ expect_failures เพื่อตรวจสอบว่าอินพุตที่ไม่ถูกต้องถูกปฏิเสธอย่างเหมาะสม จำลองผู้ให้บริการ (Terraform 1.7.0+) เพื่อจำลองพฤติกรรมของโครงสร้างพื้นฐานโดยไม่ต้อง...
official
provider-actions
hashicorp
ใช้การดำเนินการของ Terraform Provider แบบ Imperative ในเหตุการณ์วงจรชีวิตของทรัพยากรโดยใช้ Plugin Framework รองรับทริกเกอร์วงจรชีวิตก่อน/หลังการสร้างและก่อน/หลังการอัปเดต (เหตุการณ์การทำลายไม่พร้อมใช้งานใน Terraform 1.14.0) ต้องมีการกำหนดสคีมาที่ถูกต้องพร้อมประเภทเฟรมเวิร์กที่เหมาะสม ElementType สำหรับคอลเล็กชัน และตัวตรวจสอบสำหรับการตรวจสอบอินพุต รวมถึงการรายงานความคืบหน้า การจัดการหมดเวลา และการจัดการข้อผิดพลาดที่ครอบคลุมสำหรับการดำเนินการที่ใช้เวลานาน รองรับการโพลและ...
official
aws-ami-builder
hashicorp
สร้าง Amazon Machine Images แบบกำหนดเองด้วย builder amazon-ebs ของ Packer อัตโนมัติการสร้าง AMI จาก AMI ต้นทางโดยใช้เทมเพลต HCL พร้อม provisioners สำหรับการปรับแต่ง (สคริปต์เชลล์, อัปโหลดไฟล์, การจัดการการกำหนดค่า) รองรับการกระจาย AMI หลายภูมิภาคผ่าน ami_regions และการกรอง AMI ต้นทางแบบยืดหยุ่นตามชื่อ, เจ้าของ, และประเภทการจำลองเสมือน ยืนยันตัวตนผ่านตัวแปรสภาพแวดล้อม, ไฟล์ข้อมูลรับรอง AWS, หรือโปรไฟล์อินสแตนซ์ IAM; รวมคำสั่งตรวจสอบและสร้างสำหรับเทมเพลต...
official
new-terraform-provider
hashicorp
สร้างโครงร่างผู้ให้บริการ Terraform ใหม่โดยใช้ Plugin Framework สร้างพื้นที่ทำงานโมดูล Go ใหม่ตามรูปแบบการตั้งชื่อมาตรฐาน "terraform-provider-" และเริ่มต้นการพึ่งพาที่จำเป็น ให้ไฟล์ main.go ต้นแบบตามรูปแบบ Plugin Framework ของ HashiCorp พร้อมเครื่องหมาย TODO สำหรับการปรับแต่ง ตรวจสอบการตั้งค่าโดยรันคำสั่ง build และ test เพื่อให้แน่ใจว่าผู้ให้บริการคอมไพล์และผ่านการตรวจสอบเบื้องต้น จัดการพื้นที่ทำงานโดยยืนยันความตั้งใจก่อนสร้างใหม่...
official
azure-verified-modules
hashicorp
ข้อกำหนดการรับรองและแนวปฏิบัติที่ดีที่สุดสำหรับโมดูล Azure Terraform ที่ต้องการความสอดคล้องกับ AVM บังคับใช้ข้อจำกัดเวอร์ชันของ provider (azurerm >= 4.0, < 5.0; azapi >= 2.0, < 3.0) และห้ามการอ้างอิงโมดูลแบบ git โดยกำหนดให้ใช้แหล่งที่มาจาก Terraform registry ที่ถูกตรึงไว้ กำหนดให้ใช้ snake_casing ตัวพิมพ์เล็กสำหรับ identifiers ทั้งหมด ชนิดตัวแปรที่แม่นยำ แอตทริบิวต์เอาต์พุตแบบแยกส่วนผ่านรูปแบบ anti-corruption layer และ locals ที่เรียงตามลำดับตัวอักษร กำหนดให้มีตัวแปรสลับฟีเจอร์สำหรับทรัพยากรใหม่ที่ถูกเพิ่ม...
official