Groovy:使用 JSON 执行 azure CLI 命令 - 解析问题?

Groovy: Executing azure CLI Command with JSON - Parsing Issue?

目前我无法从 Groovy 运行 azure CLI 命令,因为命令中有 JSON 部分。

有一个 azure 命令可以在虚拟机上 运行 自定义脚本。机器上的 CommandToExecute 作为 JSON.

传递

工作示例:

REQUEST-CALL in Console:az vm extension set -g demo --vm-name demo-cfg01 --name CustomScript --publisher Microsoft.Azure.Extensions --settings '{"commandToExecute":"ls"}'

RESPONSE: {
  "autoUpgradeMinorVersion": true,
  "forceUpdateTag": null,
  "id": "/subscriptions/xxxxxxxxxx-xxxxxx-xxxx-xxxx-xxxxxxxxxxxxx/resourceGroups/demo/providers/Microsoft.Compute/virtualMachines/demo-cfg01/extensions/CustomScript",
  "instanceView": null,
  "location": "germanycentral",
  "name": "CustomScript",
  "protectedSettings": null,
  "provisioningState": "Succeeded",
  "publisher": "Microsoft.Azure.Extensions",
  "resourceGroup": "demo",
  "settings": {
    "commandToExecute": "ls"
  },
  "tags": null,
  "type": "Microsoft.Compute/virtualMachines/extensions",
  "typeHandlerVersion": "2.0",
  "virtualMachineExtensionType": "CustomScript"
}

这个脚本工作正常。

"Same" 使用 Groovy 执行的命令导致以下结果:

def process
        StopWatch.withTimeRecording("EXECUTING COMMAND '" + cargs + "'",_logger, Level.ALL) {
            process = (cargs).execute(null,null);
            process.waitForProcessOutput(sout, serr)
        }

请注意记录包含参数的 StringArray 的秒表:

EXECUTING COMMAND '[az, vm, extension, set, -g, demo, --vm-name, demo-cfg01, --name, CustomScript, --publisher, Microsoft.Azure.Extensions, --settings, '{"commandToExecute":"ls"}']'

Params 看起来与控制台中的一样

Azure 的响应是:

VM has reported a failure when processing extension 'CustomScript'. Error message: "Enable failed: failed to get configuration: error reading extension configuration: error parsing settings file: error parsing json: json: cannot unmarshal string into Go value of type map[string]interface {}

我认为 groovy 在执行前以某种方式转义了字符,我不知道出了什么问题。有什么建议吗?

当您在 array 上调用 execute 时 groovy(实际上是 java)将每个参数加双引号。

只需在字符串中根据需要构建命令行

groovy 中的字符串与数组具有相同的执行方法...

def cmd = """az vm extension set -g demo --vm-name demo-cfg01 --name CustomScript --publisher Microsoft.Azure.Extensions --settings '{"commandToExecute":"ls"}' """
def process = cmd.execute()

当您对字符串使用执行时 groovy 将执行您提供的确切命令

找到一个"workaround"。 az 命令还接受 *.json 文件作为设置参数。因此,我首先在临时 json 文件中创建命令,并将 json 文件作为参数传递。有效!

您正在为 .execute() 来电报价。您不需要在那里引用,因为这里不涉及 shell 或命令解析器。

那里的命令得到 '{"commandToExecute":"ls"}',这是一个有效的 JSON String(无地图),这也是错误消息的内容:

error parsing json: json: cannot unmarshal string into Go value of type map[string]interface

只需使用 {"commandToExecute": "ls"}(没有周围的 ')作为参数。