【问题标题】:Enumerate map variable using null_resource and triggers使用 null_resource 和触发器枚举映射变量
【发布时间】:2017-10-04 18:50:20
【问题描述】:

我正在尝试使用null_resourcetriggers 枚举映射变量,并在另一个资源中使用此枚举的结果。

这行得通:

resource "null_resource" "dummy" {
  count = "${length(var.file_map)}"

  triggers {
    filename = "${element(keys(var.file_map), count.index)}"
    content = "${var.file_map[element(keys(var.file_map), count.index)]}"
  }
}

variable "file_map" {
  type = "map"

  default = {
    "foo.txt" = "foo"
    "bar.txt" = "bar"
  }
}

输出:

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  + null_resource.dummy[0]
      id:                <computed>
      triggers.%:        "2"
      triggers.content:  "bar"
      triggers.filename: "bar.txt"

  + null_resource.dummy[1]
      id:                <computed>
      triggers.%:        "2"
      triggers.content:  "foo"
      triggers.filename: "foo.txt"


Plan: 2 to add, 0 to change, 0 to destroy.

但是当我尝试在另一个资源中使用枚举结果时,它失败了:

resource "local_file" "some_files" {
  content = "${null_resource.dummy.triggers.content}"
  filename = "${null_resource.dummy.triggers.filename}"
}

resource "null_resource" "dummy" {
  count = "${length(var.file_map)}"

  triggers {
    filename = "${element(keys(var.file_map), count.index)}"
    content = "${var.file_map[element(keys(var.file_map), count.index)]}"
  }
}

variable "file_map" {
  type = "map"

  default = {
    "foo.txt" = "foo"
    "bar.txt" = "bar"
  }
}

输出:

Error running plan: 1 error(s) occurred:

* local_file.some_files: 1 error(s) occurred:

* local_file.some_files: Resource 'null_resource.dummy' not found for variable
                         'null_resource.dummy.triggers.content'

有没有办法让它工作?

【问题讨论】:

    标签: enumeration terraform


    【解决方案1】:

    element 在资源 null_resource 中的类似用法,您需要在 local_file 中执行相同操作。

    resource "local_file" "some_files" {
      count = "${length(var.file_map)}"
    
      content = "${element(null_resource.dummy.*.triggers.content, count.index)}"
      filename = "${element(null_resource.dummy.*.triggers.filename, count.index)}"
    }
    
    resource "null_resource" "dummy" {
      count = "${length(var.file_map)}"
    
      triggers {
        filename = "${element(keys(var.file_map), count.index)}"
        content = "${var.file_map[element(keys(var.file_map), count.index)]}"
      }
    }
    
    variable "file_map" {
      type = "map"
    
      default = {
        "foo.txt" = "foo"
        "bar.txt" = "bar"
      }
    }
    

    运行terraform apply后,会生成两个文件

    $ cat bar.txt
    bar
    $ cat foo.txt
    foo
    

    如果您想了解更多信息,cat terraform.tfstate 将为您提供有关其工作原理的详细信息。

    【讨论】:

    • 哇,哇。太感谢了。我一直在尝试使用splat hack,但失败了。现在一切都说得通了。
    猜你喜欢
    • 1970-01-01
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多