terraform-style-check
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTerraform Style Guide
Terraform 风格指南
Generate and maintain Terraform code following HashiCorp's official style conventions and best practices.
Reference: HashiCorp Terraform Style Guide
遵循HashiCorp官方风格规范和最佳实践来生成和维护Terraform代码。
参考文档: HashiCorp Terraform 风格指南
Code Generation Strategy
代码生成策略
When generating Terraform code:
- Start with provider configuration and version constraints
- Create data sources before dependent resources
- Build resources in dependency order
- Add outputs for key resource attributes
- Use variables for all configurable values
生成Terraform代码时:
- 从Provider配置和版本约束开始
- 在依赖资源之前创建数据源
- 按依赖顺序构建资源
- 为关键资源属性添加输出
- 所有可配置值使用变量
File Organization
文件组织
| File | Purpose |
|---|---|
| Terraform and provider version requirements |
| Provider configurations |
| Primary resources and data sources |
| Input variable declarations (alphabetical) |
| Output value declarations (alphabetical) |
| Local value declarations |
| 文件 | 用途 |
|---|---|
| Terraform及Provider版本要求 |
| Provider配置 |
| 主要资源和数据源 |
| 输入变量声明(按字母顺序) |
| 输出值声明(按字母顺序) |
| 本地值声明 |
Example Structure
示例结构
hcl
undefinedhcl
undefinedterraform.tf
terraform.tf
terraform {
required_version = ">= 1.7"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
terraform {
required_version = ">= 1.7"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
variables.tf
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."
}
}
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.tf
locals {
common_tags = {
Environment = var.environment
ManagedBy = "Terraform"
}
}
locals {
common_tags = {
Environment = var.environment
ManagedBy = "Terraform"
}
}
main.tf
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"
})
}
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
outputs.tf
output "vpc_id" {
description = "ID of the created VPC"
value = aws_vpc.main.id
}
undefinedoutput "vpc_id" {
description = "ID of the created VPC"
value = aws_vpc.main.id
}
undefinedCode Formatting
代码格式规范
Indentation and Alignment
缩进与对齐
- Use two spaces per nesting level (no tabs)
- Align equals signs for consecutive arguments
hcl
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
subnet_id = "subnet-12345678"
tags = {
Name = "web-server"
Environment = "production"
}
}- 每个嵌套层级使用两个空格(不使用制表符)
- 连续参数的等号对齐
hcl
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:
hcl
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
}
}参数在块之前,元参数优先:
hcl
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
hcl
undefined- 所有名称使用小写加下划线格式
- 使用描述性名词,不包含资源类型
- 名称需具体且有意义
hcl
undefinedBad
Bad
resource "aws_instance" "webAPI-aws-instance" {}
variable "name" {}
resource "aws_instance" "webAPI-aws-instance" {}
variable "name" {}
Good
Good
resource "aws_instance" "web_api" {}
variable "application_name" {}
undefinedresource "aws_instance" "web_api" {}
variable "application_name" {}
undefinedVariables
变量
Every variable must include and :
typedescriptionhcl
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
}每个变量必须包含和:
typedescriptionhcl
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 :
descriptionhcl
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
}每个输出必须包含:
descriptionhcl
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
优先使用for_each而非count
hcl
undefinedhcl
undefinedBad - count for multiple resources
Bad - count for multiple resources
resource "aws_instance" "web" {
count = var.instance_count
tags = { Name = "web-${count.index}" }
}
resource "aws_instance" "web" {
count = var.instance_count
tags = { Name = "web-${count.index}" }
}
Good - for_each with named instances
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 }
}
undefinedvariable "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 }
}
undefinedcount for Conditional Creation
使用count实现条件创建
hcl
resource "aws_cloudwatch_metric_alarm" "cpu" {
count = var.enable_monitoring ? 1 : 0
alarm_name = "high-cpu-usage"
threshold = 80
}hcl
resource "aws_cloudwatch_metric_alarm" "cpu" {
count = var.enable_monitoring ? 1 : 0
alarm_name = "high-cpu-usage"
threshold = 80
}Security Best Practices
安全最佳实践
When generating code, apply security hardening:
- Enable encryption at rest by default
- Configure private networking where applicable
- Apply principle of least privilege for security groups
- Enable logging and monitoring
- Never hardcode credentials or secrets
- Mark sensitive outputs with
sensitive = true
生成代码时,应用安全加固措施:
- 默认启用静态加密
- 适用时配置私有网络
- 为安全组应用最小权限原则
- 启用日志与监控
- 切勿硬编码凭证或密钥
- 敏感输出标记为
sensitive = true
Example: Secure S3 Bucket
示例:安全的S3存储桶
hcl
resource "aws_s3_bucket" "data" {
bucket = "${var.project}-${var.environment}-data"
tags = local.common_tags
}
resource "aws_s3_bucket_versioning" "data" {
bucket = aws_s3_bucket.data.id
versioning_configuration {
status = "Enabled"
}
}
resource "aws_s3_bucket_server_side_encryption_configuration" "data" {
bucket = aws_s3_bucket.data.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "aws:kms"
kms_master_key_id = aws_kms_key.s3.arn
}
}
}
resource "aws_s3_bucket_public_access_block" "data" {
bucket = aws_s3_bucket.data.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}hcl
resource "aws_s3_bucket" "data" {
bucket = "${var.project}-${var.environment}-data"
tags = local.common_tags
}
resource "aws_s3_bucket_versioning" "data" {
bucket = aws_s3_bucket.data.id
versioning_configuration {
status = "Enabled"
}
}
resource "aws_s3_bucket_server_side_encryption_configuration" "data" {
bucket = aws_s3_bucket.data.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "aws:kms"
kms_master_key_id = aws_kms_key.s3.arn
}
}
}
resource "aws_s3_bucket_public_access_block" "data" {
bucket = aws_s3_bucket.data.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}Version Pinning
版本固定
hcl
terraform {
required_version = ">= 1.7"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0" # Allow minor updates
}
}
}Version constraint operators:
- - Exact version
= 1.0.0 - - Greater than or equal
>= 1.0.0 - - Allow rightmost component to increment
~> 1.0 - - Version range
>= 1.0, < 2.0
hcl
terraform {
required_version = ">= 1.7"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0" # Allow minor updates
}
}
}版本约束运算符:
- - 精确版本
= 1.0.0 - - 大于等于指定版本
>= 1.0.0 - - 允许最右侧版本号递增
~> 1.0 - - 版本范围
>= 1.0, < 2.0
Provider Configuration
Provider配置
hcl
provider "aws" {
region = "us-west-2"
default_tags {
tags = {
ManagedBy = "Terraform"
Project = var.project_name
}
}
}hcl
provider "aws" {
region = "us-west-2"
default_tags {
tags = {
ManagedBy = "Terraform"
Project = var.project_name
}
}
}Aliased provider for multi-region
Aliased provider for multi-region
provider "aws" {
alias = "east"
region = "us-east-1"
}
undefinedprovider "aws" {
alias = "east"
region = "us-east-1"
}
undefinedVersion Control
版本控制
Never commit:
- ,
terraform.tfstateterraform.tfstate.backup - directory
.terraform/ *.tfplan- files with sensitive data
.tfvars
Always commit:
- All configuration files
.tf - (dependency lock file)
.terraform.lock.hcl
切勿提交:
- ,
terraform.tfstateterraform.tfstate.backup - 目录
.terraform/ *.tfplan- 包含敏感数据的文件
.tfvars
务必提交:
- 所有配置文件
.tf - (依赖锁定文件)
.terraform.lock.hcl
Validation Tools
验证工具
Run before committing:
bash
terraform fmt -recursive
terraform validateAdditional tools:
- - Linting and best practices
tflint - /
checkov- Security scanningtfsec
提交前运行:
bash
terraform fmt -recursive
terraform validate其他工具:
- - 代码检查与最佳实践验证
tflint - /
checkov- 安全扫描tfsec
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
- 代码已使用格式化
terraform fmt - 配置已通过验证
terraform validate - 文件按标准结构组织
- 所有变量均包含类型与描述
- 所有输出均包含描述
- 资源名称使用带下划线的描述性名词
- 版本约束已明确固定
- 敏感值已标记为
sensitive = true - 无硬编码凭证或密钥
- 已应用安全最佳实践