AgentSkillsCN

terraform-functions

按类别整理 Terraform 内置函数的快速参考。适用于被问及“Terraform 函数”、常见函数(merge、concat、lookup、coalesce、length)或函数类别(数值、字符串、集合、编码、文件系统、日期/时间、IP 网络、类型转换、加密)时使用。

SKILL.md
--- frontmatter
name: terraform-functions
description: 'Quick reference for Terraform built-in functions organized by category. Use when asked about "terraform functions", common functions (merge, concat, lookup, coalesce, length) or function categories (numeric, string, collection, encoding, filesystem, date/time, IP network, type conversion, crypto).'

Terraform Functions Quick Reference

Comprehensive reference of all Terraform built-in functions organized by category. Use this skill to quickly identify which function to use for a specific task and where to find detailed documentation.

When to Use This Skill

  • User asks "what terraform functions are available"
  • Questions about function categories or groups
  • "How to manipulate strings/lists/maps in terraform"
  • Looking for the right function for a specific task
  • Need to know function signature or basic usage
  • Want to explore available functions by category

Function Overview

Terraform includes 100+ built-in functions that you can use in expressions. Functions transform and combine values.

General syntax:

hcl
function_name(arg1, arg2, ...)

Example:

hcl
locals {
  uppercase_name = upper(var.name)
  combined_list  = concat(var.list1, var.list2)
  json_data      = jsondecode(file("config.json"))
}

Testing functions: Use terraform console to experiment:

bash
$ terraform console
> upper("hello")
"HELLO"
> length([1, 2, 3])
3

Function Categories

Functions are organized into these categories:

  1. Numeric Functions - Mathematical operations
  2. String Functions - String manipulation
  3. Collection Functions - List, map, and set operations
  4. Encoding Functions - Encode/decode data formats
  5. Filesystem Functions - Read files and paths
  6. Date and Time Functions - Date/time manipulation
  7. Hash and Crypto Functions - Hashing and encryption
  8. IP Network Functions - CIDR and IP calculations
  9. Type Conversion Functions - Convert between types
  10. Validation Functions - Validate and test values
  11. Provider Functions - Provider-specific functions (Terraform provider)

Numeric Functions

Mathematical operations on numbers.

FunctionPurposeExampleDocumentation
abs(number)Absolute valueabs(-5) → 5abs
ceil(number)Round up to nearest integerceil(4.2) → 5ceil
floor(number)Round down to nearest integerfloor(4.8) → 4floor
log(number, base)Logarithmlog(16, 2) → 4log
max(number, ...)Maximum valuemax(5, 12, 9) → 12max
min(number, ...)Minimum valuemin(5, 12, 9) → 5min
parseint(string, base)Parse string to integerparseint("100", 10) → 100parseint
pow(base, exponent)Exponentiationpow(2, 3) → 8pow
signum(number)Sign of number (-1, 0, 1)signum(-5) → -1signum
sum(list)Sum of list elementssum([1, 2, 3]) → 6sum

String Functions

String manipulation and formatting.

FunctionPurposeExampleDocumentation
chomp(string)Remove trailing newlineschomp("hello\n") → "hello"chomp
endswith(string, suffix)Check if string ends with suffixendswith("hello", "lo") → trueendswith
format(spec, values...)Format string (printf-style)format("Hello, %s", "World")format
formatlist(spec, values...)Format each element in listsformatlist("ip-%s", ["a", "b"])formatlist
indent(spaces, string)Indent linesindent(4, "hello\nworld")indent
join(separator, list)Join list into stringjoin(",", ["a", "b"]) → "a,b"join
lower(string)Convert to lowercaselower("HELLO") → "hello"lower
regex(pattern, string)Match regex patternregex("[0-9]+", "abc123")regex
regexall(pattern, string)Find all regex matchesregexall("[0-9]+", "a1b2c3")regexall
replace(string, search, replace)Replace substringreplace("hello", "ll", "y")replace
split(separator, string)Split string into listsplit(",", "a,b,c") → ["a","b","c"]split
startswith(string, prefix)Check if string starts with prefixstartswith("hello", "he") → truestartswith
strcontains(string, substr)Check if string contains substringstrcontains("hello", "ll") → truestrcontains
strrev(string)Reverse stringstrrev("hello") → "olleh"strrev
substr(string, offset, length)Extract substringsubstr("hello", 1, 3) → "ell"substr
templatestring(template, vars)Render template stringtemplatestring("Hi ${name}", {name="World"})templatestring
title(string)Title casetitle("hello world") → "Hello World"title
trim(string, chars)Trim characters from both endstrim("!!hello!!", "!")trim
trimprefix(string, prefix)Remove prefixtrimprefix("helloworld", "hello")trimprefix
trimspace(string)Trim whitespacetrimspace(" hello ") → "hello"trimspace
trimsuffix(string, suffix)Remove suffixtrimsuffix("helloworld", "world")trimsuffix
upper(string)Convert to uppercaseupper("hello") → "HELLO"upper
urlencode(string)URL encodeurlencode("hello world")urlencode

