Terraform - Define list using variable block
by
Jeremy Canfield |
Updated: July 19 2023
| Terraform articles
Lists can be defined in a variable block. For example, let's say you have the following files on your Terraform server.
├── main.tf (root module)
├── data.tf
├── locals.tf
├── outputs.tf
├── providers.tf
├── terraform.tfstate
├── variables.tf
├── child (directory)
│ ├── main.tf (child module)
│ ├── data.tf
│ ├── outputs.tf
│ ├── resources.tf
For example, let's say your variables.tf file has the following.
variable "environments" {
type = list(string)
sensitive = false
default = ["dev", "stage", "prod"]
}
And your outputs.tf file in the same directory as your main root module (main.tf) could then output the environments list.
output "my-environments" {
value = var.environments
}
The terraform output command . . .
terraform output
. . . should return the following.
my-environments = tolist([
"dev",
"stage",
"prod",
])
Or, you can output specific elements in the list.
output "environment-0" {
value = var.environments[0]
}
output "environment-1" {
value = var.environments[1]
}
output "environment-2" {
value = var.environments[2]
}
Which should return the following.
environment-0 = "dev"
environment-1 = "stage"
environment-2 = "prod"
Did you find this article helpful?
If so, consider buying me a coffee over at