Home > Enterprise >  Terraform Enable or Disable Parameter inside resource block and also resource block?
Terraform Enable or Disable Parameter inside resource block and also resource block?

Time:10-28

I am defining network interface inside the VMSS AZURE Terraform Well what i want is disable or enable the load balancer backend address pool id if $app != "api" In other words if app is api then only add that parameter and attach pool id.

Also, How to enable or disable entire resource lets say i want to diable or enable the network interface block in whole.

Thanks in advance for helping.

load_balancer_backend_address_pool_ids       = [var.backend_address_pool_id] #enable only when var.app is api.
network_interface {
    name    = "${var.app}-vmss-nic"
    primary = true
    ip_configuration {
      name                                         = "internal"
      primary                                      = true
      subnet_id                                    = var.pvt_subnet_1_id
load_balancer_backend_address_pool_ids       = [var.backend_address_pool_id]
    }
  }

CodePudding user response:

This can be done by using the ternary operator [1] and a combination of the dynamic block [2] with for_each meta-argument [3] for the network interface. To achieve this you would do the following:

dynamic "network_interface" {
   for_each = var.app == "api" ? [1] : [0]
   content {
    name    = "${var.app}-vmss-nic"
    primary = true
    ip_configuration {
      name                                         = "internal"
      primary                                      = true
      subnet_id                                    = var.pvt_subnet_1_id 
  load_balancer_backend_address_pool_ids       = [var.backend_address_pool_id] 
    }
  }
}

[1] https://developer.hashicorp.com/terraform/language/expressions/conditionals

[2] https://developer.hashicorp.com/terraform/language/expressions/dynamic-blocks

[3] https://developer.hashicorp.com/terraform/language/meta-arguments/for_each

CodePudding user response:

you would need to test this but you could possible do something like

load_balancer_backend_address_pool_ids = var.app == "api" ? [var.backend_address_pool_id] : null

or incase the provider doesnt support null and just expects an empty list

load_balancer_backend_address_pool_ids = var.app == "api" ? [var.backend_address_pool_id] : []
  • Related