Skip to content

Terraform 基础

编写 Terraform 配置使用 providers, resources, 变量, and 状态 management.

你将学到

  • Terraform 语法: 块, 实参, and 表达式
  • Providers and resources
  • 变量 and 输出 for reusable configs
  • 状态 management and remote backends

概念讲解

Terraform 语法

Terraform uses HCL (HashiCorp Configuration Language), a declarative language designed for configuration. A Terraform file consists of blocks — resource, provider, 变量, 输出, terraform — each with a type and labels. Inside blocks, arguments assign values to properties. Expressions can reference other resources, use functions, and include conditionals. HCL is designed to be both human-readable and machine-parseable.

Providers and Resources

A provider is a plugin that lets Terraform manage a specific platform — AWS, Azure, Google Cloud, GitHub, Docker. You configure the provider with credentials and region. A resource is a piece of infrastructure — an EC2 instance, an S3 bucket, a DNS record. Each resource has a type (like aws_instance) and a local name. You set its properties with arguments. Resources can reference each other, creating dependencies that Terraform resolves automatically.

Variables and Outputs

Variables make configurations reusable. Define a variable with a type, default, and description, then reference it as var.name. You can override defaults via command-line flags, environment variables, or .tfvars files. Outputs expose values after the apply — the IP address of a created instance, the URL of a load balancer. Outputs are useful for passing infrastructure details to other tools or for inspection. Use locals for intermediate calculations within a configuration.

State Management

Terraform state is a JSON file that maps your configuration to real-world resources. It tracks what Terraform has created so it knows what to update or delete. Never edit state manually. Store state in a remote backend — an S3 bucket with DynamoDB locking, Terraform Cloud, or Azure Blob Storage. Remote state enables team collaboration (locking prevents concurrent applies), keeps state secure, and survives local machine failures. Use terraform 导入 to bring existing resources under Terraform management.

Terraform Modules

Modules are reusable Terraform configurations — like functions for infrastructure. A module encapsulates a set of resources with input variables and outputs. You can use modules from the Terraform Registry or write your own. Modules promote consistency and reduce duplication: instead of copying the same VPC configuration into every project, you define it once as a module and reuse it. Keep modules focused and well-documented. Version your modules so consumers can pin a specific version and upgrade deliberately rather than getting unexpected changes.

示例代码

              # variables.tf — reusable input variables
# variable "region" {
#   default = "us-east-1"
#   type    = string
# }
# variable "instance_count" {
#   default = 2
#   type    = number
# }

# main.tf — the infrastructure
# resource "aws_instance" "web" {
#   count         = var.instance_count
#   ami           = "ami-0c02fb559f6fe2234"
#   instance_type = "t3.micro"
#   tags = { Name = "web-${count.index}" }
# }
# output "instance_ips" {
#   value = aws_instance.web[*].public_ip
# }

# Workflow
terraform init && terraform validate      # init and check syntax
terraform plan -var="instance_count=3"    # preview with override
terraform apply                           # create the resources
terraform output instance_ips             # show the outputs
            

变量制作 configs reusable, 输出 expose 创建 resource attributes. workflow 是: init (设置), 验证 (检查), 计划 (preview), apply (创建), 输出 (读取 results).

动手试一试

常见错误

错误写法

存储 Terraform 状态 in git

正确做法

存储状态 in remote backend 使用 locking (S3 + DynamoDB). 状态 files 能包含 secrets and 是不 设计 for version control. Git-based 状态 causes conflicts and 数据 loss.

错误写法

不运行 terraform 计划之前 apply

正确做法

总是 review 计划输出之前 applying. 计划 shows 精确地什么将 是创建, 更改, or destroyed. Applying 不使用 reviewing risks unintended destruction 的 resources.

练习 Terraform 基础

2 个练习

练习 Terraform 基础

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误