Terraform - How to initialize set variable in tfvars

Viewed 1100

Background

The Terraform document clearly states variable defined in the root module can be set in tfvars file.

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.

An input variable of type set can be defined in a root module.

variables.tf

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

Question

Please advise how to initialize the set variable in tfvars? Using function is not allowed, and as far as I looked around, it looks there is no example in the Terraform documentations. Or if setting set is not supported, is it clearly documented?

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: ])
1 Answers

You just define it as:

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

TF will automatically convert it to the correct type.

Related