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

使用AWS CLI编写EC2操作脚本遇SSM命令执行无效求助

解决SSM Send-Command执行无效果的问题

核心排查步骤

  • 验证SSM Agent状态
    登录EC2实例后执行以下命令确认Agent运行正常:

    sudo systemctl status amazon-ssm-agent
    

    如果未运行,启动并设置开机自启:

    sudo systemctl start amazon-ssm-agent
    sudo systemctl enable amazon-ssm-agent
    
  • 检查实例IAM权限
    确保EC2实例关联的IAM角色包含AmazonSSMManagedInstanceCore权限策略,没有的话需给角色添加该策略,否则实例无法接收SSM命令。

  • 查看命令执行详情
    不要仅依赖返回的Pending状态,用以下命令获取命令的实际执行日志和错误信息:

    aws ssm get-command-invocation --command-id <你的命令ID> --instance-id <实例ID>
    

    这里能明确命令是否真的执行,以及失败的具体原因(比如git权限不足、仓库地址错误、目录无写入权限等)。

  • 确认命令执行上下文
    SSM Send-Command默认以ssm-user身份执行命令,需注意:

    • 目标目录是否对ssm-user有写入权限,比如克隆到/home/ssm-user下是合法路径,写入/root会因权限不足失败
    • 如果是私有GitHub仓库,需给ssm-user配置SSH密钥,或用HTTPS方式携带凭证(例如git clone https://<用户名>:<token>@github.com/xxx/xxx.git)
  • 等待实例完全就绪
    EC2启动后不要立刻发送SSM命令,需等待实例状态检查通过且SSM Agent在线。可以用以下命令判断实例是否已注册到SSM:

    aws ssm describe-instance-information --filters "Key=InstanceIds,Values=<实例ID>"
    

    只有返回结果中能看到该实例,再执行后续命令。

脚本优化建议

在你的bash脚本中加入等待逻辑,确保实例就绪后再发命令:

# 启动实例
aws ec2 start-instances --instance-ids <实例ID>

# 等待实例状态变为running且状态检查通过
aws ec2 wait instance-status-ok --instance-ids <实例ID>

# 等待实例注册到SSM
until aws ssm describe-instance-information --filters "Key=InstanceIds,Values=<实例ID>" | grep -q "<实例ID>"; do
  echo "等待实例注册到SSM..."
  sleep 10
done

# 执行git clone命令(根据实际情况调整仓库地址和目标路径)
COMMAND_ID=$(aws ssm send-command --instance-ids <实例ID> --document-name "AWS-RunShellScript" --parameters commands="git clone https://github.com/xxx/xxx.git /home/ssm-user/myrepo" --query Command.CommandId --output text)

# 等待命令执行完成
aws ssm wait command-executed --command-id $COMMAND_ID --instance-ids <实例ID>

# 查看执行结果
aws ssm get-command-invocation --command-id $COMMAND_ID --instance-id <实例ID>

# 执行docker build等命令,同理使用send-command
# ...

# 停止实例
aws ec2 stop-instances --instance-ids <实例ID>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 13:54:22