Best Python code snippet using autotest_python
silverpeak-preconfig-from-jinja.py
Source:silverpeak-preconfig-from-jinja.py
1# Standard library imports2import argparse3import csv4import datetime5import json6import os7import time8# Third party imports9import colored10import urllib311import yaml12from colored import stylize13from dotenv import load_dotenv14from jinja2 import (15 Environment,16 FileSystemLoader,17 PackageLoader,18 Template,19 select_autoescape,20)21# Local application imports22from silverpeak_python_sdk import Orchestrator23from urllib3.exceptions import InsecureRequestWarning24# Disable Certificate Warnings25urllib3.disable_warnings(category=InsecureRequestWarning)26def comma_separate(cs_string_list):27 # Blank List28 cs_list = []29 # Convert string to comma separated list30 cs_string_list = cs_string_list.split(",")31 # Strip leading/trailing whitespace from items32 for item in cs_string_list:33 cs_list.append(item.strip())34 return cs_list35def get_csv_file():36 # Enter source CSV file for config generation data37 correct_file = "n"38 while correct_file != "y":39 csv_filename = input("Please enter source csv filename: ")40 print(41 "Using {} for configuration source data".format(42 stylize(csv_filename, green_text)43 )44 )45 correct_file = input(46 "Do you want to proceed with that source file?(y/n, q to quit): "47 )48 if correct_file == "q":49 exit()50 else:51 pass52 return csv_filename53def prompt_for_orch_upload():54 # Check if user wants to upload preconfigs to Orchestrator55 upload_to_orch = input(56 "Upload the generated Preconfigs to Orchestrator?(y/n, other key to quit): "57 )58 if upload_to_orch == "y":59 return True60 if upload_to_orch == "n":61 return False62 else:63 exit()64def prompt_for_auto_apply(discovered_appiance_type):65 # Check if user wants to auto-approve appliances matching uploaded preconfigs66 auto_approve_check = input(67 "Do you want to auto-approve {} appliances matching the preconfigs?(y/n, other to quit): ".format(68 discovered_appiance_type69 )70 )71 if auto_approve_check == "y":72 return True73 elif auto_approve_check == "n":74 return False75 else:76 exit()77# Console text highlight color parameters78red_text = colored.fg("red") + colored.attr("bold")79green_text = colored.fg("green") + colored.attr("bold")80blue_text = colored.fg("steel_blue_1b") + colored.attr("bold")81orange_text = colored.fg("dark_orange") + colored.attr("bold")82# Parse arguments83parser = argparse.ArgumentParser()84parser.add_argument(85 "--upload", help="Upload created preconfigs to Orchestrator", type=bool86)87parser.add_argument(88 "--autoapply", help="Mark uploadded preconfigs for auto-approve", type=bool89)90parser.add_argument(91 "--autodenied",92 help="Approve and apply preconfig to matching denied appliances",93 type=bool,94)95parser.add_argument("--csv", help="specify source csv file for preconfigs", type=str)96parser.add_argument("--jinja", help="specify source jinja2 template", type=str)97parser.add_argument("--vault", help="specify source vault URL", type=str)98parser.add_argument("--orch", help="specify Orchestrator URL", type=str)99args = parser.parse_args()100# Load environment variables101load_dotenv()102# If Vault argument or Vault URL present in env103# retrieve Orch credentials from Vault104if vars(args)["vault"] is not None:105 vault_url = vars(args)["vault"]106elif os.getenv("VAULT_URL") is not None:107 vault_url = os.getenv("VAULT_URL")108elif vars(args)["orch"] is not None:109 orch = Orchestrator(vars(args)["orch"])110 orch_user = os.getenv("ORCH_USER")111 orch_pw = os.getenv("ORCH_PASSWORD")112else:113 orch = Orchestrator(str(os.getenv("ORCH_URL")))114 orch_user = os.getenv("ORCH_USER")115 orch_pw = os.getenv("ORCH_PASSWORD")116# Obtain Jinja2 template file for generating preconfig117if vars(args)["jinja"] is not None:118 ec_template_file = vars(args)["csv"]119else:120 ec_template_file = "ec_preconfig_template.jinja2"121# Retrieve Jinja2 template for generating EdgeConnect Preconfig YAML file122env = Environment(loader=FileSystemLoader("templates"))123ec_template = env.get_template(ec_template_file)124print(125 "Using {} for EdgeConnect jinja template".format(126 stylize(ec_template_file, blue_text)127 )128)129# Local directory for configuration outputs130local_config_directory = "preconfig_outputs/"131if not os.path.exists(local_config_directory):132 os.makedirs(local_config_directory)133# Obtain CSV file for generating preconfigs134if vars(args)["csv"] is not None:135 csv_filename = vars(args)["csv"]136else:137 csv_filename = get_csv_file()138# Check if configs should be uploaded to Orchestrator139if vars(args)["upload"] is not None:140 upload_to_orch = vars(args)["upload"]141else:142 upload_to_orch = prompt_for_orch_upload()143# If uploading to Orchestrator check if preconfigs should be marked for auto-approve144if vars(args)["autoapply"] is not None:145 auto_apply = vars(args)["autoapply"]146elif upload_to_orch == True:147 auto_apply = prompt_for_auto_apply("DISCOVERED")148else:149 auto_apply = False150# If auto-apply, check if should also approve matching appliances that are currently denied151if vars(args)["autodenied"] is not None:152 auto_apply_denied = vars(args)["autodenied"]153elif auto_apply == True:154 auto_apply_denied = prompt_for_auto_apply("DENIED")155else:156 auto_apply_denied = False157# Connect to Orchestrator158orch.login(orch_user, orch_pw)159# Open CSV file160with open(csv_filename, encoding="utf-8-sig") as csvfile:161 csv_dict = csv.DictReader(csvfile)162 # Set initial row number for row identification163 row_number = 1164 # Track hosts added for Orchestrator approval165 silverpeak_hostname_list = []166 # For each row/site in configuration file, generate Silver Peak and Aruba configurations167 for row in csv_dict:168 # Render EdgeConnect YAML Preconfig File from Jinja template169 if row["hostname"] != "":170 print(171 "Rendering EdgeConnect template for {} from row {}".format(172 stylize(row["hostname"], blue_text), str(row_number)173 )174 )175 silverpeak_hostname_list.append(row["hostname"])176 # Convert list strings to comma separated list, strips leading/trailing whitespace177 row["templateGroups"] = comma_separate(row["templateGroups"])178 row["businessIntentOverlays"] = comma_separate(179 row["businessIntentOverlays"]180 )181 # Render Jinja template182 preconfig = ec_template.render(data=row)183 # Validate preconfig via Orchestrator184 validate = orch.validate_preconfig(185 row["hostname"], row["serial_number"], preconfig, auto_apply186 )187 if validate.status_code == 200:188 # Write local YAML file189 output_filename = "{}_preconfig.yml".format(row["hostname"])190 with open(191 local_config_directory + output_filename, "w"192 ) as preconfig_file:193 write_data = preconfig_file.write(preconfig)194 # If option was chosen, upload preconfig to Orchestrator with selected auto-apply settings195 if upload_to_orch == True:196 orch.create_preconfig(197 row["hostname"],198 row["serial_number"],199 preconfig,200 auto_apply,201 )202 print(203 "Posted EC Preconfig {}".format(204 stylize(row["hostname"], blue_text)205 )206 )207 else:208 pass209 else:210 print("Preconfig failed validation")211 row_number = row_number + 1212 else:213 print(214 "No hostname for Silver Peak EdgeConnect from row {}: no preconfig created".format(215 stylize(row_number, red_text)216 )217 )218 row_number = row_number + 1219# If auto-apply option was chosen, also approve any matching appliances in denied discovered list220if auto_apply_denied == True:221 # Retrieve all denied discovered appliances from Orchestrator222 all_denied_appliances = orch.get_all_denied_appliances()223 # Retrieve all preconfigs from Orchestrator224 all_preconfigs = orch.get_all_preconfig()225 # Dict of Denied Appliances to approve with discovered_id and preconfig_id to apply226 approve_dict = {}227 # For each EdgeConnect host in the source csv228 # check against all preconfigs for matching tag229 # and check against all discovered denied appliances with the same tag that are reachable230 for host in silverpeak_hostname_list:231 for preconfig in all_preconfigs:232 for appliance in all_denied_appliances:233 if (234 host == preconfig["name"] == appliance["applianceInfo"]["site"]235 and appliance["applianceInfo"]["reachabilityStatus"] == 1236 ):237 approve_dict[host] = {238 "discovered_id": appliance["id"],239 "preconfig_id": preconfig["id"],240 }241 else:242 pass243 # Approve and apply corresponding preconfig for each of the matched appliances244 # This simulates the functionality of 'auto-approve' with previously denied/deleted devices245 for appliance in approve_dict:246 orch.approve_and_apply_preconfig(247 approve_dict[appliance]["preconfig_id"],248 approve_dict[appliance]["discovered_id"],249 )250else:251 pass252# Logout from Orchestrator if logged in...
remove-preconfig.py
Source:remove-preconfig.py
1import argparse2import csv3import getpass4import os5from pyedgeconnect import Orchestrator6# Parse runtime arguments7parser = argparse.ArgumentParser()8parser.add_argument(9 "-c",10 "--csv",11 help="Specify source csv file for preconfigs",12 type=str,13 required=True,14)15parser.add_argument(16 "-o",17 "--orch",18 help="specify Orchestrator URL",19 type=str,20)21args = parser.parse_args()22# Set Orchestrator FQDN/IP via arguments, environment variable,23# or user input24if vars(args)["orch"] is not None:25 orch_url = vars(args)["orch"]26elif os.getenv("ORCH_URL") is not None:27 orch_url = os.getenv("ORCH_URL")28else:29 orch_url = input("Orchstrator IP or FQDN: ")30# Set Orchestrator API Key via environment variable or user input31if os.getenv("ORCH_API_KEY") is not None:32 orch_api_key = os.getenv("ORCH_API_KEY")33else:34 orch_api_key_input = input("Orchstrator API Key (enter to skip): ")35 if len(orch_api_key_input) == 0:36 orch_api_key = None37 # Set user and password if present in environment variable38 orch_user = os.getenv("ORCH_USER")39 orch_pw = os.getenv("ORCH_PASSWORD")40 else:41 orch_api_key = orch_api_key_input42# Instantiate Orchestrator with ``log_console`` enabled for43# printing log messages to terminal44orch = Orchestrator(45 orch_url,46 api_key=orch_api_key,47 log_console=True,48 verify_ssl=False,49)50# If not using API key, login to Orchestrator with username/password51if orch_api_key is None:52 # If username/password not in environment variables, prompt user53 if orch_user is None:54 orch_user = input("Enter Orchestrator username: ")55 orch_pw = getpass.getpass("Enter Orchestrator password: ")56 # Check if multi-factor authentication required57 mfa_prompt = input("Are you using MFA for this user (y/n)?: ")58 if mfa_prompt == "y":59 orch.send_mfa(orch_user, orch_pw, temp_code=False)60 token = input("Enter MFA token: ")61 else:62 token = ""63 # Login to Orchestrator64 confirm_auth = orch.login(orch_user, orch_pw, mfacode=token)65 # Check that user/pass authentication works before proceeding66 if confirm_auth:67 pass68 else:69 print("Authentication to Orchestrator Failed")70 exit()71# If API key specified, check that key is valid before proceeding72else:73 confirm_auth = orch.get_orchestrator_hello()74 if confirm_auth != "There was an internal server error.":75 pass76 else:77 print("Authentication to Orchestrator Failed")78 exit()79# Specify CSV file for generating preconfigs80# This is a mandatory runtime argument81if vars(args)["csv"] is not None:82 csv_filename = vars(args)["csv"]83else:84 print("Source CSV file not specified, exiting")85 exit()86with open(csv_filename, encoding="utf-8-sig") as csvfile:87 csv_dict = csv.DictReader(csvfile)88 # Get all preconfigs from Orchestrator89 all_preconfigs = orch.get_all_preconfig()90 preconfigs_to_delete = []91 ec_hostname_list = []92 # Form list of preconfigs on Orchestrator matching preconfig93 # names from the CSV file94 for row in csv_dict:95 ec_hostname_list.append(row["hostname"])96 for preconfig in all_preconfigs:97 if preconfig["name"] == row["hostname"]:98 # Similar to appliances, preconfigs are identified by99 # an id (e.g. 10) rather than the name/hostname100 preconfigs_to_delete.append(preconfig["id"])101 else:102 pass103# Show user pending preconfigs to be deleted104print("The following Preconfigs are queued for deletion:")105width = 10106print(107 "\n".join(108 "".join(str(preconfigs_to_delete[i : i + width]))109 for i in range(0, len(preconfigs_to_delete), width)110 )111)112# Confirm with user to remove the specified preconfigs113proceed = input("Delete these preconfigs from Orchestrator?(y/n): ")114if proceed == "y" or proceed == "Y":115 for preconfigId in preconfigs_to_delete:116 orch.delete_preconfig(str(preconfigId))117 print("All specified preconfigs deleted from Orchestrator")118else:...
preconfigs.py
Source:preconfigs.py
...46 def get_preconfig(self, name, type):47 self._init_preconfigs()48 self._read_preconfig(name, type)49 return self._preconfigs[type][name]50 def all_preconfigs(self):51 self._init_preconfigs()52 return dict(self._preconfigs)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!