alkira/push.py

190 lines
5.7 KiB
Python
Raw Normal View History

2022-06-14 21:56:02 +02:00
#!/usr/bin/env python3
#
# Copyright 2022, Mischa Peters <mischa AT alkira DOT net>, Alkira.
# push.py
# Version 0.1 - 20220617 - initial release
#
# 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 21:56:02 +02:00
import os
import sys
import re
import json
import time
import logging
import requests
import configparser
2022-06-17 12:45:57 +02:00
import argparse
# Parse all arguments
parser = argparse.ArgumentParser(description="Push JSON connfig to AlkirAPI")
parser.add_argument("-t", "--tenant", type=str, default='alkira.cnf', help="location of alikira.cnf (default: alkira.cnf")
2022-06-17 12:48:01 +02:00
parser.add_argument("-f", "--folder", type=str, default='config', help="location of the JSON connector files (default: config")
parser.add_argument("-c", "--config", type=str, default='connectors.cnf', help="location of the connector config (default: config/connectors.cnf")
2022-06-17 12:45:57 +02:00
parser.add_argument("-v", "--verbose", type=int, default=0, help="Verbose level 0 or 1 (default: 0")
try:
args = parser.parse_args()
2022-06-17 15:21:03 +02:00
ALKIRA_CONFIG = args.tenant
connector_folder = args.folder
2022-06-17 12:45:57 +02:00
CONNECTOR_CONFIG = f'{args.folder}/{args.config}'
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 21:56:02 +02:00
###############################################
2022-06-17 12:45:57 +02:00
# Tenant config
if not os.path.isfile(ALKIRA_CONFIG):
logging.error(f"The config file {ALKIRA_CONFIG} doesn't exist")
sys.exit(1)
alkira = configparser.RawConfigParser()
alkira.read(ALKIRA_CONFIG)
ALKIRA_TENANT = alkira.get('alkira', 'ALKIRA_TENANT')
ALKIRA_USERNAME = alkira.get('alkira', 'ALKIRA_USERNAME')
ALKIRA_PASSWORD = alkira.get('alkira', 'ALKIRA_PASSWORD')
2022-06-14 21:56:02 +02:00
ALKIRA_BASE_URI = f'https://{ALKIRA_TENANT}/api'
2022-06-17 12:45:57 +02:00
# Connector config
if not os.path.isfile(CONNECTOR_CONFIG):
logging.error(f"The config file {CONNECTOR_CONFIG} doesn't exist")
sys.exit(1)
config = configparser.ConfigParser()
config.read(CONNECTOR_CONFIG)
# Set loglevel (logging.INFO, logging.DEBUG)
logging.basicConfig(level=loglevel)
logging = logging.getLogger('AlkiraAPI')
2022-06-14 21:56:02 +02:00
###############################################
# Set default headers
headers = {'Content-Type': "application/json"}
# Naming exceptions
service_exceptions = {
"saas": "internet",
"pan": "panfw",
"ftntfw": "ftnt-fw-",
"chkpfw": "chkp-fw-"
}
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:
2022-06-17 12:45:57 +02:00
logging.error(f'Error: {str(e)}')
sys.exit(1)
2022-06-14 21:56:02 +02:00
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:
2022-06-17 12:45:57 +02:00
logging.error(f'Error: {str(e)}')
sys.exit(1)
2022-06-14 21:56:02 +02:00
return response
# Authenticate
s = alkira_login()
logging.debug(s)
# Get TenantID
r = alkira_get(s, '/tenantnetworks')
data = r.json()
tenantNetworkId = data[0]['id']
tenantName = data[0]['name']
logging.info(f'Tenant Name: {tenantName}')
logging.info(f'Tenant ID: {tenantNetworkId}')
# Push connectors
logging.info('Push Connectors')
2022-06-17 12:45:57 +02:00
for connector in config.sections():
section = config[connector]
connector_result = re.match(r'(\w+)(\d+)', connector)
connector_name = connector_result.group(1)
connector_number = connector_result.group(2)
logging.debug(f'{connector_folder}/{connector_name}{connector_number}.txt')
config_path = (f'{connector_folder}/{connector_name}{connector_number}.txt')
with open (config_path, 'r') as f:
body = json.load(f)
if 'cxp' in body:
cxp = body['cxp']
logging.debug(f'JSON cxp: {cxp}')
if 'cxp' in section:
cxp = section['cxp']
logging.debug(f'CONFIG cxp: {cxp}')
body['cxp'] = cxp
if 'segments' in body:
segments = body['segments'][0]
logging.debug(f'JSON segments: {segments}')
if 'segments' in section:
segments = section['segments']
logging.debug(f'CONFIG segments: {segments}')
body['segments'][0] = segments
if 'group' in body:
group = body['group']
logging.debug(f'JSON group: {group}')
if 'group' in section:
group = section['group']
logging.debug(f'CONFIG group: {group}')
body['group'] = group
if 'billingTags' in body:
billingtags = body['billingTags'][0]
logging.debug(f'JSON billingtags: {billingtags}')
if 'billingtags' in section:
billingtags = section['billingtags']
logging.debug(f'CONFIG billingtags: {billingtags}')
body['billingTags'][0] = billingtags
2022-06-17 12:45:57 +02:00
logging.debug(json.dumps(body))
logging.info(f'Pushing {connector_name} to {cxp} (network segment: {segments}; group: {group})')
2022-06-17 12:45:57 +02:00
r = alkira_post(s, f'/tenantnetworks/{tenantNetworkId}/{connector_name}', body)
logging.info(r.status_code)
logging.debug(r.content)