Skip to content

Function contains()

📝 Description

The contains function determines whether a given list contains a specific value. It returns true if the value is found, and false otherwise.

Use Case: Validating input variables, controlling resource creation based on environment types, or checking if a tag exists in a list of mandatory tags.


💻 Syntax

contains(list, value)

💡 Examples

1. Basic Membership Check:

# Result: true
output "is_present" {
  value = contains(["dev", "stg", "prod"], "prod")
}

2. Conditional Resource Creation:

Imagine you only want to enable detailed monitoring in specific environments.

variable "env" { default = "dev" }

locals {
  allowed_envs = ["prod", "staging"]
  # Result: false (because "dev" is not in the list)
  enable_monitoring = contains(local.allowed_envs, var.env)
}

3. IP Whitelist Validation:

variable "user_ip" { default = "1.1.1.1" }
locals {
  admin_ips = ["1.1.1.1", "8.8.8.8"]
  is_admin  = contains(local.admin_ips, var.user_ip) # Result: true
}

⚠️ Key Details

  • Types Matter: If you have a list of numbers [1, 2, 3], checking for a string "1" will return false.

  • Exact Match: It looks for an exact match. It won't find "prod" inside a string like "production".

  • Lists Only: It does not work directly on maps (for maps, use keys() first to get a list of keys).


  • [[keys]] — Use this if you want to check if a key exists in a map: contains(keys(map), "mykey").

  • [[distinct]] — Remove duplicates before or after checks.

  • Official HashiCorp Docs