Reputation: 9387
In Terraform, how do we define a list of objects?
variables.tf
variable "aws_cluster_arn" {
type = string
}
variable "aws_ecs_placement_strategy" {
type = list(object)
}
in configuration.tfvars
aws_ecs_placement_strategy=(object({type="spread",field="attribute:ecs.availability-zone"}),object({type="BinPack",field="CPU"}))
I am getting following error:
Error: Invalid type specification
on variables.tf line 53, in variable "aws_ecs_placement_strategy":
53: type = list(object)
Upvotes: 2
Views: 3268
Reputation: 906
One often wants to be able to define a list of custom objects as variables in Terraform, and it's more straightforward than you'd think.
It can simply be defined as follows:
variable "var_name" {
val_a = string
val_list = list(object({
list_val_1 = string
list_val_2 = number
}))
}
This way you can define a list of variable values that can be iterated through to generate resources dynamically. When paired with the 'dynamic' block, it becomes a a powerful tool. It can be used as follows, assuming we define a list of variables following the example above:
dynamic "resource_name" {
for_each = var.var_name.val_list
content = {
val_1 = resource_name.value.list_val_1
val_2 = resource_name.value.list_val_2
}
}
Following this pattern can make your Terraform code much more modular and reusable, allowing for dynamic definitions that span multiple use cases.
Upvotes: 0
Reputation: 16778
When defining an object
type, you should specify all of the object
's fields and their types like so:
variable "aws_ecs_placement_strategy" {
type = list(object({
type = string,
field = string
}))
}
Upvotes: 5