alkira/clean.py

164 lines
4.7 KiB
Python
Raw Normal View History

2022-06-14 17:00:00 +02:00
#!/usr/bin/env python3
#
# Copyright 2022, Mischa Peters <mischa AT alkira DOT net>, Alkira.
# clean.py
# Version 0.1 - 20220617 - initial release
# Version 0.2 - 20220621 - simplified structure, prepare for -i remove for single ID
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
2022-06-14 17:00:00 +02:00
import os
import sys
import re
import json
import time
import logging
import requests
import configparser
2022-06-17 15:53:16 +02:00
import argparse
# Parse all arguments
2022-06-17 16:16:41 +02:00
parser = argparse.ArgumentParser(description="Clean Alkira tenant config with AlkiraAPI")
2022-06-17 16:01:23 +02:00
parser.add_argument("-t", "--tenant", type=str, default='alkira.cnf', help="location of alikira.cnf (default: alkira.cnf)")
#parser.add_argument("-i", "--id", type=str, help="remove specific id")
2022-06-17 16:01:23 +02:00
parser.add_argument("-v", "--verbose", type=int, default=0, help="Verbose level 0 or 1 (default: 0)")
2022-06-17 15:53:16 +02:00
parser.add_argument("-p", "--pretty", help="make the JSON pretty!", action="store_true")
try:
args = parser.parse_args()
ALKIRA_CONFIG = args.tenant
except argparse.ArgumentError as e:
print(str(e))
sys.exit()
try:
loglevel = {
0: logging.INFO,
1: logging.DEBUG
}[args.verbose]
except KeyError:
loglevel = logging.INFO
2022-06-14 17:00:00 +02:00
###############################################
2022-06-17 16:01:23 +02:00
# Set logging.INFO to logging.DEBUG for debug information
logging.basicConfig(level=loglevel)
logging = logging.getLogger('AlkiraAPI')
2022-06-17 15:53:16 +02:00
# Tenant config
2022-06-17 12:45:57 +02:00
if not os.path.isfile(ALKIRA_CONFIG):
logging.error(f"The config file {ALKIRA_CONFIG} doesn't exist")
2022-06-14 17:00:00 +02:00
sys.exit(1)
2022-06-17 12:45:57 +02:00
alkira = configparser.RawConfigParser()
alkira.read(ALKIRA_CONFIG)
2022-06-14 17:00:00 +02:00
2022-06-17 12:45:57 +02:00
ALKIRA_TENANT = alkira.get('alkira', 'ALKIRA_TENANT')
ALKIRA_USERNAME = alkira.get('alkira', 'ALKIRA_USERNAME')
ALKIRA_PASSWORD = alkira.get('alkira', 'ALKIRA_PASSWORD')
2022-06-14 17:00:00 +02:00
ALKIRA_BASE_URI = f'https://{ALKIRA_TENANT}/api'
###############################################
# Set default headers
headers = {'Content-Type': "application/json"}
2022-06-14 21:23:52 +02:00
# Naming exceptions
url_exceptions = {
2022-06-14 22:00:13 +02:00
"ocivcn": "oci-vcn-",
2022-06-14 21:23:52 +02:00
"saas": "internet",
"pan": "panfw",
"ftntfw": "ftnt-fw-",
2022-06-17 18:27:23 +02:00
"chkpfw": "chkp-fw-",
2022-06-14 21:23:52 +02:00
}
2022-06-14 17:00:00 +02:00
def alkira_login():
body = {'userName': ALKIRA_USERNAME,
'password': ALKIRA_PASSWORD}
session = requests.session()
response = alkira_post(session, '/login', body)
return session
def alkira_post(session, uri, body):
url = f'{ALKIRA_BASE_URI}{uri}'
try:
response = session.post(url, data=json.dumps(body), headers=headers)
response.raise_for_status()
except Exception as e:
logging.error(f'Error: {str(e)}')
sys.exit(1)
return response
def alkira_get(session, uri):
url = f'{ALKIRA_BASE_URI}{uri}'
try:
response = session.get(url, headers=headers)
response.raise_for_status()
except Exception as e:
logging.error(f'Error: {str(e)}')
sys.exit(1)
return response
def alkira_delete(session, uri):
url = f'{ALKIRA_BASE_URI}{uri}'
try:
response = session.delete(url, headers=headers)
response.raise_for_status()
except Exception as e:
logging.error(f'Error: {str(e)}')
sys.exit(1)
return response
# Authenticate
2022-06-20 20:34:54 +02:00
logging.info('=== Authenticating')
2022-06-14 17:00:00 +02:00
s = alkira_login()
logging.debug(s)
# Get TenantID
2022-06-20 20:37:55 +02:00
logging.info('=== Fetching Tenant Info')
2022-06-14 17:00:00 +02:00
r = alkira_get(s, '/tenantnetworks')
data = r.json()
tenantNetworkId = data[0]['id']
2022-06-14 21:23:52 +02:00
tenantName = data[0]['name']
logging.info(f'Tenant Name: {tenantName}')
logging.info(f'Tenant ID: {tenantNetworkId}')
2022-06-14 17:00:00 +02:00
to_clean = [
'connectors',
'services',
'global-cidr-lists'
]
for i in to_clean:
logging.info(f'=== Collecting {i}')
r = alkira_get(s, f'/tenantnetworks/{tenantNetworkId}/{i}')
data = r.json()
if args.pretty:
logging.debug(json.dumps(data, indent=4))
else:
logging.debug(json.dumps(data))
for item in data:
name = item.get('name')
id = item.get('id')
if 'type' in item:
type = item.get('type').lower().replace('_', '')
else:
type = ""
if type in url_exceptions.keys():
type = url_exceptions[type]
logging.debug(f'/tenantnetworks/{tenantNetworkId}/{type}{i}/{id}')
logging.info(f'=== Removing {name[:30]} ({type})')
r = alkira_delete(s, f'/tenantnetworks/{tenantNetworkId}/{type}{i}/{id}')
logging.info(r.status_code)