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

如何在AWS SSH命令中将--profile作为变量传递并应用到ProxyCommand

方案1:通过环境变量动态传递profile(无需修改配置适配多profile)

首先调整~/.ssh/config配置,让ProxyCommand自动识别环境变量中的AWS_PROFILE参数,不需要写死固定profile名称:

# SSH over Session Manager
host i-* mi-*
    ProxyCommand sh -c "aws ssm start-session ${AWS_PROFILE:+--profile \"${AWS_PROFILE}\"} --target %h --document-name AWS-StartSSHSession --parameters 'portNumber=%p'"

上述配置中${AWS_PROFILE:+--profile \"${AWS_PROFILE}\"}是Shell参数扩展语法:仅当AWS_PROFILE环境变量存在且非空时,才会自动拼接--profile 你的profile名参数,不会影响默认profile的正常使用。

使用时只需要在SSH命令前指定对应profile即可:

AWS_PROFILE=<Profile_Name> ssh -i <File.pem> -L <Local_Port>:<Remote_Port> ubuntu@i-<HOST_Name> -N -v -v

如果需要在当前终端会话下多次使用同一个profile,可以先全局导出环境变量,后续SSH命令无需额外加参数:

export AWS_PROFILE=<Profile_Name>
# 后续所有SSH命令都会自动使用上述profile
ssh -i <File.pem> ubuntu@i-<HOST_Name>

方案2:按profile配置独立Host规则(适合固定多环境场景)

如果常用的profile数量不多,可以直接在~/.ssh/config中给不同profile配置独立的Host匹配前缀:

# 开发环境profile对应规则
host dev-i-* dev-mi-*
    ProxyCommand sh -c "aws ssm start-session --profile dev --target %h --document-name AWS-StartSSHSession --parameters 'portNumber=%p'"

# 生产环境profile对应规则
host prod-i-* prod-mi-*
    ProxyCommand sh -c "aws ssm start-session --profile prod --target %h --document-name AWS-StartSSHSession --parameters 'portNumber=%p'"

使用时只要给实例ID加上对应前缀即可自动匹配对应profile,无需额外传参:

# 连接dev环境下ID为i-12345678的实例
ssh ubuntu@dev-i-12345678

注意事项

请确保你使用的profile已经提前在~/.aws/credentials或~/.aws/config中完成配置,否则AWS CLI会抛出找不到profile的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 12:48:03