Python 使用lambda使用boto3创建cloudwatch仪表板

Python 使用lambda使用boto3创建cloudwatch仪表板,python,amazon-web-services,aws-lambda,boto3,amazon-cloudwatch,Python,Amazon Web Services,Aws Lambda,Boto3,Amazon Cloudwatch,我想为多个EC2创建cloudwatch仪表板,但我无法将JSON仪表板设置为bady并使区域和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

我想为多个EC2创建cloudwatch仪表板,但我无法将JSON仪表板设置为bady并使区域和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",

您的
仪表板主体
包含文本字符串
实例id
区域
(不带引号)。这就是JSON无效的原因。您需要
实例id
区域
值,而不是简单的
实例id
区域

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

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

partbody = '{"region":"%s", "instance_id":"%s"}' % (region, instance_id)
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)
或者你可以使用f字串,但是你必须引用大括号,就像这样:

partbody = f'{{"region":"{region}", "instance_id":"{instance_id}"}}'
这两个选项都会生成如下所示的字符串:

{"region":"us-east-1", "instance_id":"i-1234567890"}
注意,我向您展示了如何使用字符串插值将变量值注入字符串。现在需要执行此操作,并将
区域
实例id
注入
仪表板主体
字符串。例如:

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

partbody = '{"region":"%s", "instance_id":"%s"}' % (region, instance_id)
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)

两种解决方案给出了错误信息:第一种解决方案给出了错误信息(“errorMessage”:“不支持%:“dict”和“tuple”的操作数类型”),第二种解决方案(“errorMessage”:“模块“lambda_函数”中的语法错误”:f字符串:嵌套太深的表达式(lambda_function.py,第27行)”您使用的是哪个版本的Python?Python版本3.8从第一个示例中删除了无关的大括号,但都没有给出运行时错误。您的代码中的
region
instance\u id
是否都是有效的字符串(如我的示例代码)?很抱歉,您使用额外的大括号是什么意思。是的,instance_id和region是stringsi感谢这不是问题所在,因为当我输入region和instance_id的值时,代码工作正常