0
votes

I'm trying to deploy two virtual machines within the same resource group to our Azure platform with Terraform. After successfully creating the first one Terraform then wants to destroy the first one to create the second one after I've changed the second VM name and Azure tag.

I've been following the Terraform guide: https://www.terraform.io/docs/providers/azurerm/r/virtual_machine.html

resource "azurerm_virtual_machine" "main" {
  location = "${var.location}"
  name = "${var.vm_name}"
  network_interface_ids = ["${azurerm_network_interface.main.id}"]
  resource_group_name = "${var.resourcegroup_vm}"
  vm_size = "${var.vm_size}"
  tags {
    application = "${var.tag}"
  }

I expected Terraform to just create the second VM after changing its variable name and tag. Not wanting to destory the first one because of the name and tag change.

1
i'd think you'd either need to duplicate the code or use iterations for this to work. or copy this code to a new folder and start a new terraform "project" in that one4c74356b41
@4c74356b41 - Yeah it will probably work if I just duplicate the code into a new project with the name + tag for the secondary VM but it would just be alot easier if you could use the same project for creating multiple VMs with name changes.Smithone
@4c74356b41 - It worked when deploying the second VM from a new project. However I'm still interested in knowing if it possible to do within the same project. It makes it easier when deploying multiple VMs to the same resource group.Smithone
If you want to create multiple vms in the same project, just set the count in the vm block.Charles Xu

1 Answers

0
votes

Terraform is based on HCL (Hashicorp Configuration Language), which is the format *.tf files are written in. It is a declarative language (as opposed to imperative), which means that you describe the desired state you want your infrastructure to be and Terraform will figure out what changes are needed to take it to that point.

If you first create an instance and then change its name you are telling Terraform that you no longer want your instance to have the old name but the new one.

To deploy a number of instances you can use the count attribute. You could then use interpolation to get names and tags based in the counter, something similar to this:

resource "azurerm_virtual_machine" "main" {
  location = "${var.location}"
  name = "${var.vm_name}-${count.index + 1}"
  network_interface_ids = ["${azurerm_network_interface.main.id}"]
  resource_group_name = "${var.resourcegroup_vm}"
  vm_size = "${var.vm_size}"
  tags {
    application = "${var.tag}-${count.index + 1}"
  }

  count = 2
}

Note the attached -${count.index + 1} to name and the application tag.