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

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

我正在尝试获取帐户的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,但是当我在代码中生成区域时,我不想指定它们。

python amazon-web-services boto amazon-cloudwatch
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.