Conditional for empty list

api_server_authorized_ip_ranges = (var.k8s_api_server_authorized_ip_ranges == ? [var.k8s_api_server_authorized_ip_ranges] : concat([data.azurerm_public_ip.ss_perimeter_fw_ip.ip_address], var.k8s_api_server_authorized_ip_ranges, module.network_vars.q.az.global.access_lists.strict))

–doesn’t work
variable “k8s_api_server_authorized_ip_ranges” {
description = “The IP ranges to whitelist for incoming traffic to the masters”
type = list(string)
default =
}

variable is as above
–so if I don’t set a variable, it should not enable ‘api_server_authorized_ip_ranges’
–but here it’s enabling it, but adding IPs from this bit
concat([data.azurerm_public_ip.ss_perimeter_fw_ip.ip_address], var.k8s_api_server_authorized_ip_ranges, module.network_vars.q.az.global.access_lists.strict)

Did you try

... = (var.k8s_api_server_authorized_ip_ranges.count < 1 ? ....

— Please set proper title and also format your code enclosing it within triple backticks.

Hi @amanohar,

The == operator can only return true when the two operands have identical types, and the type of [] alone (without any further type conversions) is an empty tuple rather than a list of strings and so I expect that comparison is always returning false.

If your goal is to use different behavior when the list is empty, test the length of the list instead:

length(var.k8s_api_server_authorized_ip_ranges) == 0 ? [var.k8s_api_server_authorized_ip_ranges] : concat([data.azurerm_public_ip.ss_perimeter_fw_ip.ip_address], var.k8s_api_server_authorized_ip_ranges, module.network_vars.q.az.global.access_lists.strict)

With that said, I do find your example a little confusing because you’ve said that in the case where the given list is empty the result should be a list containing only that empty list. I think that would therefore fail in a different way because the two arms of your conditional expression don’t agree about what the result type should be: in the true case it returns a list of lists while in the false case it returns a list of strings.

So considering both of those things and assuming that your goal was for this value to be just a plain empty list in the case where the given list is empty, perhaps the following:

  api_server_authorized_ip_ranges = (
    length(var.k8s_api_server_authorized_ip_ranges) == 0 ?
    [] :
    concat(
      [data.azurerm_public_ip.ss_perimeter_fw_ip.ip_address],
      var.k8s_api_server_authorized_ip_ranges,
      module.network_vars.q.az.global.access_lists.strict,
    )
  )
1 Like