Amazon-Web-Services

使用 lambda+boto3 訪問自定義 cloudwatch 指標?

  • September 13, 2019

我有一個自定義指標,我可以從 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'}
   ]
)

指標的數據確實存在: 在此處輸入圖像描述

那麼,我怎樣才能得到它?

非常愚蠢的錯誤:

'Value': 'instance.id'

應該

'Value': instance.id

因為instance.id是一個變數。

引用自:https://serverfault.com/questions/824510