第7天 – Terraform中的类型约束
发布: (2025年12月8日 GMT+8 01:45)
3 min read
原文: Dev.to
Source: Dev.to
基本类型
基本类型是构建块:string、number 和 bool。
variable "name" {
type = string
default = "Terraform"
}
variable "age" {
type = number
default = 25
}
variable "is_enabled" {
type = bool
default = true
}
复合类型
复合类型允许你将多个值组合在一起。
List(相同类型值的有序集合)
variable "instance_ids" {
type = list(string)
}
Set(唯一值,顺序不重要)
variable "unique_tags" {
type = set(string)
}
Tuple(不同类型的有序集合)
variable "my_tuple" {
type = tuple([string, number, bool])
}
Map(字符串键对应相同类型的值)
variable "region_mapping" {
type = map(string)
}
Object(属性可以有不同类型,类似结构体)
variable "server_config" {
type = object({
name = string
cpu = number
prod = bool
})
}
特殊类型
any(接受任意 Terraform 数据类型)
variable "input" {
type = any
}
null(表示值的缺失,常用于触发默认行为)
variable "instance_type" {
default = null
}
实际示例
基于环境的命名
variable "environment" {
type = string
default = "dev"
}
resource "aws_s3_bucket" "example" {
bucket = "${var.environment}-app-data"
}
更改 environment 会更新所有受影响的资源。
可伸缩的实例数量
variable "instance_count" {
type = number
default = 3
}
resource "aws_instance" "server" {
count = var.instance_count
ami = "ami-123"
instance_type = "t2.micro"
}
增加 instance_count 会创建更多服务器。
切换监控
variable "monitoring_enabled" {
type = bool
default = true
}
resource "aws_instance" "server" {
monitoring = var.monitoring_enabled
}
通过单个变量打开或关闭监控。
多可用区子网
variable "availability_zones" {
type = list(string)
default = ["us-east-1a", "us-east-1b"]
}
resource "aws_subnet" "subnet" {
count = length(var.availability_zones)
az = var.availability_zones[count.index]
cidr_block = "10.0.${count.index}.0/24"
}
子网会自动在指定的可用区中创建。
集中式标签管理
variable "tags" {
type = map(string)
default = {
Environment = "dev"
Owner = "teamA"
}
}
resource "aws_vpc" "main" {
tags = var.tags
}
在单一位置管理所有标签。
复合配置对象
variable "config" {
type = object({
region = string
monitoring = bool
instance_count = number
})
default = {
region = "us-east-1"
monitoring = true
instance_count = 2
}
}
provider "aws" {
region = var.config.region
}
进一步阅读
更多信息请参阅仓库:
https://github.com/ankitgadling/terraformwithaws/tree/main/day_7