首页 > 解决方案 > 如何在terraform的嵌套列表中切片第一个元素

问题描述

我想通过,var.domain_names例如list(list(string))

domain_names = [
  ["foo.com",".*foo-1.com",".*foo-2.com"],
  ["bar.com",".*bar-1.com"],
  ...
]

因此,它应该为 foo.com、bar.com ... 创建证书,但将 .*foo-1.com ... 等其他证书添加到 subject_alternative_names 中。

请帮我解决这个问题,使用 terraform 0.12.18

resource "aws_acm_certificate" "certificate" {
  domain_name               = var.domain_names[count.index]
  subject_alternative_names = slice(var.domain_names, 1, length(var.domain_names))
  validation_method         = var.validation_method

  tags = {
    Name      = var.domain_names[count.index]
    owner     = "xx"
    terraform = "true"
  }

  lifecycle {
    create_before_destroy = true
  }
}

标签: terraformterraform-provider-aws

解决方案


您可以使用一个map和一个for_each循环来完成此操作。例如:

variable "domain_names" {
  type = map(list(string))
  default = {
    "foo.com" = ["foo.com", ".*foo-1.com", ".*foo-2.com"]
    "bar.com" = [".*bar-1.com"]
  }
}

resource "aws_acm_certificate" "certificate" {
  for_each                  = var.domain_names
  domain_name               = each.key
  subject_alternative_names = each.value
  validation_method         = var.validation_method

  tags = {
    Name      = each.key
    owner     = "xx"
    terraform = "true"
  }

  lifecycle {
    create_before_destroy = true
  }
}

有关循环和条件的更多信息,请参阅此博客文章。


推荐阅读