【问题标题】:Unable to fetch terraform list variables dynamically无法动态获取 terraform 列表变量
【发布时间】:2019-09-15 13:27:34
【问题描述】:

我在 variables.tf 中有一个列表变量“test”。我正在尝试在我的 zone.tf 中使用这个列表变量。

我不想在这里使用列表索引,事实上我想运行一个循环来动态地从列表变量中获取列表的所有值。我怎样才能做到这一点?非常感谢任何帮助。

我尝试在资源资源“aws_route53_record”内的 test.tf 中使用计数,但它创建了多个我不想要的记录集,因为我只需要一个包含多个记录的记录集

   resource "aws_route53_record" "test" {
      zone_id = "${data.aws_route53_zone.dns.zone_id}"
      name    = "${lower(var.environment)}xyz"
      type    = "CAA"
      ttl     = 300
      count = "${length(var.test)}"
     records = [
        "0 issue \"${element(var.test, count.index)}\"",
      ]
    }

variables.tf :-

variable "test" {
  type    = "list"
  default = ["godaddy.com", "Namecheap.org"]
}




zone.tf :-

resource "aws_route53_record" "test" {
  zone_id = "${data.aws_route53_zone.dns.zone_id}"
  name    = "${lower(var.environment)}xyz"
  type    = "CAA"
  ttl     = 300
  records = [
    "0 issue \"${var.test[0]}\"",
    "0 issue \"${var.test[1]}\"",
  ]
}

期望获得具有两条记录的一条记录集。

实际:- 得到两个记录集和两个记录。

【问题讨论】:

    标签: terraform


    【解决方案1】:

    因此,如果我理解正确,您希望将两条记录与您的区域相关联,但现在使用 count 时,您将获得两个区域和一条记录。

    这是因为通过指定县 terraform 将创建具有 count 属性的资源等于 count 的数量。

    问题基本上是,现在您有一个列表变量,并试图通过提取列表的每个单独元素将其逐个元素放回列表属性来将其传递到预期列表的位置。

    与其进行额外的工作,更简单的解决方案是将字符串的其他部分,“0 issue”部分添加到变量的定义中,然后将整个列表对象传递给如下所示

    variable "test" {
      type    = "list"
      default = ["0 issue godaddy.com", "0 issue Namecheap.org"]
    }
    
    zone.tf :-
    
    resource "aws_route53_record" "test" {
      zone_id = "${data.aws_route53_zone.dns.zone_id}"
      name    = "${lower(var.environment)}xyz"
      type    = "CAA"
      ttl     = 300
      records = ["${var.test}"]
    }
    

    这将传递该属性的列表,而 terraform 将负责列表的编组和解组以及处理。我希望这回答了你的问题。

    【讨论】:

    • 如果需要从主机名到更长的字符串,这可以通过另外使用 formatlist("0 issue %s", var.test) 依次格式化每个列表项来实现,作为在变量默认值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    相关资源
    最近更新 更多