def agent_deleter()

in source/CRRdeployagent/CRRdeployagent.py [0:0]


def agent_deleter(agt_region, topic_name, queue_arn, monitor_account, agent_accounts):
    #
    # Deletion has to occur in a specific order
    #
    boto3.setup_default_session(region_name=agt_region)
    # -----------------------------------------------------------------
    # Create client connections
    #
    try:
        cwe = boto3.client('events')
        if not monitor_account:
            sns = boto3.client('sns')
    except Exception as e:
        print(e)
        print('Error creating Events client for ' + agt_region)
        raise e

    #------------------------------------------------------------------
    # Remove the CWE rule
    #
    # Rule name is different for Monitor/Agent vs Agent-only
    #
    rule = 'CRRRemoteAgent'

    if not monitor_account:
        rule = 'CRRAgent'
    # 
    # Remove the Targets
    #
    try:
        cwe.remove_targets(
            Rule=rule,
            Ids=[
                rule + '-' + agt_region,
            ]
        )
    except Exception as e:
        print(e)
        print('Failed to remove target ' + rule + ' id ' + rule + '-' + agt_region)

    # For Manager/Agent account, remove the SNS topic
    if not monitor_account:
        topic = topic_name + "-" + agt_region
        print("Delete " + topic + " in " + agt_region)
        # -----------------------------------------------------------------
        # RequestType Delete
        #
        sts = boto3.client('sts')
        myaccount = sts.get_caller_identity()['Account']
        topicarn = 'arn:aws:sns:' + agt_region + ':' + myaccount + ':' + topic
        # Delete the SNS topic
        sns.delete_topic(
            TopicArn=topicarn
        )

    # Delete the CW rule
    cwe.delete_rule(
        Name=rule
    )

    if not monitor_account:
        # Remove permissions to the default event bus
        for account in agent_accounts:
            try:
                cwe.remove_permission(
                    StatementId=account
                )
            except Exception as e:
                print(e)
                print('Error removing Event Bus permissions for ' + account)

    return {}