如何在通过SSO凭证连接时使用AWS Python SDK

问题描述 投票:1回答:1

我正试图创建一个python脚本来连接到我的AWS账户并与之交互。我在这里阅读了一下 https:/boto3.amazonaws.comv1documentationapilatestguidequickstart.html。

我看到它从~.awscredentials读取你的证书(在Linux机器上)。然而,我并不是与IAM用户连接,而是与SSO用户连接。因此,我使用的配置文件连接数据位于~.awsssocache目录下。

在该目录下,我看到两个json文件。其中一个文件有以下键。

  • startUrl
  • 地区
  • 访问令牌
  • 过期时间

第二个有以下键。

  • clientId
  • 客户端秘密
  • 过期时间

我在文档中没有看到任何地方告诉它如何使用我的SSO用户。

因此,当我试着运行我的脚本时,我得到了如下错误信息。

botocore.exceptions.ClientError: An error occurred (AuthFailure) when calling the DescribeSecurityGroups operation: AWS was not able to validate the provided access credentials

尽管我可以在命令提示符下运行相同的命令。

python amazon-web-services single-sign-on boto
1个回答
0
投票

你当前的.awsssocache文件夹结构看起来像这样。

$ ls
botocore-client-XXXXXXXX.json       cXXXXXXXXXXXXXXXXXXX.json

2个json文件包含了3个不同的有用参数。

botocore-client-XXXXXXXX.json -> clientId and clientSecret
cXXXXXXXXXXXXXXXXXXX.json -> accessToken

使用cXXXXXXXXXXXXXXXXXXXXX.json中的访问令牌,你可以调用 获取角色证书. 这个命令的输出可以用来创建一个新的会话。

你的Python文件应该是这样的。

import json
import os
import boto3

dir = os.path.expanduser('~/.aws/sso/cache')

json_files = [pos_json for pos_json in os.listdir(dir) if pos_json.endswith('.json')]

for json_file in json_files :
    path = dir + '/' + json_file
    with open(path) as file :
        data = json.load(file)
        if 'accessToken' in data:
            accessToken = data['accessToken']

client = boto3.client('sso',region_name='us-east-1')
response = client.get_role_credentials(
    roleName='string',
    accountId='string',
    accessToken=accessToken
)

session = boto3.Session(aws_access_key_id=response['roleCredentials']['accessKeyId'], aws_secret_access_key=response['roleCredentials']['secretAccessKey'], aws_session_token=response['roleCredentials']['sessionToken'], region_name='us-east-1')
© www.soinside.com 2019 - 2024. All rights reserved.