commit 8fb2495f34221174beddd74a18f2df9b83233476 from: mischa date: Tue Jul 05 17:22:37 2022 UTC change name -debug -> -json, and prepare for Azure account credentials (akadmin) commit - 64a452481d443d3cb3efbd9a209f12ddb542d3e4 commit + 8fb2495f34221174beddd74a18f2df9b83233476 blob - /dev/null blob + 9ea64ac22f8a9d1c94eafbec9af153e65c3678b5 (mode 755) --- /dev/null +++ push-json.py @@ -0,0 +1,260 @@ +#!/usr/bin/env python3 +# +# Copyright 2022, Mischa Peters , Alkira. +# push-debug.py +# Version 0.1 - 20220617 - initial release +# Version 0.2 - 20220621 - simplified structure, generic +# +# 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. +# +import os +import sys +import re +import json +import time +import logging +import requests +import configparser +import argparse + +# Parse all arguments +parser = argparse.ArgumentParser(description="Push single JSON file to AlkiraAPI (debug)") +parser.add_argument("-t", "--tenant", type=str, default='alkira.cnf', help="location of alikira.cnf (default: alkira.cnfi)") +parser.add_argument("-f", "--file", type=str, help="location of the JSON connector file") +parser.add_argument("-p", "--pretty", help="make the JSON pretty!", action="store_true") +parser.add_argument("-v", "--verbose", type=int, default=0, help="Verbose level 0 or 1 (default: 0)") + +if len(sys.argv)==1: + parser.print_help(sys.stderr) + sys.exit(1) + +try: + args = parser.parse_args() + ALKIRA_CONFIG = args.tenant + connector = args.file +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 + +############################################### + +# Set loglevel (logging.INFO, logging.DEBUG) +logging.basicConfig(level=loglevel) +logging = logging.getLogger('AlkiraAPI') + +# 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') +ALKIRA_BASE_URI = f'https://{ALKIRA_TENANT}/api' +AWS_SERVICE_USERNAME = alkira.get('services', 'AWS_SERVICE_USERNAME') +SERVICE_PASSWORD = alkira.get('services', 'SERVICE_PASSWORD') +CIDR_NAME = alkira.get('globalcidr', 'CIDR_NAME') +CIDR_DESCR = alkira.get('globalcidr', 'CIDR_DESCR') +CIDR_PREFIX = alkira.get('globalcidr', 'CIDR_PREFIX') +CIDR_CXP = alkira.get('globalcidr', 'CIDR_CXP') + +############################################### + +# Set default headers +headers = {'Content-Type': "application/json"} + +# URL Exceptions +url_exceptions = { + "saas": "internet", + "pan": "panfw", + "ftntfwservices": "ftnt-fw-services", + "chkpfwservices": "chkp-fw-services", + "ocivcnconnectors": "oci-vcn-connectors", + "ftntfwservices": "ftnt-fw-services", + "remoteaccessconnectors": "alkira-remote-access-connector-templates" + } + +# URL Exceptions creating credentials +service_credentials = { + "panfwservices": "pan", + "ftntfwservices": "ftntfw", + "chkpfwservices": "chkp-fw" + } + +# URL Exceptions creating instance credentials +service_instance_credentials = { + "ftntfwservices": "ftntfw-", + "chkpfwservices": "chkp-fw-" + } + +# Global CIDR +service_global_cidr = [ + "chkpfwservices" + ] + +# Credential Types +credential_types = { + "awsvpc": "", + "azurevnet": "", + "gcpvpc": "", + "ocivcn": "", + } + +# Authenticate +logging.info('=== Authenticating') +body = {'userName': ALKIRA_USERNAME, + 'password': ALKIRA_PASSWORD} +url = f'{ALKIRA_BASE_URI}/login' +session = requests.session() +response = session.post(url, data=json.dumps(body), headers=headers) + +# Get TenantID +logging.info('=== Fetching Tenant Info') +url = f'{ALKIRA_BASE_URI}/tenantnetworks' +response = session.get(url, headers=headers) +data = response.json() +tenantNetworkId = data[0]['id'] +tenantName = data[0]['name'] +logging.info(f'Tenant Name: {tenantName}') +logging.info(f'Tenant ID: {tenantNetworkId}') + +# Get Credentials +logging.info('=== Fetching Credentials') +url = f'{ALKIRA_BASE_URI}/credentials' +response = session.get(url, headers=headers) +data = response.json() +logging.debug(json.dumps(data)) +for key in data: + if key['credentialType'].lower() in credential_types: + logging.debug(f"CredentialType: {key['credentialType']} - CredentialId: {key['credentialId']}") + credential_types[key['credentialType'].lower()] = key['credentialId'] + +# Push connector +logging.info('=== Push Connector') +connector_result = re.match(r'(\w+\/)?(\w+)(connectors|services)(\d+)', connector) +if connector_result.group(1): + config_path = connector_result.group(1) +connector_type = connector_result.group(2) +connector_name = f'{connector_type}{connector_result.group(3)}' +connector_number = connector_result.group(4) +logging.info(f'Name: {connector_name} #{connector_number}') + +if connector_name in service_credentials.keys(): + print('=== Create Credentials') + credentials_url = service_credentials[connector_name] + fwcredential = f'fwcredentials-{time.time()}' + body = { + "credentials": { + "userName": AWS_SERVICE_USERNAME, + "password": SERVICE_PASSWORD + }, + "name": fwcredential + } + if args.pretty: + print(json.dumps(body, indent=4)) + else: + print(json.dumps(body)) + + url = f'{ALKIRA_BASE_URI}/credentials/{credentials_url}' + print(url) + response = session.post(url, data=json.dumps(body), headers=headers) + print(response.status_code) + print(response.content) + json_body = response.json() + if response.status_code == 200: + service_credentialid = json_body['id'] + print(f'credentialId: {service_credentialid}') + + if connector_name in service_instance_credentials.keys(): + credentials_url = service_instance_credentials[connector_name] + + print('=== Create Instance Credentials') + url = f'{ALKIRA_BASE_URI}/credentials/{credentials_url}instance' + print(url) + response = session.post(url, data=json.dumps(body), headers=headers) + print(response.status_code) + print(response.content) + json_body = response.json() + if response.status_code == 200: + service_instance_credentialid = json_body['id'] + print(f'instance credentialId: {service_instance_credentialid}') + +if connector_name in service_global_cidr: + print('=== Create Global CIDR') + body = { + "name": CIDR_NAME, + "description": CIDR_DESCR, + "values": [ + CIDR_PREFIX + ], + "cxp": CIDR_CXP + } + if args.pretty: + print(json.dumps(body, indent=4)) + else: + print(json.dumps(body)) + + url = f'{ALKIRA_BASE_URI}/tenantnetworks/{tenantNetworkId}/global-cidr-lists' + print(url) + response = session.post(url, data=json.dumps(body), headers=headers) + print(response.status_code) + print(response.content) + json_body = response.json() + if response.status_code == 201: + global_cidr_id = json_body['id'] + print(f'global cidr id: {global_cidr_id}') + +with open (connector, 'r') as f: + body = json.load(f) + +if 'connectors' in connector_name and connector_type in credential_types and credential_types[connector_type]: + if 'credentialId' in body: + logging.debug(f"JSON credentialid: {body['credentialId']}") + logging.debug(f'API credentialid: {credential_types[connector_type]}') + body['credentialId'] = credential_types[connector_type] + +if 'services' in connector_name and 'credentialId' in body: + body['credentialId'] = service_credentialid + print(f'JSON credentialId: {service_credentialid}') + +if 'services' in connector_name and 'instances' in body: + body['instances'][0]['credentialId'] = service_instance_credentialid + print(f'JSON credentialId: {service_instance_credentialid}') + +if 'services' in connector_name and 'managementServer' in body: + body['managementServer']['globalCidrListId'] = global_cidr_id + print(f'JSON globalCidrListId: {global_cidr_id}') + +if args.pretty: + print(json.dumps(body, indent=4)) +else: + print(json.dumps(body)) + +if connector_name in url_exceptions.keys(): + connector_name = url_exceptions[connector_name] + +print(f'=== Create {connector_name}') +url = f'{ALKIRA_BASE_URI}/tenantnetworks/{tenantNetworkId}/{connector_name}' +response = session.post(url, data=json.dumps(body), headers=headers) +print(response.status_code) +print(response.content)