从 Terraform 输出动态获取值并按索引传递它们

Dynamically getting values from Terraform output and pass them by index

这里是 Terraform 新手。我想在下面的vpc_zone_identifier中只输出并动态添加前2个子网。但是我无法通过索引获取它,正在请求一个名称。

vpc_zone_identifier = [module.subnet[0].subnet_id, module.subnet[1].subnet_id]

这是我试过的。

如有任何建议,我们将不胜感激。

resource "aws_subnet" "this" {
  vpc_id     = var.vpc_id
  cidr_block = var.cidr_block_subnet
  map_public_ip_on_launch = var.map_public_ip_on_launch
  tags = var.tags
}
module "subnet" {
  source = "./aws_modules/subnet"
  for_each = {for key, value in var.subnet_settings: value.cidr_block_subnet => value}
  
  vpc_id                  = module.vpc.vpc_id
  cidr_block_subnet       = each.key
  map_public_ip_on_launch = each.value.map_public_ip_on_launch
  tags                    = var.tags

  depends_on = [module.vpc]
}
variable "subnet_settings" {
     type = list(object({
        cidr_block_subnet       = string
        map_public_ip_on_launch = bool
     }))
}
subnet_settings = [
  {
    cidr_block_subnet       = "10.1.1.0/24"
    map_public_ip_on_launch = false
  },
    {
    cidr_block_subnet       = "10.1.2.0/24"
    map_public_ip_on_launch = false
  },
    {
    cidr_block_subnet       = "10.1.3.0/24"
    map_public_ip_on_launch = false
  }
]
output "subnet_id" {
 value = aws_subnet.this.id
}
resource "aws_autoscaling_group" "autosys" {
  desired_capacity    = var.node-count
  max_size            = var.node-count
  min_size            = var.node-count
  name                = var.asg-name
  vpc_zone_identifier = [module.subnet[0].subnet_id, module.subnet[1].subnet_id]
  launch_template {
    id      = aws_launch_template.autosys.id
    version = "$Latest"
  }
}

for 表达式中,迭代 list 类型时,可以在 lambda 范围内初始化两个变量。在这种情况下,第一个变量将被分配迭代的索引。因此,我们可以修改模块的 for_each 元参数:

module "subnet" {
  source = "./aws_modules/subnet"
  for_each = {for idx, subnet in var.subnet_settings: idx => subnet}

  vpc_id                  = module.vpc.vpc_id
  cidr_block_subnet       = each.value.cidr_block_subnet
  map_public_ip_on_launch = each.value.map_public_ip_on_launch
  tags                    = var.tags

  depends_on = [module.vpc]
}

现在模块键将是 var.subnet_settings 的索引。相应地,模块输出命名空间现在将是 module.<declared_name>["<index>"].<output_name>。因此,我们可以修改 vpc_zone_identifier 参数的值,使其具有 string 类型而不是 number 类型的键:

vpc_zone_identifier = [module.subnet["0"].subnet_id, module.subnet["1"].subnet_id]

现在传递给参数的值将是所需的前两个子网。