Terraform - 如何在 tfvars 中初始化设置变量

Terraform - How to initialize set variable in tfvars

背景

Terraform 文档明确指出根模块中定义的变量可以在 tfvars 文件中设置。

Type Constraints

The type constructors allow you to specify complex types such as collections:

  • set(<TYPE>)

Assigning Values to Root Module Variables

When variables are declared in the root module of your configuration, they can be set in a number of ways:

  • In variable definitions (.tfvars) files, either specified on the command line or automatically loaded.

可以在根模块中定义 set 类型的输入变量。

variables.tf

variable "roles" {
  description = "IAM roles to grant to the service account"
  type    = set(string)
}

问题

请指教如何初始化tfvars中的set变量?不允许使用函数,据我环顾四周,Terraform 文档中似乎没有示例。或者如果设置 set 不受支持,是否明确记录?

terraform.tfvars

roles = toset([
  "roles/cloudsql.client",
  "roles/bigquery.dataEditor",
  "roles/storage.admin",
  "roles/pubsub.edito",
  "roles/secretmanager.secretAccessor",
  "roles/artifactregistry.reader"
])
Error: Function calls not allowed
│ 
│   on sa.auto.tfvars line 1:
│    1: roles = toset([
│    2:   "roles/cloudsql.client",
│    3:   "roles/bigquery.dataEditor",
│    4:   "roles/storage.admin",
│    5:   "roles/pubsub.edito",
│    6:   "roles/secretmanager.secretAccessor",
│    7:   "roles/artifactregistry.reader"
│    8: ])

您只需将其定义为:

roles = [
  "roles/cloudsql.client",
  "roles/bigquery.dataEditor",
  "roles/storage.admin",
  "roles/pubsub.edito",
  "roles/secretmanager.secretAccessor",
  "roles/artifactregistry.reader"
]

TF 会自动将其转换为正确的类型。