获取Terraform上的变量列表

时间:2020-03-17 01:06:37

标签: terraform

我正在尝试使用Terraform获取变量列表,以下是我的目录结构:

.
├── main.tf
├── path_modules
│   └── module_name
│       ├── main.tf
│       └── variables.tf
└── variables.tf

我将变量放在main.tf文件中,如下所示:

module "module_name"
...
  ssh_users                   = ["user1", "user2", "user3", "user4", "user5", "user6", "user7", "user8", "user9"]
  ssh_keys                    = ["user1.pem.pub", "user2.pem.pub", "user3.pem.pub", "user4.pem.pub", "user5.pem.pub", "user6.pem.pub", "user7.pem.pub", "user8.pem.pub", "user9.pem.pub"]

然后我将代码放入./path_module/module_name/main.tf文件中,以获取该变量,如下所示:

resource "google_compute_instance" "module_name" {
...
  metadata = {
    count = length(var.ssh_keys)
    ssh-keys = format("%s:%s", "${var.ssh_users[count.index]}", file("${path.module}/${var.ssh_keys[count.index]}"))
  }

,并尝试使用 terrain validate 进行验证后,出现此错误:

Error: Reference to "count" in non-counted context

  on path_module/module_name/main.tf line number, in resource "google_compute_instance" "module_name":
  line number:     ssh-keys = format("%s:%s", "${var.ssh_users[count.index]}", file("${path.module}/${var.ssh_keys[count.index]}"))

The "count" object can be used only in "resource" and "data" blocks, and only
when the "count" argument is set.

1 个答案:

答案 0 :(得分:0)

请注意,您只能在资源级别使用count,并且metadata参数是一个映射。

resource "google_compute_instance" "module_name" {
  count = length(var.ssh_keys)

  ...

  metadata = {
    ssh-keys = format(
      "%s:%s",
      "${var.ssh_users[count.index]}", ], 
      file("${path.module}/${var.ssh_keys[count.index]}")
    )
  }
}