python - 使用 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",
解决方案
您DashboardBody
包含文字字符串instance_id
和region
(不带引号)。这就是 JSON 无效的原因。您需要 and 的值,instance_id
而region
不是简单的单词instance_id
and 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)
推荐阅读
- javascript - 如何修复类型无效 - 期望字符串(用于内置组件)或 react.js 中的类/函数?
- javascript - 在 React 和 Redux 中的下一个操作中使用先前调度的操作中的值
- javascript - 无法分配给对象“[object Object]”的只读属性“active”
- apache-flink - 为什么 Flink (RESTful) 作业的资源在启动集群时会受到工作目录的影响?
- content-management-system - 什么是 Prismic 中“切片”的 Contentful 等价物?
- hadoop - 工作节点指标未显示在浏览器(普罗米修斯)中?
- python-3.x - 向量化 scikit-learn/Python3 中的句子列表列表
- python - 使用 pandas/python 检查字典中是否不存在数据框的值
- flutter - 如何在flutter项目中使用http拦截器?
- powershell - 通过所有 AD 计算机对象使用 Powershell Get-ItemProperty