Function distinct()
📝 Description
The distinct function takes a list and returns a new list with all duplicate elements removed, keeping only the first occurrence of each element.
Use Case: Cleaning up lists of CIDR blocks, removing redundant tags, or ensuring that a load balancer doesn't try to register the same target ID twice.
💻 Syntax
💡 Examples
1. Basic De-duplication:
2. Cleaning up IP Whitelists:
Imagine you merge two lists of IPs and want to remove overlaps.
locals {
office_ips = ["1.1.1.1", "2.2.2.2"]
vpn_ips = ["2.2.2.2", "3.3.3.3"]
# Result: ["1.1.1.1", "2.2.2.2", "3.3.3.3"]
all_unique_ips = distinct(concat(local.office_ips, local.vpn_ips))
}
3. Practical Scenario: Security Groups
If several modules output the same Security Group ID, distinct ensures your instance resource only receives a clean, unique list.
⚠️ Key Details
-
Order Preservation:
distinctkeeps the elements in the order they first appeared. -
Types Matter: Just like
contains(), it treats the number1and the string"1"as different elements. -
Empty Lists: If the input list is empty, it returns an empty list without error.
🔗 Related Functions
-
[[concat]] — Combine multiple lists before calling
distinct. -
[[flatten]] — Use this before
distinctif you are dealing with nested lists.