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

使用join运算符时Terraform azurerm_virtual_machine_extension settings解析失败

解决Terraform CustomScriptExtension的settings JSON格式错误问题

问题原因

手动拼接JSON字符串时,引号转义处理不当,导致生成的JSON不符合规范。原写法中,HEREDOC内的插值字符串转义后,会让commandToExecute的值出现未正确转义的双引号,JSON解析器会误以为键值对提前结束,后续字符(比如echo的'e')就成了无效内容,触发报错。

解决方案

不要手动编写JSON结构,改用Terraform的jsonencode函数自动生成符合规范的JSON。同时用join拆分命令参数保持可读性,jsonencode会自动处理所有引号转义。

修改后的代码示例

resource "azurerm_virtual_machine_extension" "install_script" {
  name                 = "install_script"
  virtual_machine_id   = var.myvm.id
  publisher            = "Microsoft.Compute"
  type                 = "CustomScriptExtension"
  type_handler_version = "1.10" 

  settings = jsonencode({
    commandToExecute = join(" ", [
      "powershell",
      "-ExecutionPolicy unrestricted",
      "-NoProfile",
      "-NonInteractive",
      "-command \"echo hi\""
    ])
  })
}

代码说明

  • jsonencode函数接收一个Terraform对象,自动转换为合法的JSON字符串,无需手动处理引号转义。
  • 用列表拆分命令的各个参数段,再通过join(" ", ...)合并为完整命令,既提升了代码可读性,又避免手动拼接的错误。

额外优化

如果命令逻辑更复杂,还可以把命令参数单独定义为局部变量,进一步提升可读性:

locals {
  ps_command = join(" ", [
    "powershell",
    "-ExecutionPolicy unrestricted",
    "-NoProfile",
    "-NonInteractive",
    "-command \"echo hi\""
  ])
}

resource "azurerm_virtual_machine_extension" "install_script" {
  name                 = "install_script"
  virtual_machine_id   = var.myvm.id
  publisher            = "Microsoft.Compute"
  type                 = "CustomScriptExtension"
  type_handler_version = "1.10" 

  settings = jsonencode({
    commandToExecute = local.ps_command
  })
}

内容的提问来源于stack exchange,提问作者Ryu S.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 02:20:27