AWS CLI:如何扩展 aws ssm send-command 目标中的变量?

AWS CLI: How can you expand a variable in aws ssm send-command targets?

我正在尝试构建一个 bash for 循环,将实例 ID 提供给以下 AWS CLI 命令以在多个实例上 运行 Powershell。每当我尝试将 $server 的值扩展为变量 for 作为 for 循环中的实例 ID 列表时,我都会收到错误消息:

An error occurred (InvalidInstanceId) when calling the SendCommand operation:

在从启用了 AWS CLI 的 Linux 框中执行 运行 文档时,这里有一些尝试让 $server 正确扩展。当我用变量 $server 包含的相同实例 ID (i-081158da57d2a8da6) 替换 $server 或 ${server} 时,它可以正常工作。我觉得这一定非常简单,但我的研究技能让我无法弄清楚如何在我的 Linux 实例上从 AWS CLI 正确执行 SSM 文档所需的语法中扩展变量。

:~$ aws ssm send-command --document-name "AWS-RunPowerShellScript" --document-version "1" --targets '[{"Key":"InstanceIds","Values":["${server}"]}]' --parameters '{"commands":["$wmi = Get-WmiObject -Class Win32_OperatingSystem ","$uptimeMinutes = ($wmi.ConvertToDateTime($wmi.LocalDateTime)-$wmi.ConvertToDateTime($wmi.LastBootUpTime) | select-object -expandproperty "TotalMinutes")","[int]$uptimeMinutes"],"workingDirectory":[""],"executionTimeout":["60"]}' --timeout-seconds 600 --max-concurrency "50" --max-errors "0" --region us-west-2

An error occurred (InvalidInstanceId) when calling the SendCommand operation:

:~$ aws ssm send-command --document-name "AWS-RunPowerShellScript" --document-version "1" --targets '[{"Key":"InstanceIds","Values":["$server"]}]' --parameters '{"commands":["$wmi = Get-WmiObject -Class Win32_OperatingSystem ","$uptimeMinutes = ($wmi.ConvertToDateTime($wmi.LocalDateTime)-$wmi.ConvertToDateTime($wmi.LastBootUpTime) | select-object -expandproperty "TotalMinutes")","[int]$uptimeMinutes"],"workingDirectory":[""],"executionTimeout":["60"]}' --timeout-seconds 600 --max-concurrency "50" --max-errors "0" --region us-west-2

An error occurred (InvalidInstanceId) when calling the SendCommand operation:

JSON 文档用单引号括起来,这会关闭变量插值——请参阅 Difference between single and double quotes in Bash——这意味着 $server 不会展开。

效果演示如下:

[:~] $ server=banana
[:~] $ 
[:~] $ echo '[{"Key":"InstanceIds","Values":["$server"]}]'
[{"Key":"InstanceIds","Values":["$server"]}]
[:~] $

如果您改用双引号,值将被插入:

[:~] $ echo "[{\"Key\":\"InstanceIds\",\"Values\":[\"$server\"]}]"
[{"Key":"InstanceIds","Values":["banana"]}]
[:~] $ 

注意我必须在双引号内转义双引号。否则它们会从输出中消失,这将使其无效 JSON.