首页 > 解决方案 > 如何实例化渲染模板文件的内容?

问题描述

我有一个用于列表的模板文件:

variable "users" {
  type = "list"
  default = [
    "blackwidow",
    "hulk",
    "marvel",
  ]
}

// This will loop through the users list above and render out code for
// each item in the list.
data "template_file" "init" {
  template = file("user_template.tpl")
  count = length(var.users)
  vars = {
    username = var.users[count.index]
    bucketid = aws_s3_bucket.myFTP_Bucket.id
  }
}

模板文件有多个 aws 资源,例如
- “aws_transfer_user”
- “aws_s3_bucket_object”
- “aws_transfer_ssh_key”
等......事实上,它可以有更多的东西。它也有一些地形变量。

这个数据模板非常适合渲染模板文件的内容,替换为我的用户名。

但这就是 terraform 所做的一切。

Terraform 不会实例化模板文件的渲染内容。它只是将其保存为字符串并将其保存在内存中。有点像 C 预处理器进行替换,但不“包含”文件。有点令人沮丧。我希望 Terraform 实例化我渲染的模板文件的内容。我该怎么做呢?

标签: amazon-web-servicesterraformterraform-provider-aws

解决方案


template_file数据源(以及templatefile为 Terraform 0.12 替换它的函数)用于字符串模板,而不是用于模块化 Terraform 配置。

要为集合中的每个项目生成一组不同的资源实例,我们使用resourcefor_each

variable "users" {
  type = set(string)
  default = [
    "blackwidow",
    "hulk",
    "marvel",
  ]
}

resource "aws_transfer_user" "example" {
  for_each = var.users

  # ...
}

resource "aws_transfer_user" "example" {
  for_each = var.users

  # ...
}

resource "aws_s3_bucket_object" "example" {
  for_each = var.users

  # ...
}

resource "aws_transfer_ssh_key" "example" {
  for_each = aws_transfer_user.example

  # ...
}

Inside each of those resource blocks you can use each.key to refer to each one of the usernames. Inside the resource "aws_transfer_ssh_key" "example" block, because I used aws_transfer_user.example as the repetition expression, you can also use each.value to access the attributes of the corresponding aws_transfer_user object. That for_each expression also serves to tell Terraform that aws_transfer_ssh_key.example depends on aws_transfer_user.example.


推荐阅读