terraform azurerm_virtual_machine_extension 'settings' json在使用连接运算符时无法解析

gopyfrb3  于 2022-12-14  发布在  Mac
关注(0)|答案(1)|浏览(134)

我使用以下terraform块在Windows虚拟机上运行自定义脚本

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 = <<SETTINGS
    {
        "commandToExecute": "powershell -ExecutionPolicy unrestricted -NoProfile -NonInteractive  -command \" echo hi \""
    }
    SETTINGS
}

这是因为命令只有一行...但是为了提高可读性,我尝试使用连接运算符来拆分命令

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 = <<SETTINGS
    {
        "commandToExecute": "${(join(" ", (["powershell -ExecutionPolicy unrestricted -NoProfile -NonInteractive",
                     "-command \"",
                     "echo hi",
                     "\""])))}"
    }
    SETTINGS
}

我在管道中的terraform输出中不断收到错误

│ Error: "settings" contains an invalid JSON: invalid character 'e' after object key:value pair
│ 
│   with azurerm_virtual_machine_extension.install_script,
│   on main.tf line 92, in resource "azurerm_virtual_machine_extension" "install_script":
│   92:     settings = <<SETTINGS
│   93:     {
│   94:         "commandToExecute": "${(join(" ", (["powershell -ExecutionPolicy unrestricted -NoProfile -NonInteractive",
│   95:                       "-command \"",
│   96:                       "echo hi",
│   97:                       "\""])))}"
│   98:     }
│   99:     SETTINGS

据我所知,join会将多行内容缩减为一个字符串,即使我定义了多行内容,它也不会抱怨,因为join操作符被 Package 在括号()中,列表项也被 Package 在括号()中。

eqqqjvef

eqqqjvef1#

要正确转义\,您需要使用\\\,这意味着您将具有:

<<SETTINGS
    {
        "commandToExecute": "${(join(" ", (["powershell -ExecutionPolicy unrestricted -NoProfile -NonInteractive",
                     "-command \\\"",
                     "echo hi",
                     "\\\""])))}"
    }
SETTINGS

相关问题