Saturday, January 15, 2022

How to refer set of values in terraform

 main.tf

## <https://www.terraform.io/docs/providers/azurerm/r/windows_virtual_machine.html>
resource "azurerm_windows_virtual_machine" "example" {
  name                = var.machine_details.name
  computer_name       = var.machine_details.name
  resource_group_name = azurerm_resource_group.rg.name
  location            = azurerm_resource_group.rg.location
  size                = var.machine_details.size
  admin_username      = var.machine_details.username
  admin_password      = var.machine_details.password
  network_interface_ids = [
    azurerm_network_interface.example.id,
  ]

  os_disk {
    caching              = "ReadWrite"
    storage_account_type = "Standard_LRS"
  }

  source_image_reference {
    publisher = "MicrosoftWindowsServer"
    offer     = "WindowsServer"
    sku       = "2019-Datacenter"
    version   = "latest"
  }
}

How to define them.


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

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

or can pass without setting data type.
variable "machine_details" {
  
  default = {
      name             = "example-vm2"
      size = "Standard_E2s_v3" #"Standard_F2"
      username               = "adminuser"
      password = "Notallowed1!"
    }
  
}

Let's say we have multiple machines or multiple network ports, then we can pass them in a single list and access them with index.

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.

Reference: 

https://discuss.hashicorp.com/t/how-to-set-default-values-for-a-object-in-terraform/34216/3

https://stackoverflow.com/questions/70694552/how-to-set-default-values-for-a-object-in-terraform/70720572#70720572


No comments:

Post a Comment