terraform

Terraform output: how to get the first item from a container if any exists


The documentation of a Terraform provider says that I can get the value from a container in this way .identity[0] but in some cases identity is empty. How can I get the first element if at least one is in the container (otherwise null for example).

A error (and the errored line) met in actual case because of it:

Error: Invalid index
  on .../outputs.tf line 21, in output "container_registry_primary_identity_principal_id":
  21:     value = azurerm_container_registry.***.identity[0].principal_id
    ├────────────────
    │ azurerm_container_registry.***.identity is empty list of object
The given key does not identify an element in this collection value: the
collection has no elements.

Solution

  • You could maybe achieve what you want by using the try built-in function. Since you haven't added the entire output block, that should look something like the following:

    output "container_registry_primary_identity_principal_id" {
      value = try(azurerm_container_registry.***.identity[0].principal_id, null)
    }