Collection Functions

Operations on lists, maps, and sets.

FunctionPurposeExampleDocumentation
alltrue(list)Check if all elements are truealltrue([true, true]) → truealltrue
anytrue(list)Check if any element is trueanytrue([true, false]) → trueanytrue
chunklist(list, size)Split list into chunkschunklist([1,2,3,4], 2)chunklist
coalesce(values...)First non-null valuecoalesce(null, "a", "b") → "a"coalesce
coalescelist(lists...)First non-empty listcoalescelist([], ["a"], ["b"])coalescelist
compact(list)Remove empty strings from listcompact(["a", "", "b"]) → ["a","b"]compact
concat(lists...)Concatenate listsconcat([1,2], [3,4]) → [1,2,3,4]concat
contains(list, value)Check if list contains valuecontains(["a","b"], "a") → truecontains
distinct(list)Remove duplicatesdistinct([1,2,2,3]) → [1,2,3]distinct
element(list, index)Get element at index (wraps)element([1,2,3], 5) → 3element
flatten(list)Flatten nested listsflatten([[1,2],[3,4]]) → [1,2,3,4]flatten
index(list, value)Find index of valueindex(["a","b","c"], "b") → 1index
keys(map)Get map keyskeys({a=1, b=2}) → ["a","b"]keys
length(collection)Get lengthlength([1,2,3]) → 3length
list(values...)Create list (deprecated)list("a", "b")list
lookup(map, key, default)Get value from maplookup({a=1}, "a", 0) → 1lookup
map(key, value, ...)Create map (deprecated)map("a", 1, "b", 2)map
matchkeys(values, keys, searchset)Filter values by key matchesmatchkeys(values, keys, ["a"])matchkeys
merge(maps...)Merge mapsmerge({a=1}, {b=2})merge
one(list)Extract single element from listone([aws_instance.web])one
range(start?, limit, step?)Generate number sequencerange(3) → [0,1,2]range
reverse(list)Reverse listreverse([1,2,3]) → [3,2,1]reverse
setintersection(sets...)Set intersectionsetintersection([1,2], [2,3])setintersection
setproduct(sets...)Cartesian productsetproduct([1,2], ["a","b"])setproduct
setsubtract(a, b)Set differencesetsubtract([1,2,3], [2])setsubtract
setunion(sets...)Set unionsetunion([1,2], [2,3])setunion
slice(list, start, end)Extract sliceslice([1,2,3,4], 1, 3) → [2,3]slice
sort(list)Sort listsort(["c","a","b"]) → ["a","b","c"]sort
transpose(map)Transpose map of liststranspose({a=["1","2"]})transpose
values(map)Get map valuesvalues({a=1, b=2}) → [1,2]values
zipmap(keys, values)Create map from listszipmap(["a","b"], [1,2])zipmap

Encoding Functions

Encode and decode various data formats.

