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

能否在AWS SSM RunCommand文档中编写多行Shell/PowerShell条件分支脚本?

在AWS SSM文档中编写多行Shell/PowerShell条件分支脚本

当然可以在AWS SSM的AWS-RunShellScript(或AWS-RunPowerShellScript)里写多行if-else条件分支脚本,但你现在的写法有问题:SSM的commands列表里每一项会被当作单独的命令执行,而Shell的if-else是一套连贯的语法结构,拆成不同列表项会直接触发语法错误。

正确的Shell脚本写法

你需要把整套if-else逻辑作为单个命令项,推荐用YAML的块标量语法(|)来保留换行,既保证可读性又能让脚本正确执行:

- name: checkMembership
  action: 'aws:runCommand'
  inputs:
    DocumentName: AWS-RunShellScript
    InstanceIds:
      - '{{InstanceIds}}'
    Parameters:
      commands:
        - |
          if [ -n "$foo" ]; then
              echo 'hello'
          else
              echo 'bye'
          fi

如果想写紧凑点,也可以用分号把逻辑连起来:

- name: checkMembership
  action: 'aws:runCommand'
  inputs:
    DocumentName: AWS-RunShellScript
    InstanceIds:
      - '{{InstanceIds}}'
    Parameters:
      commands:
        - if [ -n "$foo" ]; then echo 'hello'; else echo 'bye'; fi

正确的PowerShell脚本写法

如果用PowerShell,记得把DocumentName换成AWS-RunPowerShellScript,同样用块标量写多行逻辑:

- name: checkMembership
  action: 'aws:runCommand'
  inputs:
    DocumentName: AWS-RunPowerShellScript
    InstanceIds:
      - '{{InstanceIds}}'
    Parameters:
      commands:
        - |
          if ($foo) {
              Write-Output 'hello'
          } else {
              Write-Output 'bye'
          }

注意点

  • Shell脚本里if后面必须加空格,条件要用[]或[[]]包裹,变量记得加引号避免空格引发的问题。
  • PowerShell语法和Shell不一样,别搞混条件判断的格式,一定要对应正确的SSM文档。
  • 用|的块标量是写多行脚本最舒服的方式,能完美保留脚本的格式,不会因为拆分命令导致语法错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 08:06:18