BIG-IQ Local Connector Test

Problem this snippet solves:

Add, list or delete a Local Connector within BIG-IQ

Code :

#!/usr/bin/python
# 

import argparse
import json
import logging
import sys

import restapi;

DEFAULT_BIGIQ_USER = "admin"
DEFAULT_BIGIQ_PASSWORD = "admin"
DEFAULT_BIGIQ_ACTION = "List"
#This will be used to retrieve the ID of the device we want to delete
DEFAULT_BIGIP_HOSTNAME = "you.test.lab"
#Default connector name to be deleted
DEFAULT_BIGIQ_CONNECTOR_NAME = "My-Tenant-Connector"

LOG = logging.getLogger(__name__)

##
# Loads a JSON file.
def load_json_file(name):
   
    with file(name) as f:
        json_data = json.load(f)
    
    if json_data:
        json_data = json.dumps(json_data)
        
    return json_data

##
# Modifies a field of a JSON string and returns it as a string
def modify_json(json_string, field_to_modify, new_value):

    json_data = json.loads(json_string)

    if json_data == None:
        sys.exit(1)

    json_data[field_to_modify] = new_value

    return json.dumps(json_data)


    
# Prints a line separator (for easy viewing).
def print_separator():
        print("-" * 80)
    
##
# Validates the HTTP/REST result.
def validate_result(result, verbose=False):
   
    # Any result beyond HTTP 400 is considered an error.
    if ((result == None) or (result[0] >= restapi.HTTP_400)):
        sys.exit(1)
    
    if verbose:
        for i in range (1, len(result)):
    LOG.info(result[i])

#Retrieve device link to include it into the local connector
def retrieve_device_link(list_devices, hostname):
    result = []
    for i in range (1, len(list_devices)):
        hostname_ = list_devices[i]['items'][0]['hostname']
        if (hostname == hostname_):
                print(list_devices[i]['items'][0]['selfLink'])
                device_link = {'link':list_devices[i]['items'][0]['selfLink']}
result.append(device_link)
return(result)

#Retrieve the local connector id to delete it
def retrieve_connector_id(list_connectors, connector_name):
    for i in range (1, len(list_connectors)):
        connector_name_ = list_connectors[i]['items'][0]['name']
        if (connector_name == connector_name_):
                print(list_connectors[i]['items'][0]['connectorId'])
                return(list_connectors[i]['items'][0]['connectorId'])

##
# Runs the BIG-IQ cloud API test suite.
def run_bigiq_tests(bigiq_address,
                    action=DEFAULT_BIGIQ_ACTION,
    hostname=DEFAULT_BIGIP_HOSTNAME,
    bigiq_user=DEFAULT_BIGIQ_USER,
                    bigiq_password=DEFAULT_BIGIQ_PASSWORD,
                    connector_name=DEFAULT_BIGIQ_CONNECTOR_NAME,
    verbose=False):
    
    LOG.info("Running BIG-IQ Local Connector tests...")
    # Initialize cloud API tester.
    LOG.info("BIG-IQ: Initializing cloud API shim...")
    cloud_api = restapi.RestApi(host=bigiq_address,
                               user=bigiq_user,
                               password=bigiq_password)
    LOG.info("BIG-IQ: Cloud API shim successfully initialized.")
    
    if (action == "Delete"):
    LOG.info("BIG-IQ: Delete Local Connector...")
        list_connectors = cloud_api.get_local_connectors()
connector_id = retrieve_connector_id(list_connectors, connector_name)
        result = cloud_api.delete_local_connector(connector_id)
        validate_result(result, verbose)
        LOG.info("BIG-IQ: Local Connector  successfully deleted.")

    if (action == "List"):
    # BIG-IQ: query devices list
    LOG.info("BIG-IQ: Querying list of connectors...")
    result = cloud_api.get_local_connectors()
validate_result(result, True)
    LOG.info("BIG-IQ: Connectors  successfully retrieved.")

    if (action == "Create"):
    # BIG-IQ: add device.
    LOG.info("BIG-IQ: Creating Local Connector...")
    list_devices = cloud_api.get_devices()
device_link = retrieve_device_link(list_devices, hostname)
connector_json_string = modify_json(load_json_file("./bigiq_create_local_connector.json"),
                                         'deviceReferences',
                                         device_link)
result = cloud_api.create_local_connector(connector_json_string)
    validate_result(result, verbose)
    LOG.info("BIG-IQ: Local Connector successfully created.")
   

    
# Initializes logging.
def init_logging(level=logging.INFO):

    log_format = '%(asctime)-15s: %(funcName)s(): %(message)s'
    logging.basicConfig(format=log_format, level=level)

##
# Main entry point
def main():
    
    parser = argparse.ArgumentParser(description="Runs various REST-API functional tests")
    
    parser.add_argument('-v', '--verbose', action='store_true', default=False)
    parser.add_argument('--bigiq-address', required=True)
    parser.add_argument('--bigiq-user', default=DEFAULT_BIGIQ_USER)
    parser.add_argument('--bigiq-password', default=DEFAULT_BIGIQ_PASSWORD)
    parser.add_argument('--action', default=DEFAULT_BIGIQ_ACTION)
    parser.add_argument('--hostname', default=DEFAULT_BIGIP_HOSTNAME)
    parser.add_argument('--connector-name', default=DEFAULT_BIGIQ_CONNECTOR_NAME) 

    args = parser.parse_args()
    
    log_level = logging.INFO
    
    if (args.verbose):
        log_level = logging.DEBUG
        
    init_logging(log_level)
    
    # BIG-IQ tests.
    run_bigiq_tests(bigiq_address=args.bigiq_address,
                    action=args.action,
    hostname=args.hostname,
    connector_name=args.connector_name,
    bigiq_user=args.bigiq_user,
                    bigiq_password=args.bigiq_password,
                    verbose=args.verbose)
    
    LOG.info("OK. Done testing.")

##
# Main entry point launcher.
if __name__ == '__main__':
    main()
Published Mar 09, 2015
Version 1.0

Was this article helpful?

No CommentsBe the first to comment