FunctionPurposeExampleDocumentation
base64decode(string)Decode base64base64decode("aGVsbG8=")base64decode
base64encode(string)Encode to base64base64encode("hello")base64encode
base64gzip(string)Gzip compress and base64 encodebase64gzip("hello")base64gzip
csvdecode(string)Parse CSV to list of mapscsvdecode("a,b\n1,2")csvdecode
jsondecode(string)Parse JSONjsondecode("{\"a\":1}")jsondecode
jsonencode(value)Encode to JSONjsonencode({a = 1})jsonencode
textdecodebase64(string, encoding)Decode base64 with encodingtextdecodebase64(str, "UTF-8")textdecodebase64
textencodebase64(string, encoding)Encode to base64 with encodingtextencodebase64(str, "UTF-8")textencodebase64
urlencode(string)URL encodeurlencode("hello world")urlencode
yamldecode(string)Parse YAMLyamldecode("a: 1\nb: 2")yamldecode
yamlencode(value)Encode to YAMLyamlencode({a = 1})yamlencode

Filesystem Functions

Read files and manipulate paths.

FunctionPurposeExampleDocumentation
abspath(path)Convert to absolute pathabspath("./file.txt")abspath
basename(path)Get filename from pathbasename("foo/bar.txt") → "bar.txt"basename
dirname(path)Get directory from pathdirname("foo/bar.txt") → "foo"dirname
file(path)Read file as stringfile("config.txt")file
filebase64(path)Read file as base64filebase64("image.png")filebase64
filebase64sha256(path)SHA256 hash of file (base64)filebase64sha256("file.txt")filebase64sha256
filebase64sha512(path)SHA512 hash of file (base64)filebase64sha512("file.txt")filebase64sha512
fileexists(path)Check if file existsfileexists("config.txt")fileexists
filemd5(path)MD5 hash of filefilemd5("file.txt")filemd5
fileset(path, pattern)Find files matching patternfileset(".", "*.txt")fileset
filesha1(path)SHA1 hash of filefilesha1("file.txt")filesha1
filesha256(path)SHA256 hash of filefilesha256("file.txt")filesha256
filesha512(path)SHA512 hash of filefilesha512("file.txt")filesha512
pathexpand(path)Expand ~ in pathpathexpand("~/file.txt")pathexpand
templatefile(path, vars)Render template filetemplatefile("tpl.txt", {name="x"})templatefile

Date and Time Functions

Date and time manipulation.

FunctionPurposeExampleDocumentation
formatdate(format, timestamp)Format timestampformatdate("YYYY-MM-DD", timestamp())formatdate
plantimestamp()Current timestamp (plan time)plantimestamp()plantimestamp
timeadd(timestamp, duration)Add duration to timestamptimeadd(timestamp(), "1h")timeadd
timecmp(a, b)Compare timestampstimecmp(t1, t2) → -1/0/1timecmp
timestamp()Current timestamp (UTC)timestamp() → "2024-01-20T10:30:00Z"timestamp

⚠️ Note: timestamp() is evaluated every time Terraform runs, causing perpetual differences. Use plantimestamp() for consistent plan-time timestamps.


Hash and Crypto Functions

Hashing and cryptographic operations.

FunctionPurposeExampleDocumentation
base64sha256(string)SHA256 hash (base64)base64sha256("hello")base64sha256
base64sha512(string)SHA512 hash (base64)base64sha512("hello")base64sha512
bcrypt(string, cost?)Generate bcrypt hashbcrypt("password", 10)bcrypt
md5(string)MD5 hashmd5("hello")md5
rsadecrypt(ciphertext, key)RSA decryptrsadecrypt(encrypted, private_key)rsadecrypt
sha1(string)SHA1 hashsha1("hello")sha1
sha256(string)SHA256 hashsha256("hello")sha256
sha512(string)SHA512 hashsha512("hello")sha512
uuid()Generate UUIDuuid() → "b5ee72a3-..."uuid
uuidv5(namespace, name)Generate UUID v5uuidv5("dns", "example.com")uuidv5

⚠️ Note: uuid() generates a new value each run, causing perpetual differences. Use only when necessary (e.g., with lifecycle ignore_changes).


IP Network Functions

CIDR and IP address calculations.

