I want to have a module that adds a network policy for AKS cluster if a user specifies it. However, I don’t know how to do conditional block items.
variable "network_plugin" { default = "kubenet" }
variable "network_policy" { default = "" }
resource "azurerm_kubernetes_cluster" "k8s" {
name = var.name
location = data.azurerm_resource_group.rg.location
resource_group_name = data.azurerm_resource_group.rg.name
network_profile {
load_balancer_sku = "Standard"
network_plugin = var.network_plugin
####### need this to be conditional #######
network_policy = var.network_policy
###########################################
}
}
I would like to simply not include the item network_policy
if it is blank ""
. The other items should always exist.
NOTE: If this is set with empty string, I’ll get: Error: expected network_profile.0.network_policy to be one of [calico azure]
, so this is why I would like to have this line conditional, allow user to add an optional network policy.
Hi @darkn3rd,
The best way to represent something being totally unset in the Terraform language is for it to be null
, as opposed to a placeholder value like the empty string. Therefore I’d recommend to change the default value for network_policy
to null
, which is how we can tell Terraform that the variable should remain optional but that it doesn’t actually have a default value:
variable "network_policy" {
type = string
default = null
}
Since there’s now not a default value, var.network_policy
will be null
when it isn’t set, and assigning null
to a resource argument is always the same as not setting it at all:
resource "azurerm_kubernetes_cluster" "k8s" {
name = var.name
location = data.azurerm_resource_group.rg.location
resource_group_name = data.azurerm_resource_group.rg.name
network_profile {
load_balancer_sku = "Standard"
network_plugin = var.network_plugin
network_policy = var.network_policy
}
}
We don’t need to write anything special in the network_policy
argument to deal with it not being set; assigning null
as the value is good enough to declare that this argument isn’t set in the case where var.network_policy
isn’t set.
1 Like