Terraform函数

为了在表达式上更加灵活地方便计算,Terraform提供了大量的内置函数。

Terraform目前不支持自定义函数,只能使用自带的。

如下整理出Terraform自带的内置函数列表,方便查阅。

执行terraform console命令进入到Terraform Console界面,可以执行并验证如下函数的执行效果。

# 执行terraform console命令进入到Terraform Console界面
$ terraform console
>  

数值计算函数

求绝对值abs()

> abs(-12)
12
> abs(0)
0

求大于等于该数值的最小整数ceil()

> ceil(1)
1
> ceil(1.1)
2
> ceil(1.9)
2

求小于等于该数值的最大整数floor()

> floor(6)
6
> floor(6.9)
6
> floor(5.34)
5

求对数log()

> log(16,2)
4
> log(9,3)
2.0000000000000004
>

求指数pow()

> pow(6,0)
1
> pow(6,1)
6
> pow(6,2)
36

求最大值max()

> max(2,98,75,4)
98

求最小值min()

> min(0,23,9,-1)
-1

字符串转换为整数parseint()

第二参数表示需要转换成的目标进制

> parseint("16", 10)
16
> parseint("16", 16)
22
> parseint("FF", 16)
255
> parseint("1010", 2)
10

字符串函数

删除字符串尾部的换行符chomp()

> chomp("www.baidu.com")
"www.baidu.com"
> chomp("www.baidu.com\n")
"www.baidu.com"
> chomp("www.baidu.com\n\n")
"www.baidu.com"
> chomp("www.baidu.com\n\n\r")
"www.baidu.com"
> chomp("www.baidu.com\n\n\ra") # 这里字符串尾部没有换行符,中间的换行符不会被删除
<<EOT
www.baidu.com

a
EOT
>

格式化输出format()

> format("Hi, %s", "ABC")
"Hi, ABC"
> format("My name is %s, i'm %d", "zhangsan", 18)
"My name is zhangsan, i'm 18"
> format("The result is %.2f", 3)
"The result is 3.00"
> format("The result is %.2f", 3.1415)
"The result is 3.14"
> format("The result is %8.2f", 3.1415)
"The result is     3.14"

遍历格式化列表formatlist()

参数可以是列表list,也可以是单个变量

> formatlist("My name is %s, i'm %d", ["zhangsan","lisi","wangwu"], [12,13,14])
tolist([
  "My name is zhangsan, i'm 12",
  "My name is lisi, i'm 13",
  "My name is wangwu, i'm 14",
])

字符串连接join()

> join(".", ["www","baidu","com"])
"www.baidu.com"
> join(". ", ["www","baidu","com"])
"www. baidu. com"
>

转换为小写lower()

> lower("WWW.BAIDU.COM")
"www.baidu.com"

转换为大写upper()

> upper("www.baidu.com")
"WWW.BAIDU.COM"

首字母大写title()

> title("www.baidu.com")
"Www.Baidu.Com"

字符串替换replace()

> replace("www.baidu.com","baidu","google")
"www.google.com"
> replace("hello larry","/la.*y/","google") # 这里使用了正则表达式
"hello google"

字符串分割split()

> split(".","www.baidu.com")
tolist([
  "www",
  "baidu",
  "com",
])

字符串反转strrev()

> strrev("baidu")
"udiab"
>

字符串截取substr()

> substr("baidu",0,3)
"bai"
> substr("baidu",-4,-1) # 编号为负数时最后一个字符的编号为-1
"aidu"

去除头尾某些特定字符

trim()函数只要有特定字符就删除:

> trim("?!what?!!!!!","?!")
"what"
> trim("abaaaaabbLarry Dengaab", "ab")
"Larry Deng"

trimprefix()函数去除头部特定字符串:

> trimprefix("?!what?!!!!!", "?!")
"what?!!!!!"

trimsuffix()函数去除尾部特定字符串:

> trimsuffix("?!what?!!!!!", "!!!")
"?!what?!!"

trimspace()函数去除头尾的空格、换行等空串:

> trimspace(" Larry Deng \n\r")
"Larry Deng"

正则匹配

regex()函数匹配第一个:

> regex("[a-z\\.]+", "2021www.pkslow.com2022larry deng 31415926")
"www.pkslow.com"

regexall()函数匹配所有:

> regexall("[a-z\\.]+", "2021www.pkslow.com2022larry deng 31415926")
tolist([
  "www.pkslow.com",
  "larry",
  "deng",
])

集合类函数

判断列表是否全为真alltrue()

