如何获取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命令获取。步骤如下:
- 从本地AWS配置文件(通常是
~/.aws/config)中找到MyProfile的SSO配置信息,复制以下字段:sso_account_id(你的AWS账号ID)sso_role_name(你通过SSO关联的IAM角色名)sso_region(SSO服务所在区域)
- 执行以下命令获取临时凭证(替换占位符为你的实际信息):
该命令会返回JSON格式的结果,包含临时的aws sso get-role-credentials \ --account-id 123456789012 \ --role-name AdministratorAccess \ --region us-east-1 \ --profile MyProfileaccessKeyId、secretAccessKey和sessionToken。 - 若需要单独提取某个字段,可结合
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
相关产品推荐
相关产品推荐

