如何使用python在AWS中执行交叉帐户(使用角色arn)?

时间:2019-12-10 10:37:25

标签: python python-3.x amazon-web-services boto3 roles

我试图使用arns in列表连接到多个aw帐户,但是每次它仅对给定列表中的第一个arn有效,而第二次失败。 我删除了第一个Aarn,然后再次删除了它,第二个和第三个都失败了。

    for arn in ROLE_ARN:
        print(arn)
        my_session = arn.split(':')[4]
        my_session = 'script-' + my_session 
        sts_client = STSConnection()
        assumed_role_object=sts_client.assume_role(
        role_arn=arn,
        role_session_name=my_session)

        os.environ["AWS_ACCESS_KEY_ID"] = assumed_role_object.credentials.access_key
        os.environ["AWS_SECRET_ACCESS_KEY"] = assumed_role_object.credentials.secret_key
        os.environ["AWS_SESSION_TOKEN"] = assumed_role_object.credentials.session_token
        print (assumed_role_object.credentials.access_key)
        print (assumed_role_object.credentials.secret_key)
        print (assumed_role_object.credentials.session_token)

        account_name = subprocess.getoutput("aws iam list-account-aliases --output text | awk '{print $2}'")
        print (account_name)
        account_id = (boto3.client('sts').get_caller_identity()['Account'])
        print (account_id)

错误:

Traceback (most recent call last):
  File "aws_security_cost_audit.py", line 432, in <module>
    main()
  File "aws_security_cost_audit.py", line 426, in main
    for_ports_and_iam()
  File "aws_security_cost_audit.py", line 402, in for_ports_and_iam
    role_session_name=my_session)
  File "/usr/local/lib/python3.4/dist-packages/boto/sts/connection.py", line 384, in assume_role
    return self.get_object('AssumeRole', params, AssumedRole, verb='POST')
  File "/usr/local/lib/python3.4/dist-packages/boto/connection.py", line 1208, in get_object
    raise self.ResponseError(response.status, response.reason, body)
boto.exception.BotoServerError: BotoServerError: 403 Forbidden
<ErrorResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/">
  <Error>
    <Type>Sender</Type>
    <Code>InvalidClientTokenId</Code>
    <Message>The security token included in the request is invalid.</Message>
  </Error>

2 个答案:

答案 0 :(得分:0)

您可以在命令中包含aws凭证

for arn in ROLE_ARN:
    print(arn)
    my_session = arn.split(':')[4]
    my_session = 'script-' + my_session 
    sts_client = STSConnection()
    assumed_role_object=sts_client.assume_role(
    role_arn=arn,
    role_session_name=my_session)

    print (assumed_role_object.credentials.access_key)
    print (assumed_role_object.credentials.secret_key)
    print (assumed_role_object.credentials.session_token)

    credential = 'AWS_SESSION_TOKEN=\"{}\" AWS_ACCESS_KEY_ID=\"{}\" AWS_SECRET_ACCESS_KEY=\"{}\"'.format(
      assumed_role_object.credentials.session_token,
      assumed_role_object.credentials.access_key,
      assumed_role_object.credentials.secret_key
    )

    command =  credential + " aws iam list-account-aliases --output text | awk '{print $2}'"
    print('command: ', command)
    account_name = subprocess.getoutput(command)

    print (account_name)
    account_id = (boto3.client('sts', aws_access_key_id=assumed_role_object.credentials.access_key, 
      aws_secret_access_key=assumed_role_object.credentials.secret_key, 
      aws_session_token=assumed_role_object.credentials.session_token).get_caller_identity()['Account'])
    print('accountId: ', account_id)

答案 1 :(得分:0)

在进行一次谷歌搜索之后,我通过创建一个boto3.session并使用此名称session调用其他boto3客户端函数来解决了该问题。 示例代码:

session = boto3.Session(                                                                                                                                    
aws_access_key_id=creds['AccessKeyId'],                                                                                                                     
aws_secret_access_key=creds['SecretAccessKey'],                                                                                                             
aws_session_token=creds['SessionToken']) 
for region in all_regions_list:                                                                                                                                 
ec2 = session.client('ec2', region_name=region)