空列表直接返回true,列表元素只能是bool类型或者对应的字符串。

> alltrue([true, "true"])
true
> alltrue([true, "true", false])
false
> alltrue([])
true
> alltrue([1]) # 列表元素不是bool类型或者不是bool类型对应的字符串,返回false
╷
│ Error: Invalid function argument
│ 
│   on <console-input> line 1:
│   (source code not available)
│ 
│ Invalid value for "list" parameter: element 0: bool required.

判断列表是否有真anytrue()

只要列表元素有一个为真就返回true,空列表返回false。

> anytrue([true])
true
> anytrue([true, false])
true
> anytrue([false, false])
false
> anytrue([])
false

列表分片chunklist()

根据分片数来对列表进行切分。

> chunklist(["www", "pkslow", "com", "Larry", "Deng"], 3)
tolist([
  tolist([
    "www",
    "pkslow",
    "com",
  ]),
  tolist([
    "Larry",
    "Deng",
  ]),
])

返回第一个非空元素coalesce()

> coalesce("", "a", "b")
"a"
> coalesce("", "", "b")
"b"

返回第一个非空列表coalescelist()

> coalescelist([], ["pkslow"])
[
  "pkslow",
]

从字符串列表里把空的去掉compact()

> compact(["", "www", "", "pkslow", "com"])
tolist([
  "www",
  "pkslow",
  "com",
])

连接多个列表concat()

> concat([1, 2, 3], [4, 5, 6])
[
  1,
  2,
  3,
  4,
  5,
  6,
]

判断是否存在某个元素contains()

> contains(["www", "pkslow", "com"], "pkslow")
true
> contains(["www", "pkslow", "com"], "Larry")
false

去除重复元素distinct()

> distinct([1, 2, 2, 1, 3, 8, 1, 10])
tolist([
  1,
  2,
  3,
  8,
  10,
])

获取列表的某个元素element()

循环访问数组元素,不会存在索引越界的问题。

> element(["a", "b", "c"], 1)
"b"
> element(["a", "b", "c"], 2)
"c"
> element(["a", "b", "c"], 3)
"a"
> element(["a", "b", "c"], 4)
"b"

把内嵌的列表都展开成一个列表flatten()

> flatten([1, 2, 3, [1], [[6]]])
[
  1,
  2,
  3,
  1,
  6,
]

获取列表中的元素的索引值index()

> index(["www", "pkslow", "com"], "pkslow")
1

获取map的所有key值keys()

> keys({name="Larry", age=18, webSite="www.pkslow.com"})
[
  "age",
  "name",
  "webSite",
]

获取map的value值values()

> values({name="Larry", age=18, webSite="www.pkslow.com"})
[
  18,
  "Larry",
  "www.pkslow.com",
]

获取字符串、列表、map等的长度length()

> length("pkslow")
6
> length([])
0
> length(["pkslow"])
1
> length(["pkslow", "com"])
2
> length({pkslow = "com"})
1

根据key值在map中找到对应的value值lookup()

lookup(map, key, default)根据key值在map中找到对应的value值,如果没有则返回默认值。

> lookup({name = "Larry", age = 18}, "age", 1)
18
> lookup({name = "Larry", age = 18}, "myAge", 1)
1

对key值进行匹配matchkeys()

matchkeys(valueslist, keyslist, searchset)对key值进行匹配,匹配到key值后,返回对应的Value值。

> matchkeys(["a", "b", "c", "d"], [1, 2, 3, 4], [2, 4])
tolist([
  "b",
  "d",
])

map合并merge()

merge()合并map,key相同的会被最后的覆盖。

> merge({name = "Larry", webSite = "pkslow.com"}, {age = 18})
{
  "age" = 18
  "name" = "Larry"
  "webSite" = "pkslow.com"
}
> merge({name = "Larry", webSite = "pkslow.com"}, {age = 18}, {age = 13})
{
  "age" = 13
  "name" = "Larry"
  "webSite" = "pkslow.com"
}

取集合的一个元素one()

one()取集合的一个元素,如果为空则返回null;如果只有一个元素,则返回该元素;如果多个元素,则报错。

> one([])
null
> one(["pkslow"])
"pkslow"
> one(["pkslow", "com"])
╷
│ Error: Invalid function argument
│ 
│   on <console-input> line 1:
│   (source code not available)
│ 
│ Invalid value for "list" parameter: must be a list, set, or tuple value with either zero or one elements.

生成顺序列表range()

存在三个生成顺序列表的range()函数:
range(max)range(start, limit)range(start, limit, step)