FunctionPurposeExampleDocumentation
cidrhost(prefix, hostnum)Calculate IP addresscidrhost("10.0.0.0/24", 5)cidrhost
cidrnetmask(prefix)Get netmask from CIDRcidrnetmask("10.0.0.0/24")cidrnetmask
cidrsubnet(prefix, newbits, netnum)Calculate subnetcidrsubnet("10.0.0.0/16", 8, 1)cidrsubnet
cidrsubnets(prefix, newbits...)Calculate multiple subnetscidrsubnets("10.0.0.0/16", 8, 8)cidrsubnets

Type Conversion Functions

Convert values between types.

FunctionPurposeExampleDocumentation
can(expression)Test if expression succeedscan(regex("^[0-9]+$", var.input))can
tobool(value)Convert to booleantobool("true") → truetobool
tolist(value)Convert to listtolist(toset([1,2,3]))tolist
tomap(value)Convert to maptomap({a = 1, b = 2})tomap
tonumber(value)Convert to numbertonumber("42") → 42tonumber
toset(value)Convert to settoset([1, 2, 2, 3])toset
tostring(value)Convert to stringtostring(42) → "42"tostring
try(expressions...)Return first successful expressiontry(var.x, "default")try
type(value)Get type of valuetype([1,2]) → "list"type

Validation and Testing Functions

Validate values and test conditions.

FunctionPurposeExampleDocumentation
can(expression)Test if expression succeedscan(regex("^ami-", var.ami_id))can
ephemeralasnull(value)Convert ephemeral to nullephemeralasnull(ephemeral.value)ephemeralasnull
issensitive(value)Check if value is sensitiveissensitive(var.password)issensitive
nonsensitive(value)Remove sensitive markingnonsensitive(sensitive_value)nonsensitive
sensitive(value)Mark value as sensitivesensitive(var.api_key)sensitive
try(expressions...)Return first successful expressiontry(var.x, var.y, "default")try

Provider-Defined Functions (Terraform Provider)

Built-in provider-specific functions from the terraform provider.

FunctionPurposeExampleDocumentation
provider::terraform::applying()Check if currently applyingprovider::terraform::applying()applying
provider::terraform::decode_tfvars(string)Parse tfvars formatprovider::terraform::decode_tfvars(file("vars.tfvars"))decode_tfvars
provider::terraform::encode_expr(value)Encode to Terraform expressionprovider::terraform::encode_expr({a = 1})encode_expr
provider::terraform::encode_tfvars(value)Encode to tfvars formatprovider::terraform::encode_tfvars({a = 1})encode_tfvars

Note: Provider-specific functions use the provider::<name>::<function> syntax and require the provider to be declared in required_providers.


Common Usage Patterns

String Manipulation

hcl
# Normalize naming
locals {
  normalized_name = lower(replace(var.name, "_", "-"))
  env_upper       = upper(var.environment)
}

# Template rendering
locals {
  user_data = templatefile("${path.module}/user-data.sh", {
    region      = var.region
    environment = var.environment
  })
}

Collection Operations

hcl
# Merge configurations
locals {
  default_tags = {
    Environment = var.environment
    ManagedBy   = "Terraform"
  }

  all_tags = merge(local.default_tags, var.additional_tags)
}

# Filter and transform
locals {
  public_subnets = [
    for subnet in var.subnets : subnet.id
    if subnet.public == true
  ]
}

# Safely access with one()
locals {
  bucket = try(one(aws_s3_bucket.logs), null)
}

File and Path Operations

hcl
# Read configuration files
locals {
  config = jsondecode(file("${path.module}/config.json"))

  ssl_cert = fileexists("${path.module}/cert.pem") ?
    file("${path.module}/cert.pem") : null
}

# Hash for change detection
resource "aws_s3_object" "config" {
  bucket = aws_s3_bucket.config.id
  key    = "config.json"
  source = "${path.module}/config.json"
  etag   = filemd5("${path.module}/config.json")
}

Type Conversion and Validation

hcl
# Safe type conversion
locals {
  port = can(tonumber(var.port)) ? tonumber(var.port) : 8080
}

# Validation with can()
variable "ami_id" {
  type = string

  validation {
    condition     = can(regex("^ami-[a-f0-9]{8,}$", var.ami_id))
    error_message = "AMI ID must be valid format (ami-xxxxxxxx)."
  }
}

