How to set default values for a object in terraform?

My terraform snippet:


variable "machine_details" {
  type = object({
    name              = string
    size = string
    username               = string
    password = string
  })

  default = [
    {
      name              = "example-vm"
      size = "Standard_F2"
      username               = "adminuser"
      password = "Notallowed1!"
    }
  ]
}

I am getting error as below.


    Error: Invalid default value for variable
    │
    │   on variables.tf line 38, in variable "machine_details":
    │   38:   default = [
    │   39:     {
    │   40:       name              = "example-vm"
    │   41:       size = "Standard_F2"
    │   42:       username               = "adminuser"
    │   43:       password = "Notallowed1!"
    │   44:     }
    │   45:   ]
This default value is not compatible with the variable's type constraint: object required.

I tried map(string) but didn’t work too.

similary list(string) also.

I am trying the latest azurerm provider.

Also, in the gcp, we have option to provide count(for instances), so if I provide 2, two instances will be created.

How to do the same with azure and aws?

How to resolve this?

Hi ukreddy-erwin,
you can reach your goal by defining your variable in this way

variable "machine_details" {
  type = list(object({
    name = string
    size = string
    username = string
    password = string
  }))

  default = [
    {
      name = "example-vm"
      size = "Standard_F2"
      username  = "adminuser"
      password = "Notallowed1!"
    }
  ]
}

and then you can use the variable in this way (for example to create an S3 bucket):

resource "aws_s3_bucket" "b" {
  count = length(var.machine_details)
  bucket = "my-test-bucket-1234${var.machine_details[count.index].name}"
  acl    = "private"
}

count is used to create as many resources as variable list length and then you can access list’s object by using this notation: var.machine_details[count.index].object-field.

Please let me know if i have understood your problem or there is something else.

Bye