> range(3)
tolist([
  0,
  1,
  2,
])
> range(1, 6)
tolist([
  1,
  2,
  3,
  4,
  5,
])
> range(1, 6, 2)
tolist([
  1,
  3,
  5,
])

反转列表reverse()

> reverse([1, 2, 3, 4])
[
  4,
  3,
  2,
  1,
]

对set求交集setintersection()

> setintersection([1, 2, 3], [2, 3, 4], [2, 3, 6])
toset([
  2,
  3,
])

列出所有组合可能setproduct()

> setproduct(["Larry", "Harry"], ["Deng", "Potter"])
tolist([
  [
    "Larry",
    "Deng",
  ],
  [
    "Larry",
    "Potter",
  ],
  [
    "Harry",
    "Deng",
  ],
  [
    "Harry",
    "Potter",
  ],
])

set的减法setsubtract()

> setsubtract([1, 2, 3], [3, 4])
toset([
  1,
  2,
])

set的加法setunion()

> setunion([1, 2, 3], [3, 4])
toset([
  1,
  2,
  3,
  4,
])
> setunion(setsubtract(["a", "b", "c"], ["a", "c", "d"]), setsubtract(["a", "c", "d"], ["a", "b", "c"]))
toset([
  "b",
  "d",
])

截取列表部分slice()

slice(list, startindex, endindex)截取列表部分,包括startindex,但不包括endindex,下标从0开始。

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

对列表中的字符串进行排序sort()

sort()对列表中的字符串进行排序,要注意如果输入的是数字,会先转化为字符串再排序。

> sort(["larry", "pkslow", "com", "deng"])
tolist([
  "com",
  "deng",
  "larry",
  "pkslow",
])
> sort([3, 6, 1, 9, 12, 79, 22]) # 从排序结果看按首字符做升序,所以是字符串排序
tolist([
  "1",
  "12",
  "22",
  "3",
  "6",
  "79",
  "9",
])

求和sum()

> sum([3, 1.2, 9, 17.3, 2.2])
32.7

对map的key和value进行换位transpose()

> transpose({"a" = ["1", "2"], "b" = ["2", "3"]})
tomap({
  "1" = tolist([
    "a",
  ])
  "2" = tolist([
    "a",
    "b",
  ])
  "3" = tolist([
    "b",
  ])
})

根据key和value的列表按一对一关系生成map集合zipmap()

> zipmap(["age", "name"], [18, "Larry Deng"])
{
  "age" = 18
  "name" = "Larry Deng"
}

加解密函数

base64加解密

> base64encode("pkslow") # Base64加密
"cGtzbG93"
> base64decode("cGtzbG93") # Base64解密
"pkslow"
> textencodebase64("pkslow", "UTF-8")
"cGtzbG93"
> textdecodebase64("cGtzbG93", "UTF-8")
"pkslow"

md5签名

> md5("www.baidu.com")
"dab19e82e1f9a681ee73346d3e7a575e"

生成UUID

> uuid()
"17c8fde5-7982-c3ca-8cef-016498cefed6"

csv文本解析

> csvdecode("seq,name,age\n1,larry,18\n2,pkslow,3\n3,Jeremy,29")
tolist([
  {
    "age" = "18"
    "name" = "larry"
    "seq" = "1"
  },
  {
    "age" = "3"
    "name" = "pkslow"
    "seq" = "2"
  },
  {
    "age" = "29"
    "name" = "Jeremy"
    "seq" = "3"
  },
])

json编解码

> jsonencode({"name"="Larry", "age"=18}) # json编码
"{\"age\":18,\"name\":\"Larry\"}"
> jsondecode("{\"age\":18,\"name\":\"Larry\"}") # json解码
{
  "age" = 18
  "name" = "Larry"
}

URL编码

> urlencode("Larry Deng/a/:/./@")
"Larry+Deng%2Fa%2F%3A%2F.%2F%40"

YAML编解码

> yamlencode({"a":"b", "c":"d"}) # yaml编码
<<EOT
"a": "b"
"c": "d"

EOT
> yamlencode({"foo":[1, 2, 3], "bar": "baz"}) # yaml编码
<<EOT
"bar": "baz"
"foo":
- 1
- 2
- 3

EOT
> yamlencode({"foo":[1, {"a":"b","c":"d"}, 3], "bar": "baz"}) # yaml编码
<<EOT
"bar": "baz"
"foo":
- 1
- "a": "b"
  "c": "d"
- 3

