Expressions 表達式
條件表達式
condition ? true_val : false_val
- condition 條件
- true_val 條件為 true 的值
- false_val 條件為false 的值
當 region 變量存在時,region=var.region,反之 region="cn-hangzhou"
terraform console
> var.region != "" ? var.region: "cn-hangzhou"
"cn-beijing"
for 表達式
借助 for 表達式可以對資料進行處理,生成新的對象;
[ for VAR in OBJECT : VAR]
[ for INDEX, VAR in OBJECT: "${INDEX}=${VAR}"]
variable "env_list" {
type = list
default = ["dev", "test", "prod"]
}
> [for i in var.env_list : i]
[
"dev",
"test",
"prod",
]
> [for i,v in var.env_list : "${i} = ${v}"]
[
"0 = dev",
"1 = test",
"2 = prod",
]
splat 表達式
splat 表達式提供了一種更簡潔的方式來表達可以用 for 表達式執行的常見操作
variable "info_list" {
type = list
default = [{
name = "test",
role = "dev",
},
{
name = "whale",
role = "admin",
}
]
}
#
> var.info_list
tolist([
{
"name" = "test"
"role" = "dev"
},
{
"name" = "whale"
"role" = "admin"
},
])
> var.info_list[*].name
tolist([
"test",
"whale",
])
> var.info_list[*].role
tolist([
"dev",
"admin",
])
内置函數
Terrform 語言包含許多内置函數,可以從表達式中調用這些函數來轉換。
函數調用的一般文法是函數名後跟括号中以逗号分隔的參數。
function(arg1, arg2)
數值函數
max() 擷取最大值
min() 擷取最小值
parseint() 将字元串解析為整數
whale@WhaledeMacBook-Pro dev % terraform console
> max(1,2,3,3,4,5)
5
> max([1,2,3,3,4,5]...)
5
> parseint("101", 10)
101
> parseint("101", 2)
5
String 字元串函數
format() 格式化
join() 字元串拼接
replace() 替換字元串
> format("Hello %s", "whale")
"Hello whale"
> join(",", ["name","age","title"])
"name,age,title"
> replace("a=b=c","=","+")
"a+b+c"
> split(",","name,age,title")
tolist([
"name",
"age",
"title",
])
Collection 集合函數
函數 | 功能 |
alltrue() anytrue() | 判斷元素中都是、存在 為true |
chunklist(list, size) | 按照指定 |
compat(list) | 去除list中的課空元素 |
con(list1, list2) | 合并兩個list |
contains(list, value) | 判斷元素是否存在 list 中 |
distinct(list) | 去除 list 中的重複元素 |
element(list,index) list[index] | 根據index擷取list中的元素 |
flatten(list,list,list) | 将多層 list 轉換成單 list |
index(list,value) | 傳回value元素的index |
Map 映射函數
函數 | 功能 |
length(list) | 計算list 的長度 |
lookup(map,key,default) | 檢索map的key,不存在傳回 default |
merge(map1,map2,map3) | 合并map,相同key 會被最後覆寫 |
keys(map) | 建立map中key 的list |