首页 > 解决方案 > 使用 lambda 使用 boto3 创建 cloudwatch 仪表板

问题描述

我想为多个 EC2 创建 cloudwatch 仪表板,我无法将 JSON 仪表板置于错误状态,并使区域和 id 实例值可变

编码

from __future__ import print_function

import json

import boto3

def lambda_handler(event, context):

    ec2_client = boto3.client('ec2')
    CW_client = boto3.client('cloudwatch', region_name='eu-west-1')

    regions = [region['RegionName']
               for region in ec2_client.describe_regions()['Regions']]
    for region in regions:
        print('Instances in EC2 Region {0}:'.format(region))
        ec2 = boto3.resource('ec2',region_name=region)

        instances = ec2.instances.filter(
            Filters=[
                {'Name': 'tag:backup', 'Values': ['true']}
            ]
        )
        for i in instances.all():
            #for ID in i.InstanceId.all():
            print(i.id)
            instance_id = i.id
            response = CW_client.put_dashboard(DashboardName='test', DashboardBody='{"widgets": [{"type": "metric", "x": 12, "y": 0, "width": 12, "height": 6, "properties": {"metrics": [[ "AWS/EC2", "CPUUtilization", "InstanceId", instance_id ]], "view": "timeSeries", "stacked": false, "region": region, "stat": "Average", "period": 60, "title": "CPUUtilization" }}]}')

错误


  "errorMessage": "An error occurred (InvalidParameterInput) when calling the PutDashboard operation: The field DashboardBody must be a valid JSON object",
  "errorType": "DashboardInvalidInputError",

标签: pythonamazon-web-servicesaws-lambdaboto3amazon-cloudwatch

解决方案


DashboardBody包含文字字符串instance_idregion(不带引号)。这就是 JSON 无效的原因。您需要 and 的instance_idregion不是简单的单词instance_idand region

您应该使用字符串插值。例如:

region = "us-east-1"
instance_id = "i-1234567890"

partbody = '{"region":"%s", "instance_id":"%s"}' % (region, instance_id)

或者您可以使用 f-strings 但您必须引用大括号,如下所示:

partbody = f'{{"region":"{region}", "instance_id":"{instance_id}"}}'

这两个选项都会生成一个如下所示的字符串:

{"region":"us-east-1", "instance_id":"i-1234567890"}

请注意,我将向您展示如何使用字符串插值将变量值注入字符串。现在您需要执行此操作并将两者都region注入instance_id字符串DashboardBody中。例如:

DashboardBody='{"widgets": [{"type": "metric", "x": 12, "y": 0, "width": 12, "height": 6, "properties": {"metrics": [[ "AWS/EC2", "CPUUtilization", "InstanceId","%s" ]], "view": "timeSeries", "stacked": false, "region":"%s", "stat": "Average", "period": 60, "title": "CPUUtilization" }}]}' % (instance_id, region)

推荐阅读