Terraform’s contains function checks whether a value exists inside a list, tuple, or set, returning true or false. It’s one of the most commonly used collection functions in HCL, useful for variable validation, conditional resource creation with count, and any logic that depends on whether something is in or out of a defined set.
It’s also frequently confused with strcontains, a separate string function added in Terraform 1.5 that checks whether a substring appears inside a string.
In this article, we will look at the contains function in Terraform, explain what it is and what it does, and share some practical examples using lists and strings.
What is the Terraform contains function?
In Terraform, the contains function is used to check if a specified value exists within a given list or set. This function returns true if the value is found and false otherwise. The function is categorized as a ‘collection’ function. The contains function is especially useful when you need to make decisions based on the contents of a list or set.
The syntax of Terraform contains function is as follows:
contains(list, value)list— The list, tuple, or set to search within.value— The value to search for. Must be comparable to the elements in the collection using the same equality rules as the==operator (so types must match, e.g.,contains(["1", "2"], 1)returnsfalsebecause the list holds strings and the value is a number).
Returns: true if at least one element in the collection equals value, otherwise false.
Read more about Terraform functions, expressions, and loops.
How to use Terraform contains - examples
In this example, Terraform contains function is given a list and, after the comma, the value to search for. If the value exists, the function returns true.
Because darth is in the first list, it returns true.
contains(["darth", "luke", "yoda"], "darth")
# trueIn the second example because jarjar is not in the list, the function returns false.
contains(["darth", "luke", "yoda"], "jarjar")
# falseType matching matters
contains uses the same equality rules as the == operator, so the value’s type must match the elements in the collection. Mismatched types return false, not an error:
contains(["1", "2", "3"], 1)
# false — list holds strings, value is a number
contains([1, 2, 3], 1)
# trueIf you’re getting unexpected false results, this is almost always why.
Check if a key exists in a map
contains does not accept a map directly. Wrap it with keys() instead:
variable "tags" {
type = map(string)
default = {
Environment = "prod"
Owner = "platform-team"
}
}
output "has_owner_tag" {
value = contains(keys(var.tags), "Owner")
# true
}Real-world example: validate an Azure VM size against a region
One good practical use of the contains function is to check if a particular virtual machine size is supported in a specific Azure region before deploying it. You can use contains to check if the desired VM size is present in the list of available sizes for that region.
provider "azurerm" {
features {}
}
variable "region" {
description = "Azure region"
type = string
default = "uksouth"
}
variable "vm_size" {
description = "VM size"
type = string
default = "Standard_DS2_v2"
}
data "azurerm_virtual_machine_sizes" "example" {
location = var.region
}
output "vm_size_supported" {
value = contains(data.azurerm_virtual_machine_sizes.example.sizes, var.vm_size)
}If vm_size_supported is false, you can fail early or fall back to a default rather than waiting for the API to reject the deploy.
What is Terraform strcontains function?
Similar to the contains function, the Terraform strcontains function checks whether a substring is within another string. This function is categorized as a ‘String’ function. The strcontains function is useful for string manipulations and conditional logic based on string data.
Syntax of the Terraform strcontains function:
strcontains(string, substr)string— The string to search within for the substring.substr— The value to search for within the main string.
Learn more: Terraform Strings: Interpolation, Multiline & Built-in Functions
How to use Terraform strcontains - examples
In this example, given the first string specified as “darth” we check for the substring within it “dar”. Because it exists, the Terraform strcontains function returns true.
strcontains("darth", "dar")
trueIn this second example, we check using the strcontains function for the substring “yoda” within the word “darth”. Because it is not contained within the string, it returns false.
> strcontains("darth", "yoda")
falseWhat is the difference between contains and strcontains in Terraform?
The two functions sound similar but operate on completely different data types.
contains is a collection function. It takes a list, tuple, or set as its first argument and returns true if any element equals the value you pass as the second. It uses the same strict equality as the == operator, so contains([1, 2], "1") is false because the types don’t match.
strcontains, added in Terraform 1.5, is a string function. It takes a string as its first argument and returns true if the substring you pass appears anywhere inside it.
Both return a boolean, and both are case-sensitive.
The most common mistake is swapping them. Calling contains("hello world", "hello") or strcontains(["hello", "world"], "hello") will both fail with an “Invalid function argument” error.
If you’re searching inside a collection of values, use contains. If you’re searching for text inside a single string, use strcontains. To do both at once (e.g., “does any item in this list contain ‘prod’?”), combine them:
anytrue([for n in local.names : strcontains(n, "prod")])Key points
The Terraform contains function is used to check if a specified value exists within a given list or set. And Terraform strcontains function checks whether a substring is within another string.
Terraform is really powerful, but to achieve an end-to-end secure GitOps approach, you need a platform that can orchestrate your infrastructure workflows. Spacelift is the infrastructure orchestration platform built for the AI-accelerated software era. It manages the full lifecycle for both traditional infrastructure as code and AI-provisioned infrastructure, giving you access to features such as:
- Policies (based on Open Policy Agent)
- Multi-IaC workflows (Terraform, OpenTofu, CloudFormation, Pulumi, Ansible, and Kubernetes)
- Self-service infrastructure via Blueprints and Templates
- AI-powered provisioning, diagnostics, and operational insight with Spacelift Intelligence
- Integrations with any third-party tools
If you want to learn more about Spacelift, create a free account today or book a demo with one of our engineers.
Note: New versions of Terraform are placed under the BUSL license, but everything created before version 1.5.x stays open-source. OpenTofu is an open-source version of Terraform that expands on Terraform’s existing concepts and offerings. It is a viable alternative to HashiCorp’s Terraform, being forked from Terraform version 1.5.6.
Manage Terraform better with Spacelift
Build more complex workflows based on Terraform using policy as code, programmatic configuration, context sharing, drift detection, resource visualization and many more.
Frequently asked questions
What are some useful collection functions in Terraform?
Collection functions in Terraform help manipulate lists, maps, and sets efficiently. Common ones include:
- flatten() to reduce nested lists into a single list
- merge() to combine multiple maps into one
- lookup() to safely retrieve values from a map with a default fallback
- keys() and values() to extract map keys or values as lists
- distinct() to remove duplicates from a list
- zipmap() to create a map from two lists (keys and values)
- chunklist() to split a list into evenly sized sublists
Is Terraform strcontains case-sensitive?
Yes, strcontains is case-sensitive. It performs an exact substring match, so strcontains(“Hello”, “hello”) returns false. For case-insensitive checks, normalize both strings with lower() first, for example strcontains(lower(var.name), lower(“optimal”)).
How do I check if a Terraform list contains multiple values at once?
To check whether a list contains multiple values, combine contains calls with alltrue (all must be present) or anytrue (any one suffices), like alltrue([for v in [“a”, “b”] : contains(var.list, v)]). This works because contains only accepts a single search value per call.
Does contains work in OpenTofu, and when was strcontains added?
Yes, both contains and strcontains work in OpenTofu, since it was forked from Terraform 1.5.6.
