Terraform 命名规范 #

命名原则 #

良好的命名规范可以提高代码可读性、可维护性和团队协作效率。

text
┌─────────────────────────────────────────────────────────────┐
│                    命名原则                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  一致性      整个项目遵循相同的命名规范                      │
│  描述性      名称应该清晰表达用途                            │
│  简洁性      避免冗长,但不要过度缩写                        │
│  可预测      遵循可预测的命名模式                            │
│                                                             │
└─────────────────────────────────────────────────────────────┘

资源命名 #

基本规范 #

hcl
resource "aws_instance" "web_server" {
  
}

resource "aws_security_group" "web_alb" {
  
}

resource "aws_s3_bucket" "log_storage" {
  
}

命名模式 #

text
<资源类型>_<用途>_<环境>

示例:
aws_instance_web_prod
aws_security_group_alb_staging
aws_s3_bucket_logs_dev

使用名称前缀 #

hcl
locals {
  name_prefix = "${var.project_name}-${var.environment}"
}

resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
  
  tags = {
    Name = "${local.name_prefix}-vpc"
  }
}

resource "aws_subnet" "public" {
  vpc_id     = aws_vpc.main.id
  cidr_block = "10.0.1.0/24"
  
  tags = {
    Name = "${local.name_prefix}-public-subnet"
  }
}

资源类型缩写 #

text
┌─────────────────────────────────────────────────────────────┐
│                    常用缩写                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  vpc     Virtual Private Cloud                             │
│  sg      Security Group                                    │
│  alb     Application Load Balancer                         │
│  nlb     Network Load Balancer                             │
│  asg     Auto Scaling Group                                │
│  rds     Relational Database Service                       │
│  ec2     Elastic Compute Cloud                             │
│  s3      Simple Storage Service                            │
│  iam     Identity and Access Management                    │
│  kms     Key Management Service                            │
│                                                             │
└─────────────────────────────────────────────────────────────┘

变量命名 #

输入变量 #

hcl
variable "vpc_cidr" {
  description = "CIDR block for the VPC"
  type        = string
}

variable "availability_zones" {
  description = "List of availability zones"
  type        = list(string)
}

variable "enable_monitoring" {
  description = "Enable CloudWatch monitoring"
  type        = bool
  default     = false
}

variable "instance_types" {
  description = "Map of instance types by environment"
  type        = map(string)
}

命名规范 #

text
┌─────────────────────────────────────────────────────────────┐
│                    变量命名规范                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  使用 snake_case                                           │
│  ✅ vpc_cidr                                               │
│  ✅ instance_type                                           │
│  ❌ vpcCidr                                                 │
│  ❌ VpcCidr                                                 │
│                                                             │
│  布尔变量使用 enable_ 或 create_ 前缀                       │
│  ✅ enable_monitoring                                       │
│  ✅ create_vpc                                              │
│                                                             │
│  列表变量使用复数形式                                       │
│  ✅ availability_zones                                      │
│  ✅ subnet_ids                                              │
│                                                             │
└─────────────────────────────────────────────────────────────┘

输出命名 #

hcl
output "vpc_id" {
  description = "The ID of the VPC"
  value       = aws_vpc.main.id
}

output "public_subnet_ids" {
  description = "List of public subnet IDs"
  value       = aws_subnet.public[*].id
}

output "alb_dns_name" {
  description = "DNS name of the load balancer"
  value       = aws_lb.main.dns_name
}

output "db_endpoint" {
  description = "Endpoint of the database"
  value       = aws_db_instance.main.endpoint
}

本地值命名 #

hcl
locals {
  name_prefix = "${var.project_name}-${var.environment}"
  
  common_tags = {
    Environment = var.environment
    Project     = var.project_name
    ManagedBy   = "terraform"
  }
  
  vpc_cidr = "10.0.0.0/16"
  
  public_subnet_cidrs = [
    cidrsubnet(local.vpc_cidr, 8, 0),
    cidrsubnet(local.vpc_cidr, 8, 1)
  ]
}

