Skip to navigation

Functions

Rivet includes most of Terraform’s built-in functions, minus those that depend on the clock, randomness, or the environment. Functions run during compilation, and only their results go into the bundle. Rivet implements its own HCL subset, not the full Terraform language, so some functions behave slightly differently; the notes below and the family pages list the differences.

Supported functions

FamilyFunctions
Numericabs, ceil, floor, log, max, min, parseint, pow, signum
Stringchomp, endswith, format, formatlist, indent, join, lower, regex, regexall, replace, split, startswith, strcontains, strrev, substr, templatestring, title, trim, trimprefix, trimsuffix, trimspace, upper
Collectionalltrue, anytrue, chunklist, coalesce, coalescelist, compact, concat, contains, distinct, element, flatten, index, keys, length, lookup, matchkeys, merge, one, range, reverse, setintersection, setproduct, setsubtract, setunion, slice, sort, sum, transpose, values, zipmap
Encodingbase64decode, base64encode, base64gzip, csvdecode, jsondecode, jsonencode, textdecodebase64, textencodebase64, urlencode, yamldecode, yamlencode
Filesystemabspath, basename, dirname, file, filebase64, fileexists, fileset, templatefile
Date/timeformatdate, timeadd, timecmp
Hash/cryptobase64sha256, base64sha512, filebase64sha256, filebase64sha512, filemd5, filesha1, filesha256, filesha512, md5, rsadecrypt, sha1, sha256, sha512, uuidv5
IP networkcidrhost, cidrnetmask, cidrsubnet, cidrsubnets
Conversion/sensitivitycan, convert, issensitive, nonsensitive, sensitive, tobool, tolist, tomap, tonumber, toset, tostring, try

The family references below give each function’s signature. Errors from wrong argument counts or types, or unknown functions, report the source location without printing argument values.

Functions can be nested and used in locals, resource attributes, and outputs. Collection results can be indexed or traversed, for example jsondecode(file("settings.json")).name. Final argument expansion works for ordinary functions: max([1, 2, 3]...). try and can require explicit expressions.

locals {
settings = merge({ port = 8080 }, { address = cidrhost("192.0.2.0/24", 10) })
}
file "settings" {
path = "/etc/example/settings.json"
content = jsonencode(local.settings)
}
output "address" {
type = string
value = try(local.settings.address, "192.0.2.1")
}

Values and compatibility

  • Integers use signed 64-bit storage. Fractional expression literals and numerical results use finite IEEE 754 double precision. This is not Terraform’s arbitrary-precision arithmetic. Integer abs, min, max, ceil, floor, parseint, integer-only range, and integer-only sum retain integer precision; overflow is rejected. Fractional values remain invalid for integer resource fields. Declared variable defaults accept literal scalars and collections.
  • Rivet has lists, sets, and string-keyed maps with typed collection inputs/outputs. toset and set operations return deterministic deduplicated sets. tolist, tomap, toset, and coalesce unify primitive elements, converting numbers and booleans to strings when a string is present and rejecting incompatible mixtures. Nested collections retain Rivet’s existing shapes rather than implementing Terraform’s full implicit type unification. Other function arguments retain Rivet’s strict types.
  • convert(value, type) accepts string, number, bool, any, list(T), set(T), map(T), tuple([T, ...]), and object({ field = T, ... }). Object fields can use optional(T) or optional(T, default); extra object attributes are discarded, and missing required fields fail. Constraints are validated even for null or empty values, and defaults are evaluated and converted once per constraint before reuse. Parsed constraints, including stored defaults, obey the byte and node bounds below. These constructors are accepted as conversion constraints; they do not extend variable and output declarations.
  • length, substr, and strrev operate on Unicode grapheme clusters. Casing and whitespace use Rust’s Unicode behavior. replace(text, from, to) is literal unless from is slash-delimited, in which case it is a regex. regex/regexall return a string without capture groups, a list with unnamed groups, or a map with named groups. Mixed capture styles fail. Patterns use Rust’s bounded regex engine, with no look-around or backreferences; its Unicode character classes can differ from Terraform’s RE2 engine.
  • format/formatlist support Terraform’s documented verbs (v, #v, t, b, d, o, x, X, e, E, f, g, G, s, q), argument positions, width, precision, and sign/alignment/zero-padding flags. Formatting is bounded; floating-point rounding follows Rust’s implementation.
  • JSON uses compact encoding with Terraform-style HTML/line-separator escaping. YAML supports a single document of finite JSON-compatible values with string keys; duplicate keys, unsupported tags, cycles, excessive alias expansion, and excessive depth fail. YAML formatting and gzip bytes can differ from Terraform while decoding to the same values. CSV requires unique headers and consistently sized records.
  • Text/base64 functions use NFC normalization. Named encodings use encoding_rs’s supported labels; UTF-16LE/BE are also supported for encoding. Unsupported encodings and lossy conversions fail.
  • CIDR functions accept IPv4 and IPv6; cidrnetmask accepts only IPv4. Host/subnet indices use signed 64-bit arguments. formatdate accepts Terraform’s explicit date tokens and quoted literals; timeadd accepts signed combinations of h, m, s, ms, us, µs, μs, and ns. Timestamps must be RFC 3339. No function reads the current clock.
  • uuidv5 accepts a UUID namespace or dns, url, oid, x500. rsadecrypt accepts base64 PKCS#1 v1.5 ciphertext and an unencrypted PKCS#1/PKCS#8 PEM RSA key, up to 8192 bits/16 KiB. Decrypted results are intrinsically sensitive.

Family references

Templates and local reads

Templates support heredocs, interpolation, conditionals, loops, strip markers, and templatefile and templatestring with their own variables. Filesystem functions stay confined to the declaring source root. Reads and rendering happen on the controller; the resulting content enters the bundle.

Provenance and limits

Functions preserve resource dependencies and conservatively propagate sensitivity, including overwritten map values and failed try/can attempts. Elements retain their annotations. keys uses container and key sensitivity, so public map keys can stay public when only the values are sensitive. issensitive returns a public boolean; nonsensitive explicitly removes sensitivity recursively while retaining dependencies.

Each value or text read or rendered result is limited to 16 MiB and each value to 100,000 nodes. Syntax, decoding, evaluation, rendering, and conversion depth are limited to 128; the syntax guard also caps operator chains. Template loops and for expressions share a compilation-wide 100,000-iteration budget. fileset inspects at most 100,000 entries, and range emits at most 1024 values. Construction and decoding enforce limits before excessive expansion. Recursive template-file inclusion fails.

Plugin functions

Approved subprocess plugins add deterministic functions through plugin::ALIAS::NAME(...). The alias selects a locally approved installation. An optional plugin "ALIAS" block checks its literal source and version requirement against that selection.

output "name" {
type = string
value = plugin::example::slug("Web API")
}

The plugin supplies typed parameter and result schemas. Calls run during compilation and preserve typed collections, resource handles, null, all argument dependencies, and nested sensitivity. A plugin can add sensitivity but cannot declassify arguments. Only evaluated results enter the bundle; function-only plugins need no executable on the managed target. Plugin compositions record their selected identities in the catalog.

Plugin functions must not read files, environment variables, the clock, randomness, or the network. They can’t override built-in functions.

Unsupported functions and syntax

Excluded functions are timestamp, plantimestamp, uuid, and bcrypt (they depend on the clock or randomness), pathexpand (depends on the home directory), ephemeralasnull, type, the deprecated list and map, and namespaced provider::... calls.