使用 lambda+boto3 访问自定义 cloudwatch 指标?

使用 lambda+boto3 访问自定义 cloudwatch 指标?

我有一个自定义指标,我可以从 bash 中获取数据:

aws cloudwatch get-metric-statistics --namespace System/Detail/Linux \
--metric-name LoadAverage1Min --start-time 2017-01-04T00:00:00 \
--end-time 2017-01-04T02:00:00 --period 60 --statistics Average \
--dimensions Name=InstanceId,Value=i-03d55dba88912f054
{
    "Datapoints": [
        {
            "Timestamp": "2017-01-04T00:33:00Z",
            "Average": 0.0,
            "Unit": "Count"
        },
        {
            "Timestamp": "2017-01-04T01:44:00Z",
            "Average": 0.0,
... etc...

但它不适用于 lambda。问题是:如何获取自定义指标的数据?

我正在尝试使用 lambda 和 boto3 来做理智的事情(抱歉,我是 Python 初学者):

import boto3
import logging
from datetime import datetime
from datetime import timedelta

#setup simple logging for INFO
logger = logging.getLogger()
logger.setLevel(logging.INFO)

#define the connection
ec2 = boto3.resource('ec2')
cw = boto3.client('cloudwatch')

def lambda_handler(event, context):
    # Use the filter() method of the instances collection to retrieve
    # all running EC2 instances.
    filters = [{
            'Name': 'instance-state-name', 
            'Values': ['running']
        }
    ]

    #filter the instances
    instances = ec2.instances.filter(Filters=filters)

    #locate all running instances
    RunningInstances = [instance.id for instance in instances]

    dnow = datetime.now()

    for instance in instances:
        inst_name = [tag['Value'] for tag in instance.tags if tag['Key'] == 'Name'][0]
        if inst_name != 'instances-name-i-need':
            continue

        response = cw.get_metric_statistics(
            Namespace='System/Detail/Linux',
            MetricName='LoadAverage1Min',
            Dimensions=[
                {
                    'Name': 'InstanceId',
                    'Value': 'instance.id'
                },
            ],
            StartTime=dnow+timedelta(hours=-15),
            EndTime=dnow,
            Period=300,
            Statistics=['Average']
        )
        print response

但是当我通过 lambda 测试运行该函数时我只收到空的响应:

{u'Datapoints': [], 'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': '98ee...6ba', 'HTTPHeaders': {'x-amzn-requestid': '98ee...6ba', 'date': 'Thu, 05 Jan 2017 22:52:12 GMT', 'content-length': '338', 'content-type': 'text/xml'}}, u'Label': 'LoadAverage1Min'}
{u'Datapoints': [], 'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': '98f4...a01', 'HTTPHeaders': {'x-amzn-requestid': '98f4...a01', 'date': 'Thu, 05 Jan 2017 22:52:13 GMT', 'content-length': '338', 'content-type': 'text/xml'}}, u'Label': 'LoadAverage1Min'}
{u'Datapoints': [], 'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': '98f8...764', 'HTTPHeaders': {'x-amzn-requestid': '98f8...764', 'date': 'Thu, 05 Jan 2017 22:52:13 GMT', 'content-length': '338', 'content-type': 'text/xml'}}, u'Label': 'LoadAverage1Min'}

但是我可以使用以下命令从 AWS 命名空间获取数据

response = cw.get_metric_statistics(
    Namespace='AWS/S3',MetricName='BucketSizeBytes',
    StartTime=datetime.utcnow() - timedelta(days=2) ,
    EndTime=datetime.utcnow(), Period=86400,
    Statistics=['Average'], Unit='Bytes',
    Dimensions=[
        {'Name': 'BucketName', 'Value': 'bucket-name'},
        {u'Name': 'StorageType', u'Value': 'StandardStorage'}
    ]
)

该指标的数据确实存在: 在此处输入图片描述

那么,我怎样才能得到它?

答案1

非常愚蠢的错误:

'Value': 'instance.id'

应该

'Value': instance.id

因为instance.id是一个变量。

相关内容