I was recently implementing a change to a Terraform azurerm_key_vault
Key Vault resource to allow a specified list of IP addresses on the firewall. The IP addresses would be provided via an Azure DevOps variable, which would contain a comma-separated list. This list is then turned into a list value in Terraform via the split
function.
I wanted the change to the resource to continue to work if the variable was not specified, but when no value was provided the result would be an empty string, and this was not a valid value for the ip_rules
property of the Key Vault resource, which requires either null
or a list of values.
The solution was to use the compact function. This takes a list of strings and removes any null or empty string elements:
resource "azurerm_key_vault" "keyvault" {
name = var.keyVaultName
location = var.location
resource_group_name = var.rgName
sku_name = "standard"
tenant_id = data.azurerm_client_config.current.tenant_id
network_acls {
default_action = "Deny"
ip_rules = compact(split(",", var.keyVaultAllowedIPs))
}
}
The compact function appears to have been a part of Terraform since at least version 1.1 but looking at the documentation it appears that it only started to remove null
values from strings (as well as empty strings) as of version 1.5.
At time of writing the current production release of Terraform is 1.9.
Top comments (0)