EOT
> yamldecode("hello: world") # yaml解码
{
  "hello" = "world"
}
> yamldecode("true") # yaml解码
true
> yamldecode("{a: &foo [1, 2, 3], b: *foo}") # yaml解码
{
  "a" = [
    1,
    2,
    3,
  ]
  "b" = [
    1,
    2,
    3,
  ]
}

文件处理

获取文件绝对路径:

> abspath(path.root)
"/root"

获取路径中的目录,或者是文件名:

> dirname("/root/iac/hello")
"/root/iac"
> dirname("/root/iac/hello/")
"/root/iac/hello"
> basename("/root/iac/hello")
"hello"
> basename("/root/iac/hello/")
"hello"

判断文件是否存在,并获取文件内容:

> fileexists("/root/iac/hello/main.tf")
true
> file("/root/iac/hello/main.tf") # 获取文件内容
> filebase64("/root/iac/hello/main.tf") # 对文件内容进行Base64编码

根据模式匹配所有文件:

> fileset("/root/iac/hello", "*.tf")
toset([
  "main.tf",
])

模板化文件:templatefile(path, vars)指定文件和变量,把变量值替换掉模板中的变量。

给定一个模块文件backends.tftpl,文件内容如下:

%{ for addr, port in ip_addrs ~}
backend ${addr}:${port}
%{ endfor ~}

> templatefile("/root/iac/hello/backends.tftpl", { port = 8080, ip_addrs = ["10.0.0.1", "10.0.0.2"] })
<<EOT
backend 0:10.0.0.1
backend 1:10.0.0.2

EOT

时间函数

时间格式化formatdate()

获取当前时间,并格式化显示,格式请参考:formatdate Function

> formatdate("YYYY-MM-DD hh:mm:ss / D MMMM YYYY", timestamp())
"2023-09-09 10:27:12 / 9 September 2023"
> formatdate("EEEE, DD-MMM-YY hh:mm:ss ZZZ", "2018-01-02T23:12:01Z")
"Tuesday, 02-Jan-18 23:12:01 UTC"

时间加减timeadd()

时间加减函数:timeadd(),支持的单位有:纳秒(ns), 微秒(usµs), 毫秒(ms), 秒(s), 分钟(m)和小时(h)。

> timeadd(timestamp(), "24h")
"2023-09-10T10:27:48Z"
> timeadd(timestamp(), "-24h10m")
"2023-09-08T10:17:55Z"

类型转换函数

判断表达式是否会执行出错can()

> can(regex("^ami-", "ami-123"))
true
> can(regex("^ami-", "bmi-123"))
false

判断值类型type()

> type("hello")
string
> type(["hello"])
tuple([
    string,
])

类型转换函数

tobool()函数只能转换bool类型的值或其对应的字符串或null值,转换其他值报错。

> tobool(true)
true
> tobool("true")
true
> tobool(null)
tobool(null)
> tobool(1)
╷
│ Error: Invalid function argument
│ 
│   on <console-input> line 1:
│   (source code not available)
│ 
│ Invalid value for "v" parameter: cannot convert number to bool.

还有其他类型转换函数,如:tolist()tomap()tonumber()toset()tostring()等。

相关推荐
百事牛1 小时前
如何禁止编辑PDF文件?推荐两种方法!
windows·pdf
分享者花花3 小时前
iPhone设备使用技巧:忘记密码的情况下如何解除iOS 18/17屏幕时间
windows·数码相机·macos·ios·电脑·cocoa·iphone
小朱同学️3 小时前
Windows:Node.js下载与安装教程
windows·node.js
分享者花花4 小时前
如何从索尼相机/ SD卡恢复已删除的照片/视频
android·windows·数码相机·ios·智能手机·word·笔记本电脑
3分云计算6 小时前
火绒使用详解 为什么选择火绒?使用了自定义规则及其高级功能的火绒,为什么能吊打卡巴斯基,360,瑞星,惠普联想戴尔的电脑管家等?
windows·网络安全·电脑·火绒安全·杀毒软件·网络防护·高级火绒
ehviwer237 小时前
fl studio mobile2024最新官方版V4.6.8安卓版+iOS苹果版
android·前端·数据库·windows·macos·idm
problc9 小时前
Ollama 使用指南:Linux、Windows 和 macOS
linux·windows·macos
2401_857617629 小时前
C#桌面开发之巅:Windows Forms与WPF深度解析
windows·c#·wpf
hmywillstronger10 小时前
【C#】【EXCEL】Bumblebee/Classes/ExRow.cs
windows·c#·excel