先看一个较完整的例子:
terraform {
required_version = ">= 1.8.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
provider "aws" {
region = "ap-southeast-1"
}
variable "project_name" {
type = string
default = "software-city"
}
resource "aws_s3_bucket" "assets" {
bucket = "${var.project_name}-assets-prod"
tags = {
Project = var.project_name
Env = "prod"
}
}
resource "aws_security_group" "api" {
name = "${var.project_name}-api-sg"
description = "API service ingress"
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
output "assets_bucket_name" {
value = aws_s3_bucket.assets.bucket
}这段蓝图可以这样理解:
总工局蓝图
├── 施工规则:Terraform / AWS provider 版本要求
├── 施工区域:ap-southeast-1
├── 城市变量:project_name
├── 建设对象 1:对象存储仓库 assets
├── 建设对象 2:API 安全门禁 sg
└── 施工结果回执:输出 bucket 名称你会发现 HCL 的风格很“工程蓝图化”:
- 不像通用编程语言那么灵活
- 但特别适合声明结构
- 对资源配置可读性很强
这也是 Terraform 长期流行的重要原因之一。