Skip to content

Terraform 速查表

基础设施即代码工具,用于构建、变更与版本化管理基础设施。

01

快速上手

Provider

Provider 定义云平台。

terraform
provider "aws" {
  region = "us-east-1"
}

Resource

Resource 定义基础设施对象。

terraform
resource "aws_instance" "web" {
  ami           = "ami-123456"
  instance_type = "t2.micro"
  tags = { Name = "WebServer" }
}

命令

核心工作流:init、plan、apply、destroy。

terraform
# terraform init
# terraform plan
# terraform apply
# terraform destroy
02

核心特性

变量

用变量实现参数化。

terraform
variable "region" {
  type    = string
  default = "us-east-1"
}

resource "aws_instance" "web" {
  region = var.region
}

输出

Output 在 apply 后暴露值。

terraform
output "instance_ip" {
  value = aws_instance.web.public_ip
}

数据源

数据源查询既有资源。

terraform
data "aws_ami" "ubuntu" {
  most_recent = true
  filter { name = "name"; values = ["ubuntu-*"] }
}

这篇内容对您有帮助吗?