背景介绍
跨账号的使用场景
一个大型的集团型企业,尤其是涉及到跨国业务比较多时,在选择云服务提供商时大多会选择目前综合能力最强的亚马逊云服务AWS,本人假设会选择AWS服务,然后在实际的应用过程会根据不同的事业部新建不同的子账号,不同的子账号会根据事业部所管理的业务购买不同的AWS 服务。
痛点
根据以上的使用场景,我们可以清楚的知道一个大型的集团型企业会有多个AWS 子账号,但是作为集团总部的管理者可能需要清楚的知道每个事业部在使用AWS时花费的成本,甚至一些技术leader还需要清楚的知道每一项支出用在什么服务上,我们假设一下如果这个集团企业开设的子账号有成百上千个的话,没有一个系统统一去管理这些子账号开设的服务,那就需要每个子账号的管理者定期的人工梳理费用明细,然后再汇总发给总部leader
解决方案
我们可以通过在指定的一个子账号下通过aws提供的sts服务访问其他子账号下的云资源,具体的代码示例如下:
以Python代码为例说明
```python
import boto3
role_arn = 'arn:aws-cn:iam::067822976751:role/dev-role-xxxx'
def assumed_role(role_arn):
'''
从当前账号切换待目标role:role_arn
返回目标role的信任关系
'''
sts_client = boto3.client('sts')
identity_role = sts_client.get_caller_identity()
current_account = identity_role ['Account']
if current_account != role_arn.split(':')[4]:
assumed_role_object = sts_client.assume_role(
RoleArn=role_arn,
RoleSessionName="Session"
)
credentials = assumed_role_object['Credentials']
print('Assume role successfully!')
return credentials
else:
return None
def get_s3_client(credentials,region_name):
'''
根据信任关系获取指定资源(比如S3)的客户端连接
'''
s3_object = boto3.client('s3', aws_access_key_id=self.credentials['AccessKeyId'], aws_secret_access_key=self.credentials['SecretAccessKey'],
aws_session_token=self.credentials['SessionToken'],
region_name=region_name)
return s3_object
credentials = assumed_role(role_arn)
s3_client = get_s3_client(credentials,'cn-northwest-1')