Cloudwatch API:如何使用多个AWS帐户

时间:2018-08-16 05:59:52

标签: python amazon-web-services boto amazon-cloudwatch

我正在尝试获取帐户的ec2实例的cpu利用率。我的代码如下。

    def GetRegions():
        return array of regions

    def getEC2InstanceID(RegionName):
         cloudwatch = boto3.client('cloudwatch', region_name=RegionName)
         response = cloudwatch.get_metric_statistics(
         .
         .
         .)
        returns array of ec2instanceID

    def EC2_Average_Utilization(InstanceID, RegionName):
        returns avg cpuusage 


def main():
    regions= GetRegions()
    for i in range(len(regions)):
        print(regions[i])
        instance_id = getEC2InstanceID(regions[i])
        print(instance_id)  # prints all the instances if there is any
        if (type(instance_id)==list):
            for j in range(len(instance_id)):
                print(instance_id[j])
                print ("For InstanceID "+ instance_id[j] +  ":")
                EC2_Average_Utilization(instance_id[j], regions[i])

此代码仅需一个帐户即可在所有区域完美执行。如果我想对多个AWS账户执行相同的操作,将采取什么步骤?

n.b我已经看到了通过在.aws / credentials中的每个帐户下创建多个配置文件来配置.aws / config的方法,但是由于在代码中生成区域时,我不想指定它们。

1 个答案:

答案 0 :(得分:0)

对于每个帐户/区域组合,您将需要使用boto3 Session对象,“安全令牌服务(STS)”和对assume_role的调用。效果与命名配置文件相同-您需要在每个帐户中都具有一个角色,该角色具有足够的权限来调用API方法(EC2,CloudWatch等)。此外,目标角色需要建立与原始帐户凭据的信任关系。

sts = boto3.client('sts')

#this is called with your default credentials. Target roles need to trust this identity
creds = sts.assume_role(RoleArn='...', RoleSessionName='...')

# set up a session w/ the temporary credentials
session = boto3.Session(
    aws_access_key_id=creds['Credentials']['AccessKeyId'],
    aws_secret_access_key=creds['Credentials']['SecretAccessKey'],
    aws_session_token=creds['Credentials']['SessionToken']
    region_name='...')

# all subsequent clients/resources should be instantiated from the session object
cloudwatch = session.client('cloudwatch')

希望这会有所帮助。

请参见https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sts.html#STS.Client.assume_role