David Tinoco Castillo
David Tinoco Castillo

Reputation: 65

Update terraform variable from resource

I want to update a variable from a resource on terraform.

Is that possible? I'm a bit new in this technology.

variable "contador" {
    default = 0
}

resource "azurerm_managed_disk" "test-disks-test3" {
    count                   = "${length(var.disks_size) * var.vm_number}"
    name                    = "SRV${var.service_base_name}${var.service_environment}01-DATADISK-0${count.index}"
    location                = "westeurope"
    resource_group_name     = "${azurerm_resource_group.test-rg-test3.name}"
    storage_account_type    = "${var.disk_tier}_${var.disk_replication}"  
    create_option           = "Empty"
    disk_size_gb            = "${element(var.disks_size, count.index)}"

    var.contador            = "${count.index % length(var.disks_size) == (length(var.disks_size) - 1) ? (var.contador + 1)  : var.contador}"

    tags{
        environment = "TestWork"
    }
}

The line in question is:

var.contador = "${count.index % length(var.disks_size) == (length(var.disks_size) - 1) ? (var.contador + 1)  : var.contador}"

Upvotes: 6

Views: 3922

Answers (1)

Quentin Revel
Quentin Revel

Reputation: 1478

TL;DR

You can't update the variable.

About HCL

Terraform is using the HCL language.

This language is declarative and not procedural or OOP. It means once it is defined, terraform doesn't not allow you to modify its value at the run time.

From the terraform documentation:

The default value of an input variable must be a literal value, containing no interpolation expressions. To assign a name to an expression so that it may be re-used within a module, use Local Values instead.

Moreover in your resource block, you can only use arguments defined by that resource and var.contador is not one of them.

Upvotes: 3

Related Questions