模块命名 #

目录命名 #

text
modules/
├── vpc/
├── security-group/
├── ec2-instance/
├── rds-mysql/
└── s3-bucket/

模块调用 #

hcl
module "vpc" {
  source = "./modules/vpc"
  
  vpc_cidr = var.vpc_cidr
}

module "web_server" {
  source = "./modules/ec2-instance"
  
  instance_type = var.instance_type
}

module "database" {
  source = "./modules/rds-mysql"
  
  instance_class = var.db_instance_class
}

标签命名 #

标签规范 #

hcl
locals {
  common_tags = {
    Name        = "${var.project_name}-${var.environment}-${var.component}"
    Environment = var.environment
    Project     = var.project_name
    Component   = var.component
    ManagedBy   = "terraform"
    Owner       = var.owner
    CreatedAt   = timestamp()
  }
}

resource "aws_instance" "web" {
  ami           = var.ami_id
  instance_type = var.instance_type
  
  tags = merge(local.common_tags, {
    Name = "${var.project_name}-${var.environment}-web-server"
  })
}

常用标签 #

text
┌─────────────────────────────────────────────────────────────┐
│                    常用标签                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  Name         资源名称                                      │
│  Environment  环境标识                                      │
│  Project      项目名称                                      │
│  Component    组件名称                                      │
│  ManagedBy    管理工具                                      │
│  Owner        负责人                                        │
│  CostCenter   成本中心                                      │
│  CreatedAt    创建时间                                      │
│                                                             │
└─────────────────────────────────────────────────────────────┘

文件命名 #

text
┌─────────────────────────────────────────────────────────────┐
│                    文件命名规范                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  使用小写字母和连字符                                       │
│  ✅ main.tf                                                │
│  ✅ variables.tf                                            │
│  ✅ networking.tf                                           │
│  ❌ Main.tf                                                 │
│  ❌ networking_config.tf                                    │
│                                                             │
│  变量文件使用 .tfvars 扩展                                  │
│  ✅ terraform.tfvars                                        │
│  ✅ dev.tfvars                                              │
│  ✅ prod.tfvars                                             │
│                                                             │
└─────────────────────────────────────────────────────────────┘

环境命名 #

hcl
variable "environment" {
  description = "Environment name"
  type        = string
  
  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "Environment must be dev, staging, or prod."
  }
}

命名示例 #

完整示例 #

hcl
locals {
  project_name = "myapp"
  environment  = "prod"
  
  name_prefix = "${local.project_name}-${local.environment}"
  
  common_tags = {
    Name        = local.name_prefix
    Environment = local.environment
    Project     = local.project_name
    ManagedBy   = "terraform"
  }
}

resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
  
  tags = merge(local.common_tags, {
    Name = "${local.name_prefix}-vpc"
  })
}

resource "aws_subnet" "public" {
  count             = 2
  vpc_id            = aws_vpc.main.id
  cidr_block        = cidrsubnet("10.0.0.0/16", 8, count.index)
  availability_zone = data.aws_availability_zones.available.names[count.index]
  
  tags = merge(local.common_tags, {
    Name = "${local.name_prefix}-public-subnet-${count.index + 1}"
    Tier = "public"
  })
}

resource "aws_security_group" "web_alb" {
  name        = "${local.name_prefix}-web-alb-sg"
  description = "Security group for web ALB"
  vpc_id      = aws_vpc.main.id
  
  tags = merge(local.common_tags, {
    Name = "${local.name_prefix}-web-alb-sg"
  })
}

resource "aws_lb" "web" {
  name               = "${local.name_prefix}-web-alb"
  internal           = false
  load_balancer_type = "application"
  security_groups    = [aws_security_group.web_alb.id]
  subnets            = aws_subnet.public[*].id
  
  tags = merge(local.common_tags, {
    Name = "${local.name_prefix}-web-alb"
  })
}

下一步 #

掌握了命名规范后,接下来学习 测试策略,了解如何测试 Terraform 代码!

最后更新:2026-03-29