Fonctions et expressions 18 min de lecture

Fonctions Terraform essentielles

Fonctions de chaines

locals {
  name       = "Mon-Serveur"
  lower_name = lower(local.name)       # "mon-serveur"
  upper_name = upper(local.name)       # "MON-SERVEUR"
  trimmed    = trimspace("  hello  ")  # "hello"
  replaced   = replace("hello-world", "-", "_") # "hello_world"
  formatted  = format("server-%03d", 1)  # "server-001"
  joined     = join("-", ["web", "prod", "01"]) # "web-prod-01"
  split_list = split(",", "a,b,c")     # ["a", "b", "c"]
}

Fonctions de collections

locals {
  list1  = ["a", "b", "c"]
  list2  = ["c", "d", "e"]

  merged    = concat(local.list1, local.list2)  # ["a","b","c","c","d","e"]
  unique    = distinct(concat(local.list1, local.list2)) # ["a","b","c","d","e"]
  has_item  = contains(local.list1, "b")        # true
  length    = length(local.list1)               # 3
  element   = element(local.list1, 0)           # "a"
  flattened = flatten([["a","b"],["c","d"]])     # ["a","b","c","d"]

  map1   = { a = 1, b = 2 }
  map2   = { b = 3, c = 4 }
  merged_maps = merge(local.map1, local.map2)   # { a=1, b=3, c=4 }
  keys   = keys(local.map1)                     # ["a", "b"]
  values = values(local.map1)                   # [1, 2]
  lookup_val = lookup(local.map1, "a", 0)       # 1
}

Fonctions de fichiers

locals {
  user_data = file("scripts/init.sh")
  template  = templatefile("templates/config.tpl", {
    db_host = "localhost"
    db_port = 5432
  })
}

Fonctions de type et conversion

locals {
  as_number = tonumber("42")    # 42
  as_string = tostring(42)      # "42"
  as_list   = tolist(toset(["a","b","a"])) # ["a","b"]
}
Astuce : Testez les fonctions dans terraform console avant de les utiliser dans votre code.