def execute(self): api = helpers.get_api_session() resource_details_cache = {} api.WriteMessageToReservationOutput(reservationId=self.reservation_id, message='Beginning reservation setup') reservation_details = api.GetReservationDetails(self.reservation_id) deploy_result = self._deploy_apps_in_reservation(api=api, reservation_details=reservation_details) # refresh reservation_details after app deployment if any deployed apps if deploy_result and deploy_result.ResultItems: reservation_details = api.GetReservationDetails(self.reservation_id) self._try_exeucte_autoload(api=api, reservation_details=reservation_details, deploy_result=deploy_result, resource_details_cache=resource_details_cache) self._connect_all_routes_in_reservation(api=api, reservation_details=reservation_details) self._run_async_power_on_refresh_ip_install(api=api, reservation_details=reservation_details, deploy_results=deploy_result, resource_details_cache=resource_details_cache) self.logger.info("Setup for reservation {0} completed".format(self.reservation_id)) api.WriteMessageToReservationOutput(reservationId=self.reservation_id, message='Reservation setup finished successfully')
def first_module_flow(): """ Functions passed into orchestration flow MUST have (sandbox, components) signature :param Sandbox sandbox: :param componentssc :return: """ # script helpers to pull in sandbox details, resource details, and api session sb_context = script_help.get_reservation_context_details() resource_details = script_help.get_resource_context_details() api = script_help.get_api_session() res_id = sb_context.id ip = resource_details.address resource_name = resource_details.name # environment variables not available during dev, we can mock it if DEBUG_MODE: warn_print(api, res_id, "=== DEBUG_MODE Boolean is on ===") custom_param = "my debug param value" else: custom_param = os.environ[INPUT_COMMAND_PARAMETER] sb_print(api, res_id, "resource name is {}".format(resource_name)) sb_print(api, res_id, "resource ip is {}".format(ip)) sb_print(api, res_id, "custom param value: {}".format(custom_param))
def executePlaybookScript(self): session = scripthelpers.get_api_session() Ansible_services = [ service for service in session.GetReservationDetails( reservation_details.id).ReservationDescription.Services if service.ServiceName == 'AnsibleServer' ] if Ansible_services == []: raise Exception('Ansible Server not found!') elif Ansible_services.__len__() > 1: raise Exception('Multiple Ansible Servers found!') else: Ansible_service = Ansible_services[0] # Build Inputs: command_inputs = [ api.InputNameValue('Host_IP', resource_context.address), api.InputNameValue( 'URL', resource_context.attributes['Ansible Playbook URL']), api.InputNameValue( 'Ansible_Parameters', resource_context.attributes['Ansible Parameters']), api.InputNameValue('Username', resource_context.attributes['User']), api.InputNameValue('Password', resource_context.attributes['Password']) ] session.ExecuteCommand(reservationId=reservation_details.id, targetName=Ansible_service.Alias, targetType='Service', commandName='AnsibleExecutePlaybook', commandInputs=command_inputs)
def main(): reservation = helpers.get_reservation_context_details() app = helpers.get_resource_context_details() app_attributes = app.attributes connectivity = helpers.get_connectivity_context_details() cloudshell = helpers.get_api_session() msg = lambda txt: cloudshell.WriteMessageToReservationOutput(reservation.id, txt) resource = helpers.get_resource_context_details_dict() resource['deployedAppData']['attributes'] = {attribute['name']: attribute['value'] for attribute in resource['deployedAppData']['attributes']} resource['deployedAppData']['attributes']['Password'] = cloudshell.DecryptPassword(resource['deployedAppData']['attributes']['Password']).Value repo = cloudshell.GetResourceDetails(app_attributes["Repository Name"]) repo_attributes = {attribute.Name: attribute.Value for attribute in repo.ResourceAttributes} repo_attributes["Host"] = repo.Address repo_attributes["Password"] = cloudshell.DecryptPassword(repo_attributes["Password"]).Value artifactory = Artifactory.from_dict(repo_attributes) build = ArtifactBuild.from_dict(repo_attributes) msg('- Looking for app dependencies') if not build.is_populated(): build = populate_build_from_sandbox(connectivity, reservation, msg) msg('- Found dependencies on Artifactory, associated with build {0} {1}'.format(build.name, build.number)) file_location, file_name = artifactory.download(build.name, build.number) msg('- Downloaded app dependencies to Execution Server at ' + os.path.join(file_location, file_name)) install_package(resource['deployedAppData']['address'], resource['deployedAppData']['attributes']['User'], resource['deployedAppData']['attributes']['Password'], os.path.join(file_location, file_name), app_attributes['Target Directory'] + '/' + file_name) msg('- Copied binaries to app server at ' + app_attributes['Target Directory'] + '/' + file_name)
def __init__(self): self.automation_api = api_helpers.get_api_session() self.workflow = Workflow(self) self.suppress_exceptions = True self._exception = None self.connectivityContextDetails = helpers.get_connectivity_context_details() self.reservationContextDetails = helpers.get_reservation_context_details() self.reservationLifecycleDetails = helpers.get_lifecycle_context_details() self.global_inputs = helpers.get_global_inputs() self.additional_info_inputs = helpers.get_resource_additional_info_inputs() self.requirement_inputs = helpers.get_resource_requirement_inputs() self.id = self.reservationContextDetails.id reservation_description = self.automation_api.GetReservationDetails(reservationId=self.id, disableCache=True).ReservationDescription self.name = reservation_description.Name self.components = Components(reservation_description.Resources, reservation_description.Services, reservation_description.Apps) self.logger = get_qs_logger(log_file_prefix='CloudShell Sandbox Orchestration', log_group=self.id, log_category='Orchestration') self.apps_configuration = AppsConfiguration(sandbox=self)
def execute(self): api = helpers.get_api_session() reservation = api.GetReservationDetails(self.reservation_id) resource_name = helpers.get_resource_context_details_dict()['name'] all_resources = [resource.Name for resource in reservation.ReservationDescription.Resources] all_resources.append(resource_name) connectors = [connector for connector in reservation.ReservationDescription.Connectors if connector.State in ['Disconnected', 'PartiallyConnected', 'ConnectionFailed'] and (connector.Source == resource_name or connector.Target == resource_name) and connector.Source in all_resources and connector.Target in all_resources] endpoints = [] for endpoint in connectors: endpoints.append(endpoint.Target) endpoints.append(endpoint.Source) self.logger.info("Executing connect for app {0}".format(resource_name)) api.WriteMessageToReservationOutput(reservationId=self.reservation_id, message='[{0}] connecting all routes'.format(resource_name)) if endpoints: api.ConnectRoutesInReservation(self.reservation_id, endpoints, 'bi') api.WriteMessageToReservationOutput(reservationId=self.reservation_id, message='[{0}] connecting all finished successfully'.format(resource_name))
def executePlaybookScript(self): session = scripthelpers.get_api_session() Ansible_resources = [] Ansible_resources_raw = [ resource for resource in session.GetReservationDetails( reservation_details.id).ReservationDescription.Resources ] for res in Ansible_resources_raw: res_det = session.GetResourceDetails(res.Name).ResourceAttributes Ansible_playbook_url = [ attr.Value for attr in res_det if attr.Name == 'Ansible Playbook URL' ] if Ansible_playbook_url.__len__() == 1: Ansible_resources.append(res) if Ansible_resources == []: raise Exception('no resources with Ansible capabilities found!') for Ansible_resource in Ansible_resources: session.ExecuteCommand(reservationId=reservation_details.id, targetName=Ansible_resource.Name, targetType='Resource', commandName='DUTExecutePlaybook', commandInputs=[])
def __init__(self, reservation_id, logger): """ Load the configuration from config files on the Blueprint's devices :param str reservation_id: reservation id """ try: self._logger = logger """:type : logging.Logger""" self.api_session = helpers.get_api_session() self.id = reservation_id self.Blueprint_name = helpers.get_reservation_context_details().environment_name full_path = None tp = self.api_session.GetActiveTopologyNames() for value in tp.Topologies: filename = basename(value) if filename == self.Blueprint_name: full_path = value break if full_path: self.blueprint_details = self.api_session.GetTopologyDetails(full_path) except: err = "Failed to initialize the Sandbox. Unexpected error:" + \ str(sys.exc_info()[0]) self.report_error(error_message=err)
def main(): session = helpers.get_api_session() command_to_run = helpers.get_user_param("Command Name") try_execute_command_on_resources( session, reservation_id=helpers.get_reservation_context_details().id, command_name=command_to_run)
def _extract_parameters_JSON(reservation_id): inputs_desc = helpers.get_api_session() \ .GetReservationInputs(reservation_id) global_inputs_JSON = _extract_global_inputs_JSON(inputs_desc) required_inputs_JSON = _extract_required_inputs_JSON(inputs_desc) additional_inputs_JSON = _extract_addition_inputs_JSON(inputs_desc) return PARAMETERS_TEMPLATE.format( requirement_template=required_inputs_JSON, additional_info_template=additional_inputs_JSON, global_template=global_inputs_JSON)
def _get_resource_context(resource_name): r = helpers.get_api_session().GetResourceDetails(resource_name) attributes = [] for attribute in r.ResourceAttributes: attribute_json = RESOURCE_ATTRIBUTES_TEMPLATE.format( name=attribute.Name, value=attribute.Value) attributes.append(attribute_json) resource_details = RESOURCEDETAILS_TEMPLATE. \ format(name=r.Name, address=r.Address, model=r.ResourceModelName, family=r.ResourceFamilyName, description=r.Description, fullname=r.Name, attributes='{' + str.join(',', attributes) + '}') return '{' + resource_details + '}'
def execute(self): api = helpers.get_api_session() reservation_details = api.GetReservationDetails(self.reservation_id) api.WriteMessageToReservationOutput(reservationId=self.reservation_id, message='Beginning reservation teardown') self._disconnect_all_routes_in_reservation(api, reservation_details) self._power_off_and_delete_all_vm_resources(api, reservation_details) self.logger.info("Teardown for reservation {0} completed".format(self.reservation_id)) api.WriteMessageToReservationOutput(reservationId=self.reservation_id, message='Reservation teardown finished successfully')
def run_post_setup_logic(self, reservation_context): """ :param ReservationContextDetails reservation_context: :param EnvironmentSetup.EnvironmentSetupResult setup_result: :return: """ reservation_details = helpers.get_api_session().GetReservationDetails(reservation_context.id) # Run a custom post-setup command on each Shell resource resource_names = [resource.Name for resource in reservation_details.ReservationDescription.Resources] self._try_execute_command_on_resources(reservation_context.id, resource_names, "Bootsrap")
def __init__(self, resource_name, resource_alias=''): if resource_name != "": self.api_session = helpers.get_api_session() self.details = self.api_session.GetResourceDetails(resource_name) self.name = self.details.Name self.address = self.details.Address self.commands = self.api_session.GetResourceCommands(resource_name).Commands self.attributes = self.details.ResourceAttributes # If there is an attribute named 'model' take its value (exist in shells), otherwise take the family's model try: self.model = self.get_attribute('Model') except QualiError: self.model = self.details.ResourceModelName self.alias = resource_alias
def execute(self): api = helpers.get_api_session() reservation_details = api.GetReservationDetails(self.reservation_id) api.WriteMessageToReservationOutput(reservationId=self.reservation_id, message='Beginning reservation teardown') self._disconnect_all_routes_in_reservation(api, reservation_details) self._power_off_and_delete_all_vm_resources(api, reservation_details, self.reservation_id) self._cleanup_connectivity(api, self.reservation_id) self.logger.info("Teardown for reservation {0} completed".format(self.reservation_id)) api.WriteMessageToReservationOutput(reservationId=self.reservation_id, message='Reservation teardown finished successfully')
def run(): session = sh.get_api_session() resources = session.GetReservationDetails(sh.get_reservation_context_details().id).ReservationDescription.Resources pcs = [] switch = sh.get_resource_context_details().name for res in resources: if res.ResourceModelName.__contains__('GenericPortChannel'): # pcs.append(res.Name) command = 'show interfaces {}'.format(res.Name.split('/')[-1]) session.ExecuteCommand( reservationId=sh.get_reservation_context_details().id, targetType='Resource', targetName=switch, commandName='run_custom_command', commandInputs=[api.InputNameValue('custom_command', command)], printOutput=True )
def create_cs_session(debug): if debug == 'yes': try: dev_helpers_71.attach_to_cloudshell_as("admin", "admin", "Global", reservation_id='59b547e3-6e9e-49d3-906f-2e28582ac98b', server_address='q1.cisco.com') except: dev_helpers_64.attach_to_cloudshell_as("admin", "admin", "Global", reservation_id='6376f07e-6d30-4b2b-811c-2eee0c77832b', server_address='q1.cisco.com') try: session = helpers_71.get_api_session() helpers = helpers_71 except: session = helpers_64.get_api_session() helpers = helpers_64 return session, helpers
def run_post_setup_logic(self, reservation_context): """ :param ReservationContextDetails reservation_context: :param EnvironmentSetup.EnvironmentSetupResult setup_result: :return: """ reservation_details = helpers.get_api_session().GetReservationDetails( reservation_context.id) # Run a custom post-setup command on each Shell resource resource_names = [ resource.Name for resource in reservation_details.ReservationDescription.Resources ] self._try_execute_command_on_resources(reservation_context.id, resource_names, "Bootsrap")
def get_cs_data(self): self.session = helpers.get_api_session() # self.session = api.CloudShellAPISession(host=connectivity_details['serverAddress'], # token_id=connectivity_details['adminAuthToken'], # domain=reservation_details['domain']) resource_context = helpers.get_resource_context_details_dict() self.name = resource_context['name'] res_dets = self.session.GetResourceDetails(resource_context['name']) self.host = self.session.GetResourceDetails( res_dets.VmDetails.CloudProviderFullName).RootAddress cp_dets = self.session.GetResourceDetails( res_dets.VmDetails.CloudProviderFullName) self.user = [ attr.Value for attr in cp_dets.ResourceAttributes if attr.Name == 'User' ][0] self.pwd = self.session.DecryptPassword([ attr.Value for attr in cp_dets.ResourceAttributes if attr.Name == 'Password' ][0]).Value
def _create_permitted_users_json(permitted_users_list): session = helpers.get_api_session() permitted_users = [] for user in permitted_users_list: try: details = session.GetUserDetails(user) user_json = USER_DETAILS_TEMPLATE.format( userName=details.Name, email=details.Email) permitted_users.append('{' + user_json + '}') except CloudShellAPIError as exc: if exc.code == '124': user_json = USER_DETAILS_TEMPLATE.format( userName=user, email='') permitted_users.append('{' + user_json + '}') else: raise return str.join(',', permitted_users)
import cloudshell.helpers.scripts.cloudshell_dev_helpers as dev_help import cloudshell.helpers.scripts.cloudshell_scripts_helpers as sc_help import cloudshell.api.cloudshell_api as api resid = '9abac2bb-32cc-404f-8f1f-7c6d411683c2' dev_help.attach_to_cloudshell_as(user='******', password='******', reservation_id=resid, domain='Global') session = sc_help.get_api_session() res_det = session.GetResourceCommands('NxOS Simulator') session.ExecuteCommand( reservationId=resid, targetType='Resource', targetName='IOS emulator', commandName='run_custom_config_command', commandInputs=[api.InputNameValue('custom_command', '')]) session.SetResourceLiveStatus() pass
from cloudshell.api.cloudshell_api import CloudShellAPISession from cloudshell.api.common_cloudshell_api import CloudShellAPIError from cloudshell.helpers.scripts import cloudshell_scripts_helpers as helpers from cloudshell.helpers.scripts import cloudshell_dev_helpers as dev_helpers dev_helpers.attach_to_cloudshell_as("admin", "admin", "Global", "55aec269-792f-4ca9-8156-9967788d3a4f", "10.211.55.4") reservation_id = helpers.get_reservation_context_details().id try: helpers.get_api_session().ExecuteCommand(reservation_id, "DriverDeepDive", "Resource", "failed_command") except CloudShellAPIError as err: print err.message raise
def _bootstrap_data(user, password, domain, reservation_id, server_address='localhost', cloudshell_api_port='8028', command_parameters={}, resource_name=None, service_name=None): """ This helper is intended to make it easier to test scripts. When a script gets executed by CloudShell, the Execution Server sets up several variables as a context for the execution. This function simulates the same conditions so the script can be tested offline. :param str user: The user the driver should authenticate as :param str passwrd: Password for the specified user :param str reservation_id: The reservation the driver should attach to :param str server_address: The address of the CloudShell server (default to localhost) :param str cloudshell_api_port: The API port to use (default 8028) :param dict[str,str] command_parameters: user parameters passed to this command :param str resource_name: For resource commands only specify the name of the resource """ if is_dev_mode(): # We assume that if the env. variable doesn't exist we need to bootstrap quali_connectivity = CONNECTIVITY_DETAILS_TEMPLATE. \ format(cloudshell_api_port=cloudshell_api_port, server_address=server_address, password=password, user=user) # Creat an initial template for reservation details just to get more info reservation_details = RESERVATIONDETAILS_TEMPLATE. \ format(id=reservation_id, domain=domain, description='', environment_name='', environment_path='', parameters_template='[]', owner_user=user, owner_pass=password, permittedUsers=[], savedSandboxId='', runningUser='') os.environ['qualiConnectivityContext'] = '{' + quali_connectivity + '}' os.environ['reservationContext'] = '{' + reservation_details + '}' parameters_details = _extract_parameters_JSON(reservation_id) reservation_desc = helpers.get_api_session() \ .GetReservationDetails(reservation_id) \ .ReservationDescription permitted_users_json = _create_permitted_users_json(reservation_desc.PermittedUsers) environment_path = '' if reservation_desc.Topologies: environment_path = reservation_desc.Topologies[0] reservation_details = RESERVATIONDETAILS_TEMPLATE. \ format(id=reservation_id, domain=reservation_desc.DomainName, description='', parameters_template='{' + parameters_details + '}', environment_path=environment_path, environment_name='', owner_user=user, owner_pass=password, permittedUsers='[' + str(permitted_users_json) + ']', savedSandboxId=reservation_desc.SavedSandboxId, runningUser=user) # Update the reservation details again with the full info os.environ['reservationContext'] = '{' + reservation_details + '}' for parameter in command_parameters: os.environ[parameter.upper()] = command_parameters[parameter] if resource_name is not None: os.environ['resourceContext'] = \ _get_resource_context(resource_name) if service_name is not None: os.environ['resourceContext'] = \ _get_service_context(reservation_desc, service_name) saved_sandbox_name = '' saved_sandbox_description = '' if reservation_desc.SavedSandboxId: saved_sandboxes = helpers.get_api_session() \ .GetSavedSandboxes().SavedSandboxes save_sandbox = next((x for x in saved_sandboxes if x.Id == reservation_desc.SavedSandboxId), None) if save_sandbox: saved_sandbox_name = save_sandbox.Name saved_sandbox_description = save_sandbox.Description reservation_lifecycle_details = RESERVATIONLIFECYCLE_TEMPLATE. \ format(reservationId=reservation_id, savedSandboxName=saved_sandbox_name, savedSandboxDescription=saved_sandbox_description, currentUserName=user) os.environ['reservationLifecycleContext'] = '{' + reservation_lifecycle_details + '}'
def _ssh_command(ssh, channel, command, prompt_regex): _ssh_write(ssh, channel, command + '\n') rv = _ssh_read(ssh, channel, prompt_regex) if '\n%' in rv.replace('\r', '\n'): es = 'CLI error message: ' + rv raise Exception(es) return rv resource_context = helper.get_resource_context_details() reservation_context = helper.get_reservation_context_details() res_id = reservation_context.id api = helper.get_api_session() session = paramiko.SSHClient() session.set_missing_host_key_policy(paramiko.AutoAddPolicy()) session.connect(resource_context.address, 22, 'root', 'amdocs') channel = session.invoke_shell() prompt = '.*]#' api.WriteMessageToReservationOutput( res_id, resource_context.name + ' sending command "mkdir -p /stage') _ssh_command(session, channel, 'mkdir -p /stage', prompt) api.WriteMessageToReservationOutput( res_id, resource_context.name + ' --previous command complete') api.WriteMessageToReservationOutput( res_id, resource_context.name + ' sending command "scp [email protected]:/stage/BSR9.9/pcrf/* /stage/"')
def get_debug_session(): username = '******' password = '******' domain = 'Global' server = 'localhost' resId = '325e5105-47c9-4add-8e6c-8fd6a6f1fc8e' attach_to_cloudshell_as(user=username, password=password, domain=domain, server_address=server, reservation_id=resId, service_name='UptimeEnforcer') get_debug_session() session = sh.get_api_session() token = session.token_id reservation_context = sh.get_reservation_context_details() reservation_context.reservation_id = reservation_context.id connectivity_context = sh.get_connectivity_context_details() connectivity_context.admin_auth_token = token resource_context = sh.get_resource_context_details() reservation_description = session.GetReservationDetails( reservation_context.id).ReservationDescription services = reservation_description.Services connectors = reservation_description.Connectors context_connectors = [
import cloudshell.helpers.scripts.cloudshell_scripts_helpers as script_help import cloudshell.helpers.scripts.cloudshell_dev_helpers as dev dev.attach_to_cloudshell_as( ) script_help.get_api_session() script_help.get_resource_context_details().attributes
from cloudshell.api.cloudshell_api import CloudShellAPISession from cloudshell.api.common_cloudshell_api import CloudShellAPIError from cloudshell.helpers.scripts import cloudshell_scripts_helpers as helpers from cloudshell.helpers.scripts import cloudshell_dev_helpers as dev_helpers dev_helpers.attach_to_cloudshell_as("admin","admin","Global","55aec269-792f-4ca9-8156-9967788d3a4f","10.211.55.4") reservation_id = helpers.get_reservation_context_details().id try: helpers.get_api_session().ExecuteCommand(reservation_id, "DriverDeepDive", "Resource", "failed_command") except CloudShellAPIError as err: print err.message raise
def __init__(self): self.reservation_id = helpers.get_reservation_context_details().id self.session = helpers.get_api_session() self.routes = self.session.GetReservationDetails(self.reservation_id).ReservationDescription.RequestedRoutesInfo
def execute(): api = helpers.get_api_session() inputs = helpers.get_reservation_context_details().parameters.global_inputs res_id = helpers.get_reservation_context_details().id connectivity = helpers.get_connectivity_context_details() tempdir = tempfile.gettempdir() # install mock shells try: with zipfile.ZipFile(os.path.dirname(__file__), "r") as z: z.extractall(tempdir) shells = [ tempdir + "\\Trafficshell.zip", tempdir + "\\Putshell.zip", tempdir + "\\L2Mockswitch.zip" ] success = install_shells(connectivity, shells) api.WriteMessageToReservationOutput( reservationId=res_id, message='Shells installation results:\n' + success) except Exception as e: print e.message # get user/admin counts to create # admins_count = 0 # if 'Number of Sys Admins' in inputs: # admins_count = int(inputs['Number of Sys Admins']) users_count = 0 if 'Number of Users' in inputs: users_count = int(inputs['Number of Users']) domain_admins_count = 0 if 'Number of Domain Admins' in inputs: domain_admins_count = int(inputs['Number of Domain Admins']) # create domains and assign users group to them # first create users group try: api.AddNewGroup(groupName='Users Group', groupRole='Regular') except CloudShellAPIError as ex: pass # probably group exists already # then create domain admins group try: api.AddNewGroup(groupName='Domain Admins', groupRole='DomainAdmin') except CloudShellAPIError as ex: pass # probably group exists already # now create domains and assign the group to it domains_created = [] for domain in ['Test Team NY', 'Test Team Calif', 'Consulting Phili']: try: api.AddNewDomain(domainName=domain) api.AddGroupsToDomain(domainName=domain, groupNames=['Users Group']) domains_created.append(domain) # assign networking service category to the new domains #import_package(connectivity, domain, tempdir + "\\Networking Service Category.zip") api.AddGroupsToDomain(domainName=domain, groupNames=['Domain Admins']) #if domain == 'Test Team NY': # import_package(connectivity, domain, tempdir + "\\Apps for testing service category.zip") except CloudShellAPIError as ex: pass # probably domain exists already api.WriteMessageToReservationOutput( res_id, 'Domains created: ' + ','.join(domains_created)) # import the put blueprint try: api.WriteMessageToReservationOutput( res_id, 'Importing "PUT Traffic Test Blueprint"') import_package(connectivity, 'Test Team NY', tempdir + "\\PUT Traffic Test Blueprint.zip") api.WriteMessageToReservationOutput( res_id, 'Importing "PUT Traffic Test Blueprint" complete') except Exception as ex: api.WriteMessageToReservationOutput( res_id, 'Importing "PUT Traffic Test Blueprint" failed') pass # create users/admins groups = None # if admins_count > 0: # groups = api.GetGroupsDetails() # sysadmin_group = [g for g in groups.Groups if g.Name == "System Administrators"][0] # a = len(sysadmin_group.Users) + 1 # added_count = 0 # admins_created = [] # while added_count < admins_count: # try: # api.AddNewUser('admin' + str(a), 'admin' + str(a), '', isActive=True, isAdmin=True) # added_count += 1 # admins_created.append('admin' + str(a)) # except: # pass # a += 1 # api.WriteMessageToReservationOutput(res_id, 'Admins created: ' + ','.join(admins_created)) if domain_admins_count > 0: if groups is None: groups = api.GetGroupsDetails() dom_admin_group = [ g for g in groups.Groups if g.Name == "Domain Admins" ][0] a = len(dom_admin_group.Users) + 1 added_count = 0 dom_admins_created = [] while added_count < domain_admins_count: try: api.AddNewUser('dadmin' + str(a), 'dadmin' + str(a), '', isActive=True, isAdmin=False) api.AddUsersToGroup(['dadmin' + str(a)], 'Domain Admins') added_count += 1 dom_admins_created.append('dadmin' + str(a)) except: pass a += 1 api.WriteMessageToReservationOutput( res_id, 'Domain Admins created: ' + ','.join(dom_admins_created)) if users_count > 0: api.WriteMessageToReservationOutput( res_id, 'Creating users and resources, this might take a while...') if groups is None: groups = api.GetGroupsDetails() users_group = [g for g in groups.Groups if g.Name == "Users Group"][0] a = len(users_group.Users) + 1 added_count = 0 users_created = [] l2_resource_created = False while added_count < users_count: try: api.AddNewUser('user' + str(a), 'user' + str(a), '', isActive=True, isAdmin=False) api.AddUsersToGroup(['user' + str(a)], 'Users Group') added_count += 1 users_created.append('user' + str(a)) except: pass a += 1 # create resources for this user (PUT+Traffic) try: api.CreateFolder('PUTs') #postfix_rn = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6)) postfix_rn = str(a - 1) resource_name = 'Product Under Test - ' + postfix_rn api.CreateResource('CS_GenericResource', 'Putshell', resource_name, '10.10.10.' + str(a), 'PUTs', '', 'A fake resource for training') api.UpdateResourceDriver(resource_name, 'Putshell') api.AutoLoad(resource_name) api.AddResourcesToDomain('Test Team NY', [resource_name], True) api.CreateFolder('Traffic Generators') #postfix_tg = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6)) postfix_tg = str(a - 1) traffic_name = 'Traffic Generator 2.0 - ' + postfix_tg api.CreateResource('CS_GenericResource', 'Trafficshell', traffic_name, '10.10.11.' + str(a), 'Traffic Generators', '', 'A fake resource for training') api.UpdateResourceDriver(traffic_name, 'Trafficshell') api.AutoLoad(traffic_name) api.AddResourcesToDomain('Test Team NY', [traffic_name], True) # connect devices to the patch panel patch_name = 'Patch Panel - Training' api.CreateResources([ ResourceInfoDto('Panel Jack', 'Generic Jack', 'Port 1 - PUT' + postfix_rn, '1', '', patch_name, ''), ResourceInfoDto('Panel Jack', 'Generic Jack', 'Port 2 - PUT' + postfix_rn, '2', '', patch_name, ''), ResourceInfoDto('Panel Jack', 'Generic Jack', 'Port 1 - TG' + postfix_tg, '1', '', patch_name, ''), ResourceInfoDto('Panel Jack', 'Generic Jack', 'Port 2 - TG' + postfix_tg, '2', '', patch_name, '') ]) api.AddResourcesToDomain('Test Team NY', [patch_name], True) api.UpdatePhysicalConnections([ PhysicalConnectionUpdateRequest( resource_name + '/Port 1', patch_name + '/Port 1 - PUT' + postfix_rn, '10'), PhysicalConnectionUpdateRequest( resource_name + '/Port 2', patch_name + '/Port 2 - PUT' + postfix_rn, '10'), PhysicalConnectionUpdateRequest( traffic_name + '/Port 1', patch_name + '/Port 1 - TG' + postfix_tg, '10'), PhysicalConnectionUpdateRequest( traffic_name + '/Port 2', patch_name + '/Port 2 - TG' + postfix_tg, '10') ]) # create L2 mock switch if needed l2_training = 'L2 Mock Switch - Training' try: if l2_resource_created == False: try: l2 = api.GetResourceDetails(l2_training) l2_resource_created = True except: pass if l2_resource_created == False: api.CreateResource( resourceFamily='CS_Switch', resourceModel='L2Mockswitch', resourceName=l2_training, resourceAddress='1.2.3.4', folderFullPath='', parentResourceFullPath='', resourceDescription='A fake resource for training') api.UpdateResourceDriver(l2_training, 'L2Mockswitch') api.CreateResource( resourceFamily='CS_Chassis', resourceModel='L2Mockswitch.GenericChassis', resourceName='Chassis1', resourceAddress='1', folderFullPath='', parentResourceFullPath=l2_training, resourceDescription='') except Exception as ex: api.WriteMessageToReservationOutput(res_id, ex.message) pass # resource probably exists already # add L2 ports and connect to PUT chassis_name = l2_training + '/Chassis1' api.CreateResources([ ResourceInfoDto('CS_Port', 'L2Mockswitch.GenericPort', 'Port 3 - PUT' + postfix_rn, '3', '', chassis_name, ''), ResourceInfoDto('CS_Port', 'L2Mockswitch.GenericPort', 'Port 4 - PUT' + postfix_rn, '4', '', chassis_name, ''), ResourceInfoDto('CS_Port', 'L2Mockswitch.GenericPort', 'Port 3 - TG' + postfix_tg, '3', '', chassis_name, ''), ResourceInfoDto('CS_Port', 'L2Mockswitch.GenericPort', 'Port 4 - TG' + postfix_tg, '4', '', chassis_name, '') ]) api.AddResourcesToDomain('Test Team NY', [l2_training], True) api.UpdatePhysicalConnections([ PhysicalConnectionUpdateRequest( resource_name + '/Port 3', chassis_name + '/Port 3 - PUT' + postfix_rn, '10'), PhysicalConnectionUpdateRequest( resource_name + '/Port 4', chassis_name + '/Port 4 - PUT' + postfix_rn, '10'), PhysicalConnectionUpdateRequest( traffic_name + '/Port 3', chassis_name + '/Port 3 - TG' + postfix_tg, '10'), PhysicalConnectionUpdateRequest( traffic_name + '/Port 4', chassis_name + '/Port 4 - TG' + postfix_tg, '10') ]) except Exception as ex: api.WriteMessageToReservationOutput(res_id, ex.message) pass # try: # api.AddTopologiesToDomain('Test Team NY', ['PUT Traffic Test']) # except: # pass api.WriteMessageToReservationOutput( res_id, 'Users created: ' + ','.join(users_created)) print 'Process complete'
import cloudshell.helpers.scripts.cloudshell_scripts_helpers as cs_helper from cloudshell.api.common_cloudshell_api import CloudShellAPIError route_list = [] res_id = cs_helper.get_reservation_context_details().id route_details = cs_helper.get_api_session().GetReservationDetails(res_id).ReservationDescription.TopologiesRouteInfo w2output = cs_helper.get_api_session().WriteMessageToReservationOutput # build route lists # route lists used by the Route API are just are endpoints paired in an open list: # ['source1', 'target1', 'source2', 'target2', ... 'sourceN', 'targetN'] for route in route_details: for r in route.Routes: route_list.append(r.Source) route_list.append(r.Target) # execute routes if len(route_list) > 0: try: w2output(reservationId=res_id, message='Queuing {} routes for disconnection'.format(len(route_list)/2)) cs_helper.get_api_session().DisconnectRoutesInReservation(reservationId=res_id, endpoints=route_list) except CloudShellAPIError as err: w2output(reservationId=res_id, message=err.message)
def main(): session = helpers.get_api_session() command_to_run = helpers.get_user_param("Command Name") try_execute_command_on_resources(session, reservation_id=helpers.get_reservation_context_details().id, command_name=command_to_run)
:return: """ resv_det = api.GetReservationDetails(reservation.id) server = None user = None password = None for resource in resv_det.ReservationDescription.Resources: if resource.ResourceModelName.lower() == 'generic tftp server': server = resource.FullAddress res_det = api.GetResourceDetails(resource.Name) for attribute in res_det.ResourceAttributes: if attribute.Name == 'Storage username': user = attribute.Value if attribute.Name == 'Storage password': password = attribute.Value return server, user, password ses = helpers.get_api_session() reservation = helpers.get_reservation_context_details() resource = helpers.get_resource_context_details() filename = os.environ['FileName'] filename_input = InputNameValue('file_path', filename) ftp, user, password = get_ftp(ses, reservation) remote_host_input = InputNameValue('remote_host', ftp) ses.EnqueueCommand(reservation.id, resource.name, 'Resource', 'load_firmware', [filename_input, remote_host_input])
def execute(self): api = helpers.get_api_session() resource_details_cache = {} api.WriteMessageToReservationOutput( reservationId=self.reservation_id, message='Beginning reservation setup') reservation_details = api.GetReservationDetails(self.reservation_id) deploy_result = self._deploy_apps_in_reservation( api=api, reservation_details=reservation_details) # refresh reservation_details after app deployment if any deployed apps if deploy_result and deploy_result.ResultItems: reservation_details = api.GetReservationDetails( self.reservation_id) self._connect_all_routes_in_reservation( api=api, reservation_details=reservation_details) self._run_async_power_on_refresh_ip_install( api=api, reservation_details=reservation_details, deploy_results=deploy_result, resource_details_cache=resource_details_cache) self._try_exeucte_autoload( api=api, reservation_details=reservation_details, deploy_result=deploy_result, resource_details_cache=resource_details_cache) remote_host, user, password = self._get_ftp(api, self.reservation_id) global_inputs = helpers.get_reservation_context_details( ).parameters.global_inputs api.WriteMessageToReservationOutput(reservationId=self.reservation_id, message=str(global_inputs)) # Begin Firmware load for IntlTAC environments ############################################# # Check for presense of version selector input if 'GigaVue Version' in global_inputs: self.logger.info( "Executing load_firmware for relevant devices: version " + global_inputs['GigaVue Version']) api.WriteMessageToReservationOutput( reservationId=self.reservation_id, message='Beginning load_firmware') version = global_inputs['GigaVue Version'] self._apply_software_image( api=api, reservation_details=reservation_details, deploy_result=deploy_result, resource_details_cache=resource_details_cache, version=version, remote_host=remote_host) self.logger.info("Setup for reservation {0} completed".format( self.reservation_id)) api.WriteMessageToReservationOutput( reservationId=self.reservation_id, message='Reservation setup finished successfully')
import cloudshell.helpers.scripts.cloudshell_scripts_helpers as script_helpers import debug import cloudshell_cli_handler def decrypt(password): decypted = session.DecryptPassword(password).Value return decypted debug.get_debug_session() res_id = script_helpers.get_reservation_context_details().id session = script_helpers.get_api_session() resources = session.GetReservationDetails( res_id).ReservationDescription.Resources password = script_helpers.get_resource_context_details().attributes.get( '{0}.Admin Password'.format( script_helpers.get_resource_context_details().model)) i = 0 while i < 5: try: password = decrypt(password) except: i = 1000 i = i + 1 CS_Cli = cloudshell_cli_handler.CreateSession( host=script_helpers.get_resource_context_details().address, username=script_helpers.get_resource_context_details().attributes.get(
def main(): session = script_helpers.get_api_session() sandbox_id = script_helpers.get_reservation_context_details().id session.ConfigureApps(reservationId=sandbox_id, printOutput=True)
from cloudshell.helpers.scripts.cloudshell_scripts_helpers import get_reservation_context_details, get_api_session, \ get_resource_context_details api = get_api_session() sb_details = get_reservation_context_details() sb_id = sb_details.id resource_details = get_resource_context_details() name = resource_details.name ip = resource_details.address api.WriteMessageToReservationOutput(reservationId=sb_id, message=f"Resource name: {name}, IP: {ip}") # printing to std_out will be the return value of resource scripts print(f"resource script completed for '{name}'")
import cloudshell.helpers.scripts.cloudshell_scripts_helpers as cs_helper from cloudshell.api.common_cloudshell_api import CloudShellAPIError bi_dir = [] uni_dir = [] res_id = cs_helper.get_reservation_context_details().id route_details = cs_helper.get_api_session().GetReservationDetails( res_id).ReservationDescription.TopologiesRouteInfo w2output = cs_helper.get_api_session().WriteMessageToReservationOutput # build route lists # route lists used by the Route API are just are endpoints paired in an open list: # ['source1', 'target1', 'source2', 'target2', ... 'sourceN', 'targetN'] for route in route_details: for r in route.Routes: if r.RouteType == 'bi': bi_dir.append(r.Source) bi_dir.append(r.Target) if r.RouteType == 'uni': uni_dir.append(r.Source) uni_dir.append(r.Target) # execute routes if len(bi_dir) > 0: try: w2output(reservationId=res_id, message='Queuing {} Bi-Dir routes for connection'.format( len(bi_dir) / 2)) cs_helper.get_api_session().ConnectRoutesInReservation( reservationId=res_id, endpoints=bi_dir, mappingType='bi')