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

如何获取AWS SSO认证后的Access Key与Secret Key用于脚本?

解决AWS SSO认证后无法获取静态密钥的问题

首先明确:通过aws sso login生成的是临时会话凭证,并非存储在AWS配置文件中的静态access_key和secret_key,这就是为什么aws configure get命令返回空且退出码为1的原因——该命令仅用于读取静态配置的密钥,而SSO凭证是动态缓存的临时凭证。

推荐方案:直接使用SSO Profile运行脚本

不需要手动提取密钥,AWS CLI和SDK会自动从本地缓存读取临时SSO凭证,只要你已经执行过aws sso login --profile MyProfile,在脚本中直接指定该profile即可:

  • CLI命令示例:aws ec2 describe-instances --profile MyProfile
  • 代码示例(以Python Boto3为例):
    import boto3
    session = boto3.Session(profile_name='MyProfile')
    ec2 = session.client('ec2')
    response = ec2.describe_instances()
    

若必须提取临时凭证(不推荐)

如果你的脚本确实需要明文临时密钥,可以使用aws sso get-role-credentials命令获取。步骤如下:

  1. 从本地AWS配置文件(通常是~/.aws/config)中找到MyProfile的SSO配置信息,复制以下字段:
    • sso_account_id(你的AWS账号ID)
    • sso_role_name(你通过SSO关联的IAM角色名)
    • sso_region(SSO服务所在区域)
  2. 执行以下命令获取临时凭证(替换占位符为你的实际信息):
    aws sso get-role-credentials \
      --account-id 123456789012 \
      --role-name AdministratorAccess \
      --region us-east-1 \
      --profile MyProfile
    
    该命令会返回JSON格式的结果,包含临时的accessKeyId、secretAccessKey和sessionToken。
  3. 若需要单独提取某个字段,可结合jq工具(需提前安装):
    # 获取临时Access Key
    aws sso get-role-credentials --account-id 123456789012 --role-name AdministratorAccess --region us-east-1 --profile MyProfile | jq -r '.roleCredentials.accessKeyId'
    # 获取临时Secret Key
    aws sso get-role-credentials --account-id 123456789012 --role-name AdministratorAccess --region us-east-1 --profile MyProfile | jq -r '.roleCredentials.secretAccessKey'
    

注意:临时凭证有有效期(通常为1小时),过期后需要重新执行aws sso login或再次调用get-role-credentials刷新,且不建议将这类凭证硬编码到脚本中,优先使用Profile方式更安全便捷。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 23:07:21