Function calls and console literacy
A function turns inputs into a result
A Terraform function computes a value inside an expression. For example, length(["search", "catalog"]) produces 2. It does not create two resources. Arguments go inside parentheses; commas separate them. A result can feed a local value, an output or another function. In this chapter, all examples use synthetic data and predicted results; they have not been executed.
Build a useful configuration summary
Combine defaults and overrides, count ports and turn service names into a label. Save the following in a fresh local lab directory, not an existing project:
locals { tags = merge({ team = "web", env = "test" }, { env = "stage" }) ports = concat([8080], [8081, 8082]) groups = flatten([["search"], ["catalog", "report"]])}output "summary" { value = { tags = local.tags count = length(local.ports) services = join(", ", local.groups) }}Predicted summary: tags contain team = "web" and env = "stage"; count = 3; services = "search, catalog, report". merge resolves a repeated key using the later input, concat joins sequences without recursively flattening them, and flatten removes directly nested sequence layers. Merge is shallow: a later nested object replaces the earlier value at that key, rather than recursively merging its fields.
Practice with the expression console
Use an approved Terraform binary matching the lab version, in an isolated directory with no providers, external data sources or remote backend. Run terraform console, enter one expression at a time, and type exit when finished. Do not copy prompts into expressions. The console uses configuration and state, can lock state, and its plan mode can invoke provider operations; do not experiment in a production directory. These independent expressions have predicted results:
length(["api", "db"])join("-", ["shop", "test"])split("-", "shop-test")format("worker-%02d", 3)merge([{ app = "shop" }, { env = "test" }]...)Results: 2, "shop-test", ["shop", "test"], "worker-03", and an object with app and env keys. The ... expands a sequence into separate function arguments; this is different from the grouping marker in a for expression. length counts collection elements or string characters (Unicode grapheme clusters), not UTF-8 bytes.
Read and reshape collections
Use these independent expressions to explore the input and result types:
keys({ west = 2, east = 1 })values({ west = 2, east = 1 })toset(["api", "api", "db"])flatten([[1, 2], [], [3]])concat([1, 2], [3])Predicted results: ["east", "west"], [1, 2], a set containing api and db (no positional contract), [1, 2, 3], [1, 2, 3]. Keys and values use corresponding lexical key order. flatten does not recurse through intervening map/object attributes. For an ordered display of a string set, explicitly sort it.
Calculate a subnet without provisioning one
CIDR notation identifies a network prefix. Adding two bits to /24 yields four /26 subnets, numbered zero through three. The second begins at address .64. The following fixture only computes strings:
locals { subnet = cidrsubnet("192.0.2.0/24", 2, 1)}output "subnet" { value = local.subnet}output "host" { value = cidrhost(local.subnet, 5)}Predicted subnet = "192.0.2.64/26" and host = "192.0.2.69". The host index is relative to the selected subnet. The prefix is reserved for documentation. These functions do not create networks, reserve addresses, check cloud-specific reserved addresses or detect conflicts with existing networks. A subnet index of 4 cannot fit into two new bits.
Choose predictable functions and read errors
Numeric, string, collection, encoding, conversion and IP functions are useful categories. Some calls depend on files or execution time; for example, file-reading functions need an existing file, and timestamp-related values need not be stable between runs. Keep beginner tests on fixed inputs. Unknown values may propagate when a result depends on them; a known collection length can sometimes be computed even if its elements are unknown. Sensitive values can taint derived results; a function is not a declassification mechanism. Check argument count, type and domain when a call fails. The next lesson distinguishes a missing key from an invalid value.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Function calls and console literacy — knowledge check
Check function evaluation and input contracts.
What does merge({env="test"}, {env="stage"}) produce?
What does length(["a", "b"]) return?
What does the ... in merge(local.maps...) do?
Which prefix is returned by cidrsubnet("192.0.2.0/24", 2, 1)?
Does cidrhost reserve an address in a cloud network?