name: terraform配置 user-invocable: false description: 用于编写和组织Terraform基础设施即代码配置,用于云资源供应。 allowed-tools: []
Terraform 配置
编写和组织Terraform基础设施即代码配置。
基本结构
# 提供者配置
terraform {
required_version = ">= 1.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
}
}
provider "aws" {
region = var.region
}
资源
resource "aws_instance" "web" {
ami = var.ami_id
instance_type = var.instance_type
tags = {
Name = "web-server"
Environment = var.environment
}
lifecycle {
create_before_destroy = true
prevent_destroy = false
}
}
变量
variable "environment" {
description = "环境名称"
type = string
default = "development"
validation {
condition = contains(["development", "staging", "production"], var.environment)
error_message = "环境必须是 development、staging 或 production。"
}
}
variable "instance_count" {
description = "实例数量"
type = number
default = 1
}
variable "tags" {
description = "资源标签"
type = map(string)
default = {}
}
输出
output "instance_id" {
description = "EC2 实例的 ID"
value = aws_instance.web.id
}
output "public_ip" {
description = "公共 IP 地址"
value = aws_instance.web.public_ip
sensitive = false
}
数据源
data "aws_ami" "amazon_linux" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["amzn2-ami-hvm-*-x86_64-gp2"]
}
}
data "aws_vpc" "default" {
default = true
}
本地变量
locals {
common_tags = {
Project = "myapp"
ManagedBy = "terraform"
Environment = var.environment
}
name_prefix = "${var.project}-${var.environment}"
}
resource "aws_instance" "web" {
# ...
tags = merge(local.common_tags, {
Name = "${local.name_prefix}-web"
})
}
常用命令
# 初始化
terraform init
# 格式化
terraform fmt -recursive
# 验证
terraform validate
# 计划
terraform plan -out=tfplan
# 应用
terraform apply tfplan
# 销毁
terraform destroy
# 显示状态
terraform show
# 列出资源
terraform state list
最佳实践
文件组织
project/
├── main.tf # 主要资源
├── variables.tf # 变量声明
├── outputs.tf # 输出声明
├── versions.tf # 提供者版本
├── terraform.tfvars # 变量值(如果敏感则git忽略)
└── modules/ # 本地模块
└── network/
使用变量以提高灵活性
# 不好
resource "aws_instance" "web" {
instance_type = "t2.micro"
}
# 好
resource "aws_instance" "web" {
instance_type = var.instance_type
}
使用本地变量计算值
locals {
timestamp = formatdate("YYYY-MM-DD-hhmmss", timestamp())
full_name = "${var.prefix}-${var.name}-${var.suffix}"
}