terraform

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Terraform Expert Engineer Skill

Terraform专家工程师技能

This skill provides a comprehensive guide for Terraform development.
本技能为Terraform开发提供了综合指南。

1. Terraform CLI Basic Commands

1. Terraform CLI基础命令

1.1. Initialization and Planning

1.1. 初始化与规划

sh
undefined
sh
undefined

Initialize workspace (download providers)

Initialize workspace (download providers)

terraform init
terraform init

Initialize with backend config

Initialize with backend config

terraform init -backend-config="bucket=my-terraform-state"
terraform init -backend-config="bucket=my-terraform-state"

Check execution plan

Check execution plan

terraform plan
terraform plan

Save execution plan to file

Save execution plan to file

terraform plan -out=tfplan
terraform plan -out=tfplan

Plan specific resource only

Plan specific resource only

terraform plan -target=aws_instance.example
undefined
terraform plan -target=aws_instance.example
undefined

1.2. Apply and Destroy

1.2. 应用与销毁

WARNING: These commands modify infrastructure. Always run
terraform plan
first and ask user permission.
sh
undefined
警告:这些命令会修改基础设施。请始终先执行
terraform plan
并获得用户许可。
sh
undefined

Apply changes

Apply changes

terraform apply
terraform apply

Apply saved plan

Apply saved plan

terraform apply tfplan
terraform apply tfplan

Auto-approve apply (for CI/CD)

Auto-approve apply (for CI/CD)

terraform apply -auto-approve
terraform apply -auto-approve

Destroy resources

Destroy resources

terraform destroy
terraform destroy

Destroy specific resource only

Destroy specific resource only

terraform destroy -target=aws_instance.example
undefined
terraform destroy -target=aws_instance.example
undefined

1.3. State Management

1.3. 状态管理

sh
undefined
sh
undefined

Check state

Check state

terraform state list
terraform state list

Show resource details

Show resource details

terraform state show aws_instance.example
terraform state show aws_instance.example

Move resource (for refactoring)

Move resource (for refactoring)

terraform state mv aws_instance.old aws_instance.new
terraform state mv aws_instance.old aws_instance.new

Import existing resource

Import existing resource

terraform import aws_instance.example i-1234567890abcdef0
terraform import aws_instance.example i-1234567890abcdef0

Remove resource from state (keeps actual resource)

Remove resource from state (keeps actual resource)

terraform state rm aws_instance.example
undefined
terraform state rm aws_instance.example
undefined

1.4. Other Useful Commands

1.4. 其他实用命令

sh
undefined
sh
undefined

Validate configuration

Validate configuration

terraform validate
terraform validate

Format

Format

terraform fmt
terraform fmt

Format recursively

Format recursively

terraform fmt -recursive
terraform fmt -recursive

Check outputs

Check outputs

terraform output
terraform output

Output in JSON format

Output in JSON format

terraform output -json
terraform output -json

Interactive console (for testing expressions)

Interactive console (for testing expressions)

terraform console
terraform console

Lock providers

Lock providers

terraform providers lock -platform=linux_amd64 -platform=darwin_amd64
undefined
terraform providers lock -platform=linux_amd64 -platform=darwin_amd64
undefined

2. Resource Management

2. 资源管理

2.1. Basic Resource Block Structure

2.1. 基础资源块结构

hcl
resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  tags = {
    Name = "example-instance"
  }
}
hcl
resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  tags = {
    Name = "example-instance"
  }
}

2.2. Meta-arguments

2.2. 元参数

  • depends_on
    : Explicit dependencies
  • count
    : Resource replication (index-based)
  • for_each
    : Resource replication (key-based)
  • provider
    : Specify alternate provider
  • lifecycle
    : Lifecycle control
  • depends_on
    :显式依赖
  • count
    :资源复制(基于索引)
  • for_each
    :资源复制(基于键)
  • provider
    :指定备用提供商
  • lifecycle
    :生命周期控制

2.3. Lifecycle Settings

2.3. 生命周期设置

