简体   繁体   中英

Deleting all the CloudWatch rules using boto3

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.

  1. Get the list of Name of all the rules you have using list_rules
  2. Use iteration to delete all your rules, one by one, using using delete_rule .
client = 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:

  1. Get list of your rules using list_rules method;
  2. Loop through the list of rules and within each iteration:

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.

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