您可以通过以下方式解决此问题:
import json
event_pattern = '{"source": ["aws.ec2"], "detail-type": ["EC2 Instance State-change Notification"]}'
try:
json.loads(event_pattern)
except json.JSONDecodeError as e:
print("Invalid EventPattern JSON:", e)
import boto3
import json
event_pattern = {
"source": ["aws.ec2"],
"detail-type": ["EC2 Instance State-change Notification"]
}
client = boto3.client('events')
response = client.put_rule(
Name='my-rule',
EventPattern=json.dumps(event_pattern)
)
请注意,如果您提供的EventPattern无效,AWS boto3将引发InvalidEventPatternException异常。您可以通过捕获和处理此异常来识别和解决问题。例如:
import boto3
import json
from botocore.exceptions import ClientError
event_pattern = {
"source": ["aws.ec2"],
"detail-type": ["EC2 Instance State-change Notification"]
}
client = boto3.client('events')
try:
response = client.put_rule(
Name='my-rule',
EventPattern=json.dumps(event_pattern)
)
except ClientError as e:
if e.response['Error']['Code'] == 'InvalidEventPatternException':
print("Invalid EventPattern:", e.response['Error']['Message'])
else:
print("An error occurred:", e)
这些解决方法应该能够帮助您解决“AWS boto3 CloudWatch Events put_rule - 参数EventPattern的类型无效。”的问题。