You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform部署Logic App时对象变量在JSON模板中引用失败

用Terraform部署Logic App时的JSON解析错误

配置代码

Terraform资源body配置

body = jsonencode({
    properties = {
      definition = jsondecode(templatefile("templ.json",
        {
          schedHour     = tostring(var.schedule_hour) # 字符串类型
          functUri      = "https://abc"
          reqBody       = jsonencode(var.func_parameters)   # 对象类型
      }))  
      state = "Enabled"
    }
  })

Logic App模板(templ.json)中引用reqBody的部分

"inputs": {
        "subscribe": {
          "body": "${reqBody}",
          "method": "POST",
          "uri": "${functUri}"
        },
        "unsubscribe": {}
      }

变量定义

variable "func_parameters" {
  type = object({
    pipeline = object({
      calc_date = string
      # 其他属性
    })
  })
}

错误信息

执行terraform apply时触发错误:

Error: Error in function call
    
  on ../modules/logic-app/main.tf line 21, in resource "azapi_resource" "logic_app_workflow":
  21:       definition = jsondecode(templatefile(templ.json,
  22:         {
  23:           scheduleHour     = tostring(var.schedule_hour)
  24:           functUri   = "https://abc"
  27:           reqBody      = jsonencode(var.func_parameters)
  28:       }))
    ├────────────────
    │ while calling jsondecode(str)
    │ var.func_parameters is object with 1 attribute "pipeline"
    │ var.schedule_hour is 5

Call to function "jsondecode" failed: invalid character 'p' after object key:value pair.

尝试直接对变量用jsondecode时,收到错误:

on ../modules/logic-app/main.tf line 27, in resource "azapi_resource" "logic_app_workflow":
  27:           requestBody      = jsondecode(var.func_parameters)
    ├────────────────
    │ while calling jsondecode(str)
    │ var.func_parameters is a object
 
Invalid value for "str" parameter: string required.

解决方案

问题根源是提前对对象变量做jsonencode后传入模板,导致模板渲染出的JSON语法非法:模板中"body": "${reqBody}"会把JSON字符串直接插入,未转义的双引号破坏了JSON结构。

步骤1:修改Terraform代码,直接传入对象变量

去掉reqBody的jsonencode,直接将原始对象传入templatefile:

body = jsonencode({
    properties = {
      definition = jsondecode(templatefile("templ.json",
        {
          schedHour     = tostring(var.schedule_hour)
          functUri      = "https://abc"
          reqBody       = var.func_parameters  # 直接传入对象,不做jsonencode
      }))  
      state = "Enabled"
    }
  })

步骤2:调整模板,在内部对对象做jsonencode

修改templ.json中的body字段,使用jsonencode将对象转为合法的JSON结构嵌入:

"inputs": {
        "subscribe": {
          "body": ${jsonencode(reqBody)},  # 模板内对对象做jsonencode
          "method": "POST",
          "uri": "${functUri}"
        },
        "unsubscribe": {}
      }

这样模板渲染后会生成语法合法的JSON,jsondecode可以正确解析,最终生成的Logic App定义也能正确包含所需的请求体结构。

内容的提问来源于stack exchange,提问作者be9inn3r

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 03:23:14