Lookup on Terraform

Basic Syntax of the Lookup Function

lookup(map name, key, default_value)

Based on the above syntax, the lookup function has three primary arguments.

  1. Map name: A map variable that contains the key-value pairs.
  2. Key: A key value that we want to retrieve from the map
  3. Default value: A default value that we intend to return if the map doesn’t contain the key.

Example-1

variable "env" { // key
  default = "test"
}

variable "allow_port" { // map 
  default = {
    prod = ["80", "443"]
    rest = ["80", "443", "8080", "22"]
  }
}
 
  dynamic "ingress" {
    for_each = lookup(var.allow_port, var.env, var.allow_port["rest"])
    content {
      from_port   = ingress.value
      to_port     = ingress.value
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    }
  }

Example-2

# AMI Collection Map
variable “ami_collection” {
    type = map(string)
  default = {
    “ubuntu” = “ami-00ae935ce6c2aa534”
    “amazon_linux” = “ami-00ae935ce6c2aa534”
    “rhel_sql” = “ami-0fd0947c3f88732f8”
    “windows_server_2019” = “ami-00ae935ce6c2aa534”
    “windows_server_2022” = “ami-0f96fbe09adbebdc9”
 }
}
# Selecting a available key (ubuntu)
output “select_ami” {
    value = lookup(var.ami_collection, “ubuntu”, “ami-0de899d345371c9aa”)
}
# Selecting an unavailable key
output “select_ami_default” {
    value = lookup(var.ami_collection, “ubuntu_server”, “ami-0de899d345371c9aa”)
}

Bir cevap yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir