简体   繁体   中英

How to enable/disable a rule in AWS EventBridge using Python/Boto3

How can you enable/disable an Event Bridge rule that schedules a Lambda Function.

The longer term goal is to turn off the schedule on certain holidays, so my next task is to see if there are any good holiday/management libraries. The first task was just to see if I could enable/disable the Event Bridge rule from a python program.

I first took this line from an S3 test I had working:

s3_resource = boto3.resource('s3') 

and changed it to

resource = boto3.resource('events') 

It returned the following error: boto3.exceptions.ResourceNotExistsError: The 'events' resource does not exist. The available resources are:

  • cloudformation
  • cloudwatch
  • dynamodb
  • ec2
  • glacier
  • iam
  • opsworks
  • s3
  • sns
  • sqs

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/events.html#eventbridge

I used pip to upgrade my boto release 1.17.57.

pip install boto3 --upgrade -t . 
pip install botocore --upgrade -t . 

I installed locally so I can zip this to a Lambda function eventually. I had to change resource to client as the method.

import uuid
import boto3
import os
import pprint

client = boto3.client('events') 
action = "enable"
myRulename = 'PolygonIOAPIDataCollectorMarketHours'

if action == "enable":
    response = client.enable_rule(
        Name=myRulename
    )
else:
    response = client.disable_rule(
        Name=myRulename
    )

pprint.pprint(response)

The first run, I got a security error, and had to add a policy to the IAM user.

It returns:

{'ResponseMetadata': {'HTTPHeaders': {'content-length': '0',
                                      'content-type': 'application/x-amz-json-1.1',
                                      'date': 'Wed, 09 Sep 2020 02:01:32 GMT',
                                      'x-amzn-requestid': '6d1de8cc-1c82-4a7f-956a-ad33e6e8c899'},
                      'HTTPStatusCode': 200,
                      'RequestId': '6d1de8cc-1c82-4a7f-956a-ad33e6e8c899',
                      'RetryAttempts': 0}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM