遍历文件函数的映射

Tra*_*Lex 0 terraform

我有一个使用 terraform 将多个文件上传到 s3 的用例。我想使用计数功能上传多个对象。为此需要使用 file("${path.module}/path/to/file") 遍历源代码。

有没有办法利用count.index使文件函数成为映射变量?

Mar*_*ins 5

Terraform 0.12.8 引入了一个新函数fileset,该函数可以返回一组与特定基目录中特定模式匹配的文件路径。

我们可以将它与资源for_each(而不是count)结合起来将匹配的文件上传到 S3,如下所示:

resource "aws_s3_bucket_object" "example" {
  for_each = fileset("${path.module}/files", "*") # could use ** instead for a recursive search

  bucket       = "example"
  key          = each.value
  source       = "${path.module}/${each.value.source_path}"

  # Unless the bucket has encryption enabled, the ETag of each object is an
  # MD5 hash of that object.
  etag = filemd5("${path.module}/${each.value.source_path}")
}
Run Code Online (Sandbox Code Playgroud)

使用这里for_each代替count意味着 Terraform 将通过其 S3 路径而不是通过其在列表中的位置来识别资源的每个实例,因此您可以添加和删除文件而不会干扰其他文件。例如,如果您有一个名为的文件,example.txt那么 Terraform 会将其实例跟踪为aws_s3_bucket_object.example["example.txt"],而不是像aws_s3_bucket_object.example[3]3 是它在文件列表中的位置这样的地址。


我编写了一个 Terraform 模块,该模块fileset还支持基于文件名后缀的模板渲染和检测文件类型,这可能会在一些更复杂的情况下使生活更轻松:apparentlymart/dir/template. 您可以aws_s3_bucket_object以与上述类似的方式使用其结果,如其自述文件中所示。