Terraform 内置函数 #

函数概述 #

Terraform 提供了丰富的内置函数,用于处理和转换数据。这些函数可以在表达式中使用,帮助你构建更灵活的配置。

text
┌─────────────────────────────────────────────────────────────┐
│                    函数分类                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  数值函数     abs, ceil, floor, max, min...                │
│  字符串函数   join, split, lower, upper, format...         │
│  集合函数     length, contains, merge, keys, values...     │
│  编码函数     jsonencode, base64encode, yamlencode...      │
│  文件函数     file, fileexists, templatefile...            │
│  日期函数     timestamp, formatdate, timeadd...            │
│  加密函数     md5, sha256, bcrypt, rsadecrypt...           │
│  网络函数     cidrhost, cidrsubnet, cidrnetmask...         │
│  类型函数     tolist, tomap, toset, tostring...           │
│                                                             │
└─────────────────────────────────────────────────────────────┘

数值函数 #

abs #

返回绝对值:

hcl
abs(-5)

ceil 和 floor #

hcl
ceil(4.2)

floor(4.8)

max 和 min #

hcl
max(1, 2, 3, 4, 5)

min(1, 2, 3, 4, 5)

max([1, 2, 3]...)

min([1, 2, 3]...)

pow 和 sqrt #

hcl
pow(2, 3)

sqrt(16)

signum #

hcl
signum(-5)
signum(0)
signum(5)

字符串函数 #

join 和 split #

hcl
join(", ", ["a", "b", "c"])

split(", ", "a, b, c")

lower 和 upper #

hcl
lower("HELLO")

upper("hello")

title 和 strrev #

hcl
title("hello world")

strrev("hello")

trim 系列函数 #

hcl
trim("  hello  ", " ")

trimspace("  hello  ")

trimprefix("hello-world", "hello-")

trimsuffix("hello-world", "-world")

substr #

hcl
substr("hello world", 0, 5)

format 和 formatlist #

hcl
format("Hello, %s!", "World")

format("The value is %d", 42)

format("%s has %d items", "bucket", 10)

formatlist("%s-%d", ["a", "b"], [1, 2])

indent #

hcl
indent(4, "hello\nworld")

replace #

hcl
replace("hello world", "world", "terraform")

replace("hello world", "/wor.d/", "terraform")

regex 和 regexall #

hcl
regex("[a-z]+", "hello123world")

regexall("[a-z]+", "hello123world")

coalesce #

hcl
coalesce("", null, "default")

coalesce("a", "b", "c")

coalescelist #

hcl
coalescelist([], ["a", "b"], ["c"])

集合函数 #

length #

hcl
length(["a", "b", "c"])

length({a = 1, b = 2})

length("hello")

contains #

hcl
contains(["a", "b", "c"], "a")

contains(["a", "b", "c"], "d")

index 和 element #

hcl
index(["a", "b", "c"], "b")

element(["a", "b", "c"], 1)

element(["a", "b", "c"], 5)

keys 和 values #

hcl
keys({a = 1, b = 2, c = 3})

values({a = 1, b = 2, c = 3})

lookup #

hcl
lookup({a = "1", b = "2"}, "a", "default")

lookup({a = "1", b = "2"}, "c", "default")

merge #

hcl
merge({a = 1}, {b = 2})

merge({a = 1, b = 2}, {b = 3, c = 4})

slice #

hcl
slice(["a", "b", "c", "d", "e"], 1, 4)

concat #

hcl
concat(["a", "b"], ["c", "d"])

flatten #

hcl
flatten([["a", "b"], ["c", ["d", "e"]]])

distinct #

hcl
distinct(["a", "b", "a", "c", "b"])

set 系列函数 #

hcl
setintersection(["a", "b"], ["b", "c"])

setunion(["a", "b"], ["b", "c"])

setdifference(["a", "b", "c"], ["b"])

setsymmetricdifference(["a", "b"], ["b", "c"])

setproduct(["a", "b"], ["1", "2"])

toset #

hcl
toset(["a", "b", "a"])

编码函数 #

JSON 函数 #

hcl
jsonencode({
  name = "example"
  port = 8080
})

jsondecode("{\"name\":\"example\",\"port\":8080}")

Base64 函数 #

hcl
base64encode("hello world")

base64decode("aGVsbG8gd29ybGQ=")

base64gzip("hello world")

base64gunzip("...")

YAML 函数 #

hcl
yamlencode({
  name = "example"
  items = ["a", "b", "c"]
})

yamldecode("name: example\nitems:\n- a\n- b\n- c")

URL 编码 #

hcl
urlencode("hello world")

urldecode("hello%20world")

CSV 函数 #

hcl
csvdecode("name,age\nalice,30\nbob,25")

文件函数 #

file #

hcl
file("${path.module}/config.yaml")

fileexists #

hcl
fileexists("${path.module}/config.yaml")

fileset #

hcl
fileset("${path.module}", "*.tf")

fileset("${path.module}", "**/*.yaml")

filebase64 #

hcl
filebase64("${path.module}/config.yaml")

filebase64sha256 #

hcl
filebase64sha256("${path.module}/config.yaml")

templatefile #

