对于我的资源(azapi_resource 类型 Microsoft.Logic/workflows@2019-05-01,我有这个正文:
body = jsonencode({
properties = {
definition = jsondecode(templatefile("${path.module}/xyz.json",
{
.
.
uri = "https://****"
requestBody = var.params_obj
}))
parameters = {
.
.
uri = { value = "https://****" } #it is a string;
reqBody = { value = var.params_obj #it is an object
}
state = "Enabled"
}
})
在我的变量.tf 中,我声明了 var:
variable "params_obj" {
type = object({
pipeline = object({
calculation_date = string
name = string
abc = optional(object({
.
.
})
})
})
}
在我的示例 json xyz.json 中,我必须引用 var.params_obj 但不起作用,它按原样放入逻辑应用程序代码视图中,而不是变量的对象值。在我的 json 示例 xyz.json 中,我尝试引用如下:
"inputs": {
"subscribe": {
"body": "${reqBody}" #not working; I tried also with "[parameters('reqBody')]" #I tried with another forms... not working;
,
"method": "POST",
"uri": "${uri}" #it works to reference the string uri value;
"unsubscribe": {}
我的问题是如何在我的 json 模板中正确引用该 reqBody?因为有点奇怪。我的示例 json 包含 Microsoft.Logic/workflows 的定义和架构;
"$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#"
假设您希望请求正文作为模板中的有效 json 字符串,您需要使用
jsondecode
函数将 var 转换为 json 字符串,然后再尝试在模板中使用它
main.tf
variable "params_obj" {
type = object({
pipeline = object({
calculation_date = string
name = string
abc = optional(object({
foo = string
}))
})
})
default = {
pipeline = {
calculation_date = "monday"
name = "chris"
}
}
}
output "this" {
value = templatefile("mytemp.tftpl", {
reqBody = jsonencode(var.params_obj)
uri = "bar"
})
}
模板
{
"inputs": {
"subscribe": {
"body": "${reqBody}" ,
"method": "POST",
"uri": "${uri}"
},
"unsubscribe": {}
}
}
输出
Outputs:
this = <<EOT
{
"inputs": {
"subscribe": {
"body": "{"pipeline":{"abc":null,"calculation_date":"monday","name":"chris"}}" ,
"method": "POST",
"uri": "bar"
},
"unsubscribe": {}
}
}
EOT
如果不使用 jsondecode
函数并尝试将 var 直接传递给模板,我会收到错误
│ Error: Error in function call
│
│ on main.tf line 20, in output "this":
│ 20: value = templatefile("mytemp.tftpl", {
│ 21: reqBody = var.params_obj
│ 22: uri = "bar"
│ 23: })
│ ├────────────────
│ │ while calling templatefile(path, vars)
│ │ var.params_obj is object with 1 attribute "pipeline"
│
│ Call to function "templatefile" failed: mytemp.tftpl:4,29-36: Invalid template interpolation value; Cannot include the given value in a string template: string required..