We have ton of cloudwatch rules that we need to get rid of, I was working on a python script, to delete all the CloudWatch rules, but I could only find the delete rule for a specific rule on boto3 website, but I want to delete all the rules we have.
import boto3
client = boto3.client('events')
response = client.delete_rule(
Name='string'
)
You have to do it in two stages.
Name
of all the rules you have using list_rulesclient = boto3.client('events')
rule_names = [rule['Name'] for rule in client.list_rules()['Rules']]
for rule_name in rule_names:
response = client.delete_rule(Name=rule_name)
print(response)
Depending on how many rules you actually have, you may need to run list_rules
multiple times with NextToken
.
As CloudWatch Event Rule usually has at least one target, you need to:
So the resulting script will look like this:
import boto3
client = boto3.client('events')
rules = client.list_rules()['Rules']
for rule in rules:
rule_targets = client.list_targets_by_rule(
Rule=rule['Name']
)['Targets']
target_ids = [target['Id'] for target in rule_targets]
remove_targets_response = client.remove_targets(
Rule=rule['Name'],
Ids=target_ids
)
print(remove_targets_response)
delete_rule_response = client.delete_rule(
Name=rule['Name']
)
print(delete_rule_response)
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.