def assume_role(self,account_id, role_name, duration, external_id):
role_arn = "arn:aws:iam::" + account_id + ":role/" + role_name
role_session_name = "AssumeRoleSession"
client = boto3.client('sts', 'us-east-2')
response = client.assume_role(RoleArn=role_arn,
RoleSessionName=role_session_name,
DurationSeconds=duration,
ExternalId=external_id
)
tmp_credentials = {
'access-key-id': response['Credentials']['AccessKeyId'],
'secret-access-key': response['Credentials']['SecretAccessKey'],
'session-token':response['Credentials']['SessionToken']
}
return tmp_credentials
def create_clients(self, account_credentials):
account_id = account.get('account-id')
role_name = account.get('role-name')
duration = 3600
external_id = account.get('external-id')
region_name= account.get('region-name')
tmp_credentials = self.assume_role(account_id,role_name,duration,external_id)
xray_client = boto3.client('xray',
aws_access_key_id=tmp_credentials.get('access-key-id'),
aws_secret_access_key=tmp_credentials.get('secret-access-key'),
aws_session_token=tmp_credentials.get('session-token'),
region_name=region_name)
现在我这样做:
response = xray_client.get_service_graph(StartTime=start_time,
EndTime=end_time)
print(f"response: {response}")
我得到的回应是不正确的,它是
response: {'ResponseMetadata': {'RequestId': '0fa2d89c-4adf-4816-b86e-240cff3fdad6', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Sat, 15 May 2021 12:54:50 GMT', 'content-type': 'application/json', 'content-length': '97', 'connection': 'keep-alive', 'x-amzn-requestid': '0fa2d89c-4adf-4816-b86e-240cff3fdad6'}, 'RetryAttempts': 0}, 'Services': [], 'ContainsOldGroupVersions': False}
看到响应中的Services值是一个空列表[],那就是问题所在。如果我使用帐户永久 access_key_id 和 secret_key_id 而不是 tmp_credentials (id,id,sessionToken) 直接访问 xray,我会在服务列表中获得多个服务。我遵循的参考资料是:
https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html
此外,还使用 awsXrayFullAccess 策略和多个其他策略在目标 AWS 账户中正确配置了角色。