我正在尝试获取帐户的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,但是当我在代码中生成区域时,我不想指定它们。
您将需要使用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')
希望这可以帮助。