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

通过CloudFormation执行PowerShell命令报错,请求协助排查

问题:CloudFormation中执行PowerShell命令报错"Missing '=' operator after key in hash literal"

我尝试通过CloudFormation模板执行PowerShell命令时,日志抛出错误:Missing '=' operator after key in hash literal. The hash literal was incomplete,但该命令在Windows PowerShell中手动执行正常。

报错日志详情

2023-02-13 06:24:11,459 [ERROR] Command 2-Reboot (powershell.exe -Command {Import-Module -name AWSPowerShell; [string]$token = Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token-ttl-seconds" = "21600"} -Method PUT -Uri http://169.254.169.254/latest/api/token; $instanceId = Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token" = $token} -Method GET -Uri http://169.254.169.254/latest/meta-data/instance-id; Write-Output "reboot instance $instanceId through API"; Restart-EC2Instance -InstanceId $instanceId}) failed
2023-02-13 06:24:11,459 [DEBUG] Command 2-Reboot output: At line:1 char:84

+ ... WSPowerShell; [string]$token = Invoke-RestMethod -Headers @{X-aws-ec2 ...

+                                                                  ~

Missing '=' operator after key in hash literal.

At line:1 char:84

+ ... WSPowerShell; [string]$token = Invoke-RestMethod -Headers @{X-aws-ec2 ...

+                                                                  ~

The hash literal was incomplete.

At line:1 char:231

+ ... atest/api/token; $instanceId = Invoke-RestMethod -Headers @{X-aws-ec2 ...

+                                                                  ~

Missing '=' operator after key in hash literal.

At line:1 char:231

+ ... atest/api/token; $instanceId = Invoke-RestMethod -Headers @{X-aws-ec2 ...

+                                                                  ~

The hash literal was incomplete.

    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException

    + FullyQualifiedErrorId : MissingEqualsInHashLiteral

问题原因

问题出在哈希表键名的引号处理上:CloudFormation解析模板时会转义双引号,导致命令中带连字符的键名(如X-aws-ec2-metadata-token-ttl-seconds)丢失外层引号。PowerShell会把连字符当成运算符,无法识别为哈希表的键名,从而抛出语法错误。

修复方案

调整命令的引号嵌套,给哈希表键名使用单引号,同时用& { ... }包裹整个脚本块,确保PowerShell正确解析:

powershell.exe -Command "& {Import-Module -name AWSPowerShell; [string]$token = Invoke-RestMethod -Headers @{'X-aws-ec2-metadata-token-ttl-seconds' = '21600'} -Method PUT -Uri http://169.254.169.254/latest/api/token; $instanceId = Invoke-RestMethod -Headers @{'X-aws-ec2-metadata-token' = $token} -Method GET -Uri http://169.254.169.254/latest/meta-data/instance-id; Write-Output 'reboot instance $instanceId through API'; Restart-EC2Instance -InstanceId $instanceId}"

关键调整点

  • 将哈希表键名的双引号替换为单引号,避免CloudFormation转义后丢失引号
  • 用& { ... }包裹整个命令脚本块,确保PowerShell正确处理多语句逻辑
  • 字符串常量改用单引号,减少嵌套转义冲突

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:45:14