# Try with fallbacks
locals {
  db_endpoint = try(
    aws_db_instance.primary.endpoint,
    aws_db_instance.replica.endpoint,
    "localhost:5432"
  )
}

Network Calculations

hcl
# Calculate subnets
locals {
  vpc_cidr = "10.0.0.0/16"

  # Create /24 subnets
  subnet_cidrs = cidrsubnets(local.vpc_cidr, 8, 8, 8, 8)

  # Calculate specific IPs
  nat_gateway_ip = cidrhost(local.subnet_cidrs[0], 5)
}

Finding More Information

Official Documentation:

Testing Functions:

bash
# Interactive console
terraform console

# Example session
> upper("hello")
"HELLO"

> cidrsubnet("10.0.0.0/16", 8, 1)
"10.0.1.0/24"

> merge({a = 1}, {b = 2})
{
  "a" = 1
  "b" = 2
}

Getting Function Signatures:

bash
# List all functions with signatures (Terraform v1.4+)
terraform metadata functions -json

Best Practices

Do's

Use descriptive variable names when using complex function chains

hcl
# Good
locals {
  normalized_bucket_name = lower(replace(var.bucket_name, "_", "-"))
}

# Avoid
locals {
  bn = lower(replace(var.bn, "_", "-"))
}

Use try() for safe access to potentially null values

hcl
# Good
locals {
  container_memory = try(var.container_definitions[0].memory, 512)
}

Use can() for validation

hcl
# Good validation
validation {
  condition     = can(regex("^[a-z0-9-]+$", var.name))
  error_message = "Name must contain only lowercase letters, numbers, and hyphens."
}

Use one() for count-based resources

hcl
# Good
output "bucket_id" {
  value = try(one(aws_s3_bucket.optional).id, null)
}

Test functions in terraform console before using

Don'ts

Don't use uuid() or timestamp() without lifecycle ignore_changes

hcl
# Bad - causes perpetual diff
resource "random_id" "example" {
  keepers = {
    timestamp = timestamp()  # Changes every run!
  }
}

# Good - use plantimestamp() or ignore_changes
resource "random_id" "example" {
  keepers = {
    timestamp = plantimestamp()  # Consistent during plan
  }
}

Don't over-nest function calls - use locals for clarity

hcl
# Bad - hard to read
resource "aws_s3_bucket" "example" {
  bucket = lower(replace(trimspace(var.name), "_", "-"))
}

# Good - clear steps
locals {
  cleaned_name     = trimspace(var.name)
  normalized_name  = replace(local.cleaned_name, "_", "-")
  bucket_name      = lower(local.normalized_name)
}

resource "aws_s3_bucket" "example" {
  bucket = local.bucket_name
}

Don't use file() for large files - consider alternatives

hcl
# Bad for large files
locals {
  large_config = jsondecode(file("large-config.json"))
}

# Consider: use data sources or external systems for large configs

Don't use deprecated functions (list(), map())

hcl
# Bad - deprecated
locals {
  items = list("a", "b", "c")
  config = map("key", "value")
}

# Good - use literal syntax
locals {
  items = ["a", "b", "c"]
  config = { key = "value" }
}

Quick Reference Summary

Total Functions: 100+ built-in functions

Categories:

  • Numeric (10) - Math operations
  • String (23) - Text manipulation
  • Collection (30) - Lists, maps, sets
  • Encoding (11) - JSON, YAML, CSV, Base64
  • Filesystem (15) - Files and paths
  • Date/Time (5) - Timestamps and formatting
  • Hash/Crypto (10) - Hashing and encryption
  • IP Network (4) - CIDR calculations
  • Type Conversion (9) - Type conversions
  • Validation (6) - Testing and validation
  • Provider (4) - Terraform provider functions

Most Commonly Used:

  • try() - Safe value access
  • merge() - Merge maps
  • concat() - Combine lists
  • length() - Get collection size
  • lookup() - Map value with default
  • jsondecode() / jsonencode() - JSON handling
  • file() - Read files
  • templatefile() - Template rendering
  • cidrsubnet() - Subnet calculations
  • one() - Extract single element

Documentation: https://developer.hashicorp.com/terraform/language/functions