Terraform 基础设施即代码入门:用代码管理云资源
Terraform 是 HashiCorp 开发的基础设施即代码(IaC)工具,支持管理所有主流云平台的资源。
一、安装和配置
# macOS
brew install terraform
# 验证安装
terraform version
# 基本命令
terraform init # 初始化项目
terraform plan # 预览变更
terraform apply # 执行变更
terraform destroy # 销毁资源
二、第一个 Terraform 配置
# main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "WebServer"
}
}
resource "aws_security_group" "web_sg" {
name = "web-sg"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
三、核心概念
| 概念 | 说明 |
|---|---|
| Provider | 云平台插件(AWS、Azure、GCP) |
| Resource | 被管理的资源(实例、网络等) |
| Data Source | 查询已有资源信息 |
| State | 基础设施状态文件(terraform.tfstate) |
| Module | 可复用的配置模块 |
四、状态管理
远程状态存储是最佳实践:
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
}
}
五、变量和输出
# variables.tf
variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t2.micro"
}
# outputs.tf
output "instance_ip" {
value = aws_instance.web.public_ip
}