alkira/push.py

264 lines
8.0 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
2022-06-17 16:16:41 +02:00
parser = argparse.ArgumentParser(description="Push JSON config to 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("-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)")
parser.add_argument("-v", "--verbose", type=int, default=0, help="Verbose level 0 or 1 (default: 0)")
2022-06-17 12:45:57 +02:00
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 16:01:23 +02:00
# Set loglevel (logging.INFO, logging.DEBUG)
logging.basicConfig(level=loglevel)
logging = logging.getLogger('AlkiraAPI')
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)
2022-06-14 21:56:02 +02:00
###############################################
# Set default headers
headers = {'Content-Type': "application/json"}
# URL Exceptions
url_exceptions = {
2022-06-14 21:56:02 +02:00
"saas": "internet",
"pan": "panfw",
"ftntfw": "ftnt-fw-",
"chkpfw": "chkp-fw-",
"ocivcnconnectors": "oci-vcn-connectors",
"ftntfwservices": "ftnt-fw-services"
}
# URL Exceptions creating credentials
service_credentials = {
"panfwservices": "pan",
"ftntfwservices": "ftntfw"
}
# URL Exceptions creating instance credentials
service_instance_credentials = {
"ftntfwservices": "ftntfw-"
2022-06-14 21:56:02 +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:
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
def alkira_service(session, connector_name):
body = {
"credentials": {
"userName": "admin",
"password": "Blabla123"
},
"name": "fwcredentials01"
}
logging.debug(f'Received Connector: {connector_name}')
logging.info('=== Create Credentials')
if connector_name in service_credentials.keys():
credentials_url = service_credentials[connector_name]
logging.debug(f'URL: {credentials_url}')
response = alkira_post(session, f'/credentials/{credentials_url}', body)
json_body = response.json()
if response.status_code == 200:
fw_id = json_body['id']
logging.debug(f'credentialId: {fw_id}')
logging.info('=== Create Instance Credentials')
if connector_name in service_instance_credentials.keys():
credentials_url = service_instance_credentials[connector_name]
logging.debug(f'URL: {credentials_url}')
response = alkira_post(session, f'/credentials/{credentials_url}instance', body)
json_body = response.json()
if response.status_code == 200:
instance_id = json_body['id']
logging.debug(f'instance credentialId: {instance_id}')
return fw_id, instance_id
2022-06-14 21:56:02 +02:00
# 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-14 21:56:02 +02:00
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')
if 'service' in connector_name:
fw_id, instance_id = alkira_service(s, connector_name)
logging.debug(f'Got credentialId: {fw_id} AND {instance_id}')
2022-06-17 12:45:57 +02:00
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
2022-06-17 18:35:46 +02:00
if 'size' in body:
size = body['size']
logging.debug(f'JSON size: {size}')
if 'size' in section:
size = section['size']
logging.debug(f'CONFIG size: {size}')
body['size'] = size
if 'credentialId' in body and 'fw_id' in locals():
logging.debug(f'Set credentialId: {fw_id}')
body['credentialId'] = fw_id
if 'instances' in body:
if 'credentialId' in body['instances'][0] and 'instance_id' in locals():
logging.debug(f'Set instance credentialId: {instance_id}')
body['instances'][0]['credentialId'] = instance_id
print(json.dumps(body))
2022-06-17 12:45:57 +02:00
logging.debug(json.dumps(body))
logging.info(f'=== Pushing {connector_name} to {cxp} (size: {size}; segment: {segments})')
logging.debug(f'CONNECTOR BEFORE AGAIN: {connector_name}')
if connector_name in url_exceptions.keys():
connector_name = url_exceptions[connector_name]
logging.debug(f'CONNECTOR AFTER AGAIN: {connector_name}')
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)