第10天:Conditional expressions、Dynamic blocks、Splat expressions 在 Terraform 中
发布: (2025年12月4日 GMT+8 00:08)
3 min read
原文: Dev.to
Source: Dev.to
条件表达式
Terraform 中的条件表达式允许你根据条件在两个值之间进行选择。语法为 condition ? true_value : false_value。这在根据变量值或其他条件设置资源属性时非常有用。
- 根据环境(dev/prod)选择实例
- 根据配置启用监控
- 根据区域选择不同的 AMI
示例
// main.tf
resource "aws_instance" "instance" {
ami = "ami-0fa3fe0fa7920f68e"
region = "us-east-1"
instance_type = var.environment == "dev" ? "t3.micro" : "t3.small"
count = var.instance_count
tags = var.tags
}
// variables.tf
variable "environment" {
type = string
default = "dev"
}
Splat 表达式
Splat 表达式允许你从对象列表中提取多个值。语法为 resource_type.resource_name[*].attribute。这在从多个资源实例中检索属性时非常有用。
示例
// main.tf
resource "aws_instance" "instance" {
ami = "ami-0fa3fe0fa7920f68e"
region = "us-east-1"
instance_type = var.environment == "dev" ? "t3.micro" : "t3.small"
count = var.instance_count
tags = var.tags
}
// splat expression example in Terraform
output "instance_ids" {
value = aws_instance.instance[*].id
}
动态块
Terraform 中的动态块允许你根据列表或映射变量在资源内部生成多个嵌套块。语法如下:
dynamic "block_name" {
for_each = var.list_variable
content {
# block attributes
}
}
这对于在不复制代码的情况下创建多个相似的配置非常有用。
示例
// variables.tf
variable "ingress_values" {
type = list(object({
from_port = number
to_port = number
protocol = string
cidr_blocks = list(string)
}))
default = [
{
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
},
{
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
]
}
// main.tf
resource "aws_security_group" "security_group" {
name = "sg"
dynamic "ingress" {
for_each = var.ingress_values
content {
from_port = ingress.value.from_port
to_port = ingress.value.to_port
protocol = ingress.value.protocol
cidr_blocks = ingress.value.cidr_blocks
}
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
通过使用条件表达式、Splat 表达式和动态块,你可以创建更灵活、可复用且易于维护的 Terraform 配置。