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

使用Ansible通过AWS SSM启动会话时遭遇Port插件未找到错误

问题:Ansible通过SSM代理连接EC2主机失败,出现Port插件错误

尝试用Ansible playbook连接EC2目标主机,已配置动态EC2清单,使用aws ssm start-session作为代理命令,但执行任务时报错:

Plugin with name Port not found. Step name: Port
debug1: ssh_exchange_identification:
ssh_exchange_identification: Connection closed by remote host

对应的add_host任务配置如下:

- name: create hosts inventory
  add_host:
    name: "{{item.tags.Name}}"
    groups: target_vm_group
    ansible_ssh_common_args: -o StrictHostKeyChecking=no -o ProxyCommand="sh -c \"aws ssm start-session --target %h --document-name AWS-StartSSHSession --profile xyz --debug --region us-east-1 --cli-read-timeout 0 --cli-connect-timeout 0 --parameters 'portNumber=%p'\""
    ansible_ssh_pass: "{{ssh_user}}"
    ansible_become_pass: "{{ssh_password}}"
    ansible_ssh_host: "{{item.instance_id}}"
    ansible_user: "{{ssh_user}}"
    env_ec2_name: "{{item.tags.Name}}"
    ip_address: "{{item.private_ip_address}}"
    instance_id: "{{item.instance_id}}"
    env_name: "{{item.tags.EnvironmentName}}"
  with_items: "{{ ec2s.instances }}"

问题分析与修复

1. 代理命令参数格式错误

AWS-StartSSHSession文档要求parameters参数为键值对形式,原配置中--parameters 'portNumber=%p'的单引号包裹格式不符合要求,会导致SSM无法识别参数,进而抛出Port插件错误。

修复方式:去掉单引号,改为--parameters portNumber=%p,或使用标准JSON格式--parameters '{"portNumber":["%p"]}'。

2. 变量赋值错误

ansible_ssh_pass被错误赋值为{{ssh_user}}(用户名),应改为{{ssh_password}},否则会导致SSH认证失败,间接引发连接关闭错误。

3. 优化代理命令可读性(可选)

原命令的引号转义过于复杂,可使用YAML的折叠换行符>-简化,同时移除不必要的--debug参数减少冗余日志:

ansible_ssh_common_args: >-
  -o StrictHostKeyChecking=no 
  -o ProxyCommand="aws ssm start-session --target %h --document-name AWS-StartSSHSession --profile xyz --region us-east-1 --cli-read-timeout 0 --cli-connect-timeout 0 --parameters portNumber=%p"

修复后的完整任务配置

- name: create hosts inventory
  add_host:
    name: "{{item.tags.Name}}"
    groups: target_vm_group
    ansible_ssh_common_args: >-
      -o StrictHostKeyChecking=no 
      -o ProxyCommand="aws ssm start-session --target %h --document-name AWS-StartSSHSession --profile xyz --region us-east-1 --cli-read-timeout 0 --cli-connect-timeout 0 --parameters portNumber=%p"
    ansible_ssh_pass: "{{ssh_password}}"
    ansible_become_pass: "{{ssh_password}}"
    ansible_ssh_host: "{{item.instance_id}}"
    ansible_user: "{{ssh_user}}"
    env_ec2_name: "{{item.tags.Name}}"
    ip_address: "{{item.private_ip_address}}"
    instance_id: "{{item.instance_id}}"
    env_name: "{{item.tags.EnvironmentName}}"
  with_items: "{{ ec2s.instances }}"

额外检查项

  • 执行Ansible的主机需安装AWS CLI,且xyz配置文件拥有ssm:StartSession权限。
  • 目标EC2实例需激活SSM Agent,且IAM角色关联AmazonSSMManagedInstanceCore策略。
  • 确认目标实例SSH服务正常运行,ansible_user拥有登录权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 03:45:40