hcl
templatefile("${path.module}/user_data.sh.tpl", {
  environment = "production"
  region      = "us-east-1"
})

模板文件 user_data.sh.tpl

bash
#!/bin/bash
echo "Environment: ${environment}"
echo "Region: ${region}"

日期函数 #

timestamp #

hcl
timestamp()

formatdate #

hcl
formatdate("YYYY-MM-DD", timestamp())

formatdate("YYYY-MM-DD hh:mm:ss", timestamp())

formatdate("DD MMM YYYY hh:mm ZZZ", "2018-01-02T23:12:01Z")

timeadd #

hcl
timeadd("2017-11-22T00:00:00Z", "1h")

timeadd(timestamp(), "24h")

timecmp #

hcl
timecmp("2017-11-22T00:00:00Z", "2017-11-22T01:00:00Z")

timecmp("2017-11-22T01:00:00Z", "2017-11-22T00:00:00Z")

timecmp("2017-11-22T00:00:00Z", "2017-11-22T00:00:00Z")

加密函数 #

Hash 函数 #

hcl
md5("hello world")

sha1("hello world")

sha256("hello world")

sha512("hello world")

bcrypt #

hcl
bcrypt("password")

bcrypt("password", 12)

RSA 函数 #

hcl
rsadecrypt(encrypted_string, private_key_pem)

UUID 函数 #

hcl
uuid()

uuidv5("dns", "example.com")

网络函数 #

CIDR 函数 #

hcl
cidrhost("10.0.0.0/16", 5)

cidrnetmask("10.0.0.0/16")

cidrsubnet("10.0.0.0/16", 8, 0)

cidrsubnet("10.0.0.0/16", 8, 1)

cidrsubnets("10.0.0.0/16", 8, 8, 8, 8)

示例 #

hcl
locals {
  vpc_cidr = "10.0.0.0/16"
  
  subnet_cidrs = [
    for i in range(3) : cidrsubnet(local.vpc_cidr, 8, i)
  ]
}

output "subnet_cidrs" {
  value = local.subnet_cidrs
}

类型转换函数 #

tolist, tomap, toset #

hcl
tolist(["a", "b", "c"])

tomap({a = 1, b = 2})

toset(["a", "b", "a"])

tostring, tonumber, tobool #

hcl
tostring(42)

tonumber("42")

tobool("true")

can 和 try #

hcl
can(var.might_not_exist)

try(var.might_not_exist, "default")

try(jsondecode("invalid json"), {})

type #

hcl
type("hello")

type([1, 2, 3])

type({a = 1})

条件和逻辑函数 #

alltrue 和 anytrue #

hcl
alltrue([true, true, true])

alltrue([true, false, true])

anytrue([false, false, true])

anytrue([false, false, false])

coalesce #

hcl
coalesce(null, "", "default")

coalesce("first", "second", "third")

defaults #

hcl
defaults({a = 1, b = null}, {b = 2, c = 3})

其他实用函数 #

sort #

hcl
sort(["c", "a", "b"])

reverse #

hcl
reverse(["a", "b", "c"])

range #

hcl
range(5)

range(1, 5)

range(0, 10, 2)

one #

hcl
one(["single"])

one([])

one(null)

sensitive 和 nonsensitive #

hcl
sensitive("password")

nonsensitive(sensitive("password"))

函数组合示例 #

生成子网 CIDR #

hcl
locals {
  vpc_cidr = "10.0.0.0/16"
  azs      = ["us-east-1a", "us-east-1b", "us-east-1c"]
  
  public_subnets = [
    for i, az in local.azs : {
      cidr_block        = cidrsubnet(local.vpc_cidr, 8, i)
      availability_zone = az
    }
  ]
}

标签处理 #

hcl
locals {
  common_tags = {
    Environment = var.environment
    ManagedBy   = "terraform"
  }
  
  resource_tags = merge(
    local.common_tags,
    var.extra_tags,
    {
      Name = "${var.project_name}-${var.environment}"
    }
  )
}

配置文件生成 #

hcl
locals {
  config = {
    database = {
      host     = aws_db_instance.main.address
      port     = aws_db_instance.main.port
      name     = aws_db_instance.main.db_name
      username = aws_db_instance.main.username
    }
    cache = {
      host = aws_elasticache_cluster.main.cache_nodes[0].address
      port = aws_elasticache_cluster.main.cache_nodes[0].port
    }
  }
}

resource "aws_s3_bucket_object" "config" {
  bucket  = var.config_bucket
  key     = "config.json"
  content = jsonencode(local.config)
}

用户数据脚本 #

hcl
locals {
  user_data = templatefile("${path.module}/user_data.sh.tpl", {
    db_host     = aws_db_instance.main.address
    db_port     = aws_db_instance.main.port
    db_name     = aws_db_instance.main.db_name
    redis_host  = aws_elasticache_cluster.main.cache_nodes[0].address
    redis_port  = aws_elasticache_cluster.main.cache_nodes[0].port
    environment = var.environment
  })
}

resource "aws_instance" "web" {
  user_data = base64encode(local.user_data)
}

下一步 #

掌握了内置函数后,接下来学习 表达式与条件,了解 Terraform 表达式的高级用法!

最后更新:2026-03-29