如何使用 boto3 列出 CloudWatch 指标

How to list CloudWatch metrics using boto3

是否有人有一个 boto3 示例来说明如何获得与此 AWS CLI 命令相同的结果:

aws cloudwatch list-metrics --namespace "CWAgent" --metric-name "LogicalDisk % Free Space" --query Metrics[*]

我正在尝试获取这些维度的值:

instance, InstanceId, ImageId, objectname, InstanceType

这是我正在尝试使用的代码:

import boto3

# Create CloudWatch client
client = boto3.client('cloudwatch')

obj = []
response = client.list_metrics(
    Namespace='CWagent',
    MetricName='LogicalDisk % Free Space',
    Dimensions=[
        {
            'Name': 'instance',
            'Value': obj
        },
        {
            'Name': 'InstanceId',
            'Value': obj
        },
        {
            'Name': 'ImageId',
            'Value': obj
        },
        {
            'Name': 'objectname',
            'Value': obj
        },
        {
            'Name': 'InstanceType',
            'Value': obj
        },
    ],
    NextToken='string'
)

for r in response:
    a = instance
    b = InstanceId
    c = ImageId
    d = objectname
    e = InstanceType
    print(a, b, c, d, e)

此 boto3 代码将从单个实例或所有实例访问 CWAgent 指标维度,以了解您如何设置实例变量: `

import boto3

ec2 = boto3.resource('ec2')
instances = ec2.instances.filter(Filters=[{'Name': 'tag:Name', 'Values': ['MY_INSTANCE_NAME']}])

#instances = ec2.instances.all()

cw = boto3.client('cloudwatch')

for i in instances:
    a = i.instance_id

# List metrics through the pagination interface
    paginator = cw.get_paginator('list_metrics')
    for response in paginator.paginate(
        MetricName='LogicalDisk % Free Space',
        Namespace='CWAgent',
        Dimensions=[
        {'Name': 'instance'},
            {'Name': 'InstanceId', 'Value': a},
            {'Name': 'ImageId'},
            {'Name': 'objectname'},
            {'Name': 'InstanceType'}
        ],):
            print(response['Metrics'])

`