Skip to content

Functions keys() & values()

📝 Description

  • keys: Takes a map and returns a list containing all the keys in that map, sorted lexicographically (alphabetically).

  • values: Takes a map and returns a list containing all the values in that map, in the same order as the keys.

Use Case: Creating dynamic lists for security groups, generating documentation from your variables, or simply checking which environments are defined in your configuration.


💻 Syntax

keys(map)
values(map)

💡 Examples

1. Extracting Keys (Names):

variable "environments" {
  default = {
    "prod" = "10.0.1.0/24"
    "dev"  = "10.0.2.0/24"
    "stg"  = "10.0.3.0/24"
  }
}

# Result: ["dev", "prod", "stg"] (Sorted alphabetically!)
output "env_names" {
  value = keys(var.environments)
}

2. Extracting Values (Data):

# Result: ["10.0.2.0/24", "10.0.1.0/24", "10.0.3.0/24"]
output "env_cidrs" {
  value = values(var.environments)
}

3. Practical Scenario: Loops and Validation

You can use keys() to check if a specific key exists before doing something complex:

locals {
  has_prod = contains(keys(var.environments), "prod")
}

⚠️ Key Details

  • Sorting: keys() always sorts the result alphabetically. This is important for "stable" Terraform runs (чтобы порядок не прыгал при каждом запуске).

  • Sync: values() всегда возвращает список в том же порядке, что и keys(). Если первый ключ — "dev", то первое значение в списке values() будет именно от "dev".