Passing size variable in Terraform

I'm not quite sure how to go about this.

I got a Terraform code to build a Linux VM on Azure. The Size is pre-defined in the Code. I was wondering how I can define the VM Size so that the user can pass the size via pre-defined Variable in the CLI.

The current variables user can pass in CLI is only Azure region:

variable "location" {
    type = string
    description = "Azure location of Terraform deployment"
    default = "canadacentral"
}

Where the user will pass terraform apply -var "location=eastus" for example, however I would like to allow the user to also pass something like -var "size=small".

The small would represent Standard_DS1_v2 for example, where medium would instead use Standard_B2ms.


You can declare another variable in the config:

variable "vm_size" {
  type        = string
  description = "The size of the Linux virtual machine"

  # validation block for restricting inputs to recognized sizes
  validation {
    condition     = contains(["small", "medium"], var.vm_size)
    error_message = "Valid vm_size inputs are 'small' or 'medium'."
  }
}

The user would then be able to pass a string for the size of the virtual machine. We can then create a Map corresponding from user input keys to Azure size values:

locals {
  vm_size = {
    "small"  = "Standard_DS1_v2"
    "medium" = "Standard_B2ms"
  }
}

Now we can resolve Azure VM sizes from user variable inputs like local.vm_size[var.vm_size]. We can then use these in the resource as per normal:

resource "azurerm_windows_virtual_machine" "this" {
  ...
  size = local.vm_size[var.vm_size]
  ...
}

You can also use the lookup function to provide a default value if you want:

# default to small size
lookup(local.vm_size, var.vm_size, "Standard_DS1_v2")