如何用Terraform创建符合特定命名规范的多AWS LB目标组
实现方案
1. 定义多目标组配置变量
先把原来的单个参数变量改成对象列表,让每个元素对应一个目标组的独立配置:
variable "target_groups" { type = list(object({ forward_port = number forward_protocol = string target_type = string deregistration_delay = number health_check_interval = number health_check_path = string cookie_type = string })) description = "批量目标组的配置列表,每个元素对应一个独立目标组" default = [] }
2. 修改资源块支持批量创建
用count遍历配置列表,同时实现命名规则:列表长度为1时用test-tg,长度大于1时追加从1开始的索引:
resource "aws_lb_target_group" "main" { count = length(var.target_groups) name = length(var.target_groups) == 1 ? "test-tg" : "test-tg${count.index + 1}" port = var.target_groups[count.index].forward_port protocol = var.target_groups[count.index].forward_protocol target_type = var.target_groups[count.index].target_type deregistration_delay = var.target_groups[count.index].deregistration_delay health_check { interval = var.target_groups[count.index].health_check_interval path = var.target_groups[count.index].health_check_path } stickiness { type = var.target_groups[count.index].cookie_type } }
3. 使用示例
创建1个目标组
variable "target_groups" { default = [ { forward_port = 80 forward_protocol = "HTTP" target_type = "instance" deregistration_delay = 300 health_check_interval = 30 health_check_path = "/" cookie_type = "lb_cookie" } ] }
生成的目标组名称为test-tg。
创建3个独立配置的目标组
variable "target_groups" { default = [ { forward_port = 80 forward_protocol = "HTTP" target_type = "instance" deregistration_delay = 300 health_check_interval = 30 health_check_path = "/" cookie_type = "lb_cookie" }, { forward_port = 8080 forward_protocol = "HTTP" target_type = "ip" deregistration_delay = 120 health_check_interval = 15 health_check_path = "/health" cookie_type = "application_cookie" }, { forward_port = 443 forward_protocol = "HTTPS" target_type = "instance" deregistration_delay = 300 health_check_interval = 60 health_check_path = "/status" cookie_type = "lb_cookie" } ] }
生成的目标组名称依次为test-tg1、test-tg2、test-tg3,每个组的端口、健康检查规则等参数完全独立。
补充说明
如果更习惯用for_each而非count,可以将变量改为map(object(...))类型,命名逻辑调整为:当map长度为1时用test-tg,否则结合map的key生成名称,但count在处理连续索引命名的场景下更直接。
内容的提问来源于stack exchange,提问作者cloudbud
相关产品推荐
相关产品推荐