hcl
resource "aws_instance" "example" {
  # ...

  lifecycle {
    create_before_destroy = true  # Create new first on replacement
    prevent_destroy       = true  # Prevent deletion
    ignore_changes        = [tags] # Attributes to ignore changes
    replace_triggered_by  = [null_resource.trigger.id]
  }
}
hcl
resource "aws_instance" "example" {
  # ...

  lifecycle {
    create_before_destroy = true  # Create new first on replacement
    prevent_destroy       = true  # Prevent deletion
    ignore_changes        = [tags] # Attributes to ignore changes
    replace_triggered_by  = [null_resource.trigger.id]
  }
}

3. Module Design

3. 模块设计

3.1. Module Invocation

3.1. 模块调用

hcl
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "5.0.0"

  name = "my-vpc"
  cidr = "10.0.0.0/16"
}
hcl
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "5.0.0"

  name = "my-vpc"
  cidr = "10.0.0.0/16"
}

3.2. Module Source Types

3.2. 模块源类型

  • Local path:
    ./modules/vpc
  • Terraform Registry:
    hashicorp/consul/aws
  • GitHub:
    github.com/hashicorp/example
  • S3:
    s3::https://s3-eu-west-1.amazonaws.com/bucket/module.zip
  • 本地路径:
    ./modules/vpc
  • Terraform Registry:
    hashicorp/consul/aws
  • GitHub:
    github.com/hashicorp/example
  • S3:
    s3::https://s3-eu-west-1.amazonaws.com/bucket/module.zip

3.3. Module Best Practices

3.3. 模块最佳实践

  • Standard file structure:
    main.tf
    ,
    variables.tf
    ,
    outputs.tf
  • Document with README.md
  • Set meaningful default values
  • Validate inputs with validation blocks
  • 标准文件结构:
    main.tf
    variables.tf
    outputs.tf
  • 使用README.md编写文档
  • 设置有意义的默认值
  • 使用验证块验证输入

4. State Management

4. 状态管理

4.1. Remote Backend Configuration

4.1. 远程后端配置

hcl
terraform {
  backend "s3" {
    bucket         = "my-terraform-state"
    key            = "prod/terraform.tfstate"
    region         = "ap-northeast-1"
    encrypt        = true
    dynamodb_table = "terraform-locks"
  }
}
hcl
terraform {
  backend "s3" {
    bucket         = "my-terraform-state"
    key            = "prod/terraform.tfstate"
    region         = "ap-northeast-1"
    encrypt        = true
    dynamodb_table = "terraform-locks"
  }
}

4.2. State Management Best Practices

4.2. 状态管理最佳实践

  • Use remote backend (required for team development)
  • Enable state locking (prevent concurrent execution)
  • Enable encryption
  • Do not directly edit state file (use
    terraform state
    commands)
  • Separate state files per environment
  • 使用远程后端(团队开发必需)
  • 启用状态锁定(防止并发执行)
  • 启用加密
  • 不要直接编辑状态文件(使用
    terraform state
    命令)
  • 按环境分离状态文件

5. Variables and Outputs

5. 变量与输出

5.1. Input Variables

5.1. 输入变量

hcl
variable "instance_type" {
  type        = string
  description = "EC2 instance type"
  default     = "t2.micro"

  validation {
    condition     = contains(["t2.micro", "t2.small", "t2.medium"], var.instance_type)
    error_message = "Please specify an allowed instance type"
  }
}
hcl
variable "instance_type" {
  type        = string
  description = "EC2 instance type"
  default     = "t2.micro"

  validation {
    condition     = contains(["t2.micro", "t2.small", "t2.medium"], var.instance_type)
    error_message = "Please specify an allowed instance type"
  }
}

5.2. Variable Setting Methods (Priority Order)

5.2. 变量设置方式(优先级顺序)

  1. Command line
    -var
    ,
    -var-file
  2. *.auto.tfvars
    files
  3. terraform.tfvars.json
  4. terraform.tfvars
  5. Environment variables
    TF_VAR_*
  6. Default values
  1. 命令行
    -var
    -var-file
  2. *.auto.tfvars
    文件
  3. terraform.tfvars.json
  4. terraform.tfvars
  5. 环境变量
    TF_VAR_*
  6. 默认值

5.3. Sensitive Data Handling

5.3. 敏感数据处理

hcl
variable "db_password" {
  type      = string
  sensitive = true  # Mask in output
}

output "connection_string" {
  value     = "postgres://user:${var.db_password}@host/db"
  sensitive = true  # Output contains sensitive data
}
Note: Sensitive data is stored in plaintext in state files. Remote backend encryption or HCP Terraform recommended.
hcl
variable "db_password" {
  type      = string
  sensitive = true  # Mask in output
}

output "connection_string" {
  value     = "postgres://user:${var.db_password}@host/db"
  sensitive = true  # Output contains sensitive data
}
注意:敏感数据会以明文形式存储在状态文件中。建议使用远程后端加密或HCP Terraform。

6. Providers

6. 提供商

6.1. Provider Declaration

6.1. 提供商声明

hcl
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "ap-northeast-1"
}
hcl
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "ap-northeast-1"
}

6.2. Multiple Providers

6.2. 多提供商

hcl
provider "aws" {
  alias  = "us_east"
  region = "us-east-1"
}

provider "aws" {
  alias  = "ap_northeast"
  region = "ap-northeast-1"
}

resource "aws_instance" "us" {
  provider = aws.us_east
  # ...
}
hcl
provider "aws" {
  alias  = "us_east"
  region = "us-east-1"
}

provider "aws" {
  alias  = "ap_northeast"
  region = "ap-northeast-1"
}

resource "aws_instance" "us" {
  provider = aws.us_east
  # ...
}

7. Built-in Functions

7. 内置函数

7.1. Common Functions

7.1. 常用函数

hcl
undefined
hcl
undefined

String operations

String operations

join("-", ["foo", "bar"]) # "foo-bar" split(",", "a,b,c") # ["a", "b", "c"] format("Hello, %s!", "World") # "Hello, World!"
join("-", ["foo", "bar"]) # "foo-bar" split(",", "a,b,c") # ["a", "b", "c"] format("Hello, %s!", "World") # "Hello, World!"

Collection operations

Collection operations

length(["a", "b", "c"]) # 3 lookup(map, key, default) # Get value from map merge(map1, map2) # Merge maps flatten([["a"], ["b", "c"]]) # ["a", "b", "c"]
length(["a", "b", "c"]) # 3 lookup(map, key, default) # Get value from map merge(map1, map2) # Merge maps flatten([["a"], ["b", "c"]]) # ["a", "b", "c"]

Type conversions

Type conversions

tostring(123) # "123" tolist(set) # Set to list tomap(object) # Object to map
tostring(123) # "123" tolist(set) # Set to list tomap(object) # Object to map

Conditional expressions

Conditional expressions

coalesce("", "default") # "default" (first non-empty value) try(expression, fallback) # Fallback on error
undefined
coalesce("", "default") # "default" (first non-empty value) try(expression, fallback) # Fallback on error
undefined

8. HCP Terraform / Terraform Cloud

8. HCP Terraform / Terraform Cloud

8.1. Key Features

8.1. 核心功能

  • Remote state management (encryption, versioning)
  • Team collaboration
  • Policy enforcement (Sentinel)
  • Private module registry
  • VCS integration (GitHub, GitLab, etc.)
  • Cost estimation
  • 远程状态管理(加密、版本控制)
  • 团队协作
  • 策略强制执行(Sentinel)
  • 私有模块注册表
  • VCS集成(GitHub、GitLab等)
  • 成本估算

8.2. Workspace Configuration

8.2. 工作区配置

hcl
terraform {
  cloud {
    organization = "my-org"

    workspaces {
      name = "my-workspace"
    }
  }
}
hcl
terraform {
  cloud {
    organization = "my-org"

    workspaces {
      name = "my-workspace"
    }
  }
}

9. Security Best Practices

9. 安全最佳实践

9.1. Credential Management

9.1. 凭证管理

  • Do not hardcode
  • Use environment variables or auth files
  • IAM roles / service accounts recommended
  • HashiCorp Vault integration
  • 不要硬编码凭证
  • 使用环境变量或认证文件
  • 推荐使用IAM角色/服务账户
  • HashiCorp Vault集成

9.2. State File Security

9.2. 状态文件安全

  • Use encrypted backend
  • Set appropriate access controls
  • Add
    .terraform/
    to
    .gitignore
  • Add
    *.tfvars
    to
    .gitignore
    (if contains sensitive info)
  • 使用加密后端
  • 设置适当的访问控制
  • .terraform/
    添加到
    .gitignore
  • 如果包含敏感信息,将
    *.tfvars
    添加到
    .gitignore

10. Reference Links

10. 参考链接