def export_templates_to_file(self, export_file, name_list=None, template_type=None): device_templates = DeviceTemplates(self.session, self.host, self.port) feature_templates = FeatureTemplates(self.session, self.host, self.port) template_export = {} #pylint: disable=too-many-nested-blocks if template_type != 'feature': # Export the device templates and associated feature templates device_template_list = device_templates.get_device_template_list( name_list=name_list) template_export.update( {'vmanage_device_templates': device_template_list}) feature_name_list = [] if name_list: for device_template in device_template_list: if 'generalTemplates' in device_template: for general_template in device_template[ 'generalTemplates']: if 'templateName' in general_template: feature_name_list.append( general_template['templateName']) if 'subTemplates' in general_template: for sub_template in general_template[ 'subTemplates']: if 'templateName' in sub_template: feature_name_list.append( sub_template['templateName']) name_list = list(set(feature_name_list)) # Since device templates depend on feature templates, we always add them. feature_templates = FeatureTemplates(self.session, self.host, self.port) feature_template_list = feature_templates.get_feature_template_list( name_list=name_list) template_export.update( {'vmanage_feature_templates': feature_template_list}) if export_file.endswith('.json'): with open(export_file, 'w') as outfile: json.dump(template_export, outfile, indent=4, sort_keys=False) elif export_file.endswith('.yaml') or export_file.endswith('.yml'): with open(export_file, 'w') as outfile: yaml.dump(template_export, outfile, indent=4, sort_keys=False) else: raise Exception("File format not supported")
def run_module(): # define available arguments/parameters a user can pass to the module argument_spec = vmanage_argument_spec() argument_spec.update(factory_default=dict(type='bool', default=False), ) # seed the result dict in the object # we primarily care about changed and state # change is if this module effectively modified the target # state will include any data that you want your module to pass back # for consumption, for example, in a subsequent task result = dict(changed=False, original_message='', message='') # the AnsibleModule object will be our abstraction working with Ansible # this includes instantiation, a couple of common attr would be the # args/params passed to the execution, as well as if the module # supports check mode module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) vmanage = Vmanage(module) feature_templates = FeatureTemplates(vmanage.auth, vmanage.host) vmanage.result[ 'feature_templates'] = feature_templates.get_feature_template_list( factory_default=vmanage.params['factory_default']) vmanage.exit_json(**vmanage.result)
def __init__(self, session, host, port=443): """Initialize Files object with session parameters. Args: session (obj): Requests Session object host (str): hostname or IP address of vManage port (int): default HTTPS 443 """ self.session = session self.host = host self.port = port self.base_url = f'https://{self.host}:{self.port}/dataservice/' self.device_templates = DeviceTemplates(self.session, self.host, self.port) self.feature_templates = FeatureTemplates(self.session, self.host, self.port) self.template_data = TemplateData(self.session, self.host, self.port) self.policy_data = PolicyData(self.session, self.host, self.port) self.policy_lists = PolicyLists(self.session, self.host, self.port) self.policy_definitions = PolicyDefinitions(self.session, self.host, self.port) self.local_policy = LocalPolicy(self.session, self.host, self.port) self.central_policy = CentralPolicy(self.session, self.host, self.port) self.vmanage_device = Device(self.session, self.host, self.port)
def __init__(self, session, host, port=443): """Initialize Device Templates object with session parameters. Args: session (obj): Requests Session object host (str): hostname or IP address of vManage port (int): default HTTPS 443 """ self.session = session self.host = host self.port = port self.base_url = f'https://{self.host}:{self.port}/dataservice/' self.feature_templates = FeatureTemplates(self.session, self.host, self.port)
def __init__(self, session, host, port=443): """Initialize Reset vManage object with session parameters. Args: session (obj): Requests Session object host (str): hostname or IP address of vManage port (int): default HTTPS 443 """ self.session = session self.host = host self.port = port self.base_url = f'https://{self.host}:{self.port}/dataservice/' self.utilities = Utilities(self.session, self.host) self.cen_pol = CentralizedPolicy(self.session, self.host) self.inventory = DeviceInventory(self.session, self.host) self.dev_temps = DeviceTemplates(self.session, self.host) self.fet_temps = FeatureTemplates(self.session, self.host) self.loc_pol = LocalizedPolicy(self.session, self.host) self.sec_pol = SecurityPolicy(self.session, self.host) self.pol_lists = PolicyLists(self.session, self.host)
def templates(ctx, template_type, diff, default, name, json): """ Show template information """ device_templates = DeviceTemplates(ctx.auth, ctx.host, ctx.port) feature_templates = FeatureTemplates(ctx.auth, ctx.host, ctx.port) template_data = TemplateData(ctx.auth, ctx.host, ctx.port) pp = pprint.PrettyPrinter(indent=2) if name: if template_type == 'device': template_list = template_data.export_device_template_list(name_list=[name]) elif template_type == 'feature': template_list = feature_templates.get_feature_template_list(name_list=[name]) else: raise click.ClickException("Must specify template type with name") template = template_list[0] if template_list else None if template: if diff: diff_template = {} if template_type == 'device': diff_template_list = template_data.export_device_template_list(name_list=[diff]) if diff_template_list: diff_template = diff_template_list[0] else: click.secho(f"Cannot find device template {diff}", fg="red") elif template_type == 'feature': diff_template_list = feature_templates.get_feature_template_list(name_list=[diff]) if diff_template_list: diff_template = diff_template_list[0] else: click.secho(f"Cannot find feature template {diff}", fg="red") else: # Should not get here raise click.ClickException(f"Unknown template type {template_type}") if diff_template: diff_ignore = set([ 'templateId', 'policyId', 'connectionPreferenceRequired', 'connectionPreference', 'templateName', 'attached_devices', 'input' ]) diff = dictdiffer.diff(template, diff_template, ignore=diff_ignore) pp.pprint(list(diff)) else: pp.pprint(template) else: click.secho(f"Cannot find template named {name}", fg="red") else: if template_type in ['device', None]: device_template_list = template_data.export_device_template_list(factory_default=default) if not json: click.echo(" DEVICES") click.echo("NAME TYPE ATTACHED DEVICE TYPES") click.echo("--------------------------------------------------------------------------") for template in device_template_list: attached_devices = device_templates.get_template_attachments(template['templateId']) click.echo( f"{template['templateName'][:30]:30} {template['configType'][:10]:10} {len(attached_devices):<9} {template['deviceType'][:16]:16} " ) click.echo() else: pp.pprint(device_template_list) if template_type in ['feature', None]: feature_template_list = feature_templates.get_feature_template_list(factory_default=default) if not json: click.echo(" DEVICE DEVICES DEVICE") click.echo("NAME TYPE TEMPLATES ATTACHED MODELS") click.echo("------------------------------------------------------------------------------------") for template in feature_template_list: click.echo( f"{template['templateName'][:30]:30} {template['templateType'][:20]:20} {template['attachedMastersCount']:<10} {template['devicesAttached']:<9} {','.join(template['deviceType'])[:16]:16}" ) else: pp.pprint(feature_template_list)
def run_module(): # define available arguments/parameters a user can pass to the module argument_spec = vmanage_argument_spec() argument_spec.update(state=dict(type='str', choices=['absent', 'present'], default='present'), name=dict(type='str', alias='templateName'), description=dict(type='str', alias='templateDescription'), definition=dict(type='dict', alias='templateDefinition'), template_type=dict(type='str', alias='templateType'), device_type=dict(type='list', alias='deviceType'), template_min_version=dict(type='str', alias='templateMinVersion'), factory_default=dict(type='bool', alias='factoryDefault'), url=dict(type='bool', alias='templateUrl'), update=dict(type='bool', default=True), aggregate=dict(type='list'), push=dict(type='bool', default=False)) # seed the result dict in the object # we primarily care about changed and state # change is if this module effectively modified the target # state will include any data that you want your module to pass back # for consumption, for example, in a subsequent task result = dict(changed=False, ) # the AnsibleModule object will be our abstraction working with Ansible # this includes instantiation, a couple of common attr would be the # args/params passed to the execution, as well as if the module # supports check mode module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) vmanage = Vmanage(module) vmanage_feature_templates = FeatureTemplates(vmanage.auth, vmanage.host) vmanage_template_data = TemplateData(vmanage.auth, vmanage.host) # Always as an aggregate... make a list if just given a single entry if vmanage.params['aggregate']: feature_template_list = vmanage.params['aggregate'] else: if vmanage.params['state'] == 'present': try: feature_template_list = [{ 'templateName': vmanage.params['name'], 'templateDescription': vmanage.params['description'], 'deviceType': vmanage.params['device_type'], 'templateDefinition': vmanage.params['definition'], 'templateType': vmanage.params['template_type'], 'templateMinVersion': vmanage.params['template_min_version'], 'factoryDefault': vmanage.params['factory_default'] }] except: module.fail_json( msg= "Required values: name, description, device_type, definition, template_type, template_min_version, factory_default" ) else: try: feature_template_list = [{ 'templateName': vmanage.params['name'] }] except: module.fail_json(msg='Required values: name') feature_template_updates = [] if vmanage.params['state'] == 'present': feature_template_updates = vmanage_template_data.import_feature_template_list( feature_template_list, check_mode=module.check_mode, update=vmanage.params['update'], push=vmanage.params['push']) if feature_template_updates: vmanage.result['changed'] = True else: feature_template_dict = vmanage_feature_templates.get_feature_template_dict( factory_default=True, remove_key=False) for feature_template in feature_template_list: if feature_template['templateName'] in feature_template_dict: if not module.check_mode: vmanage_feature_templates.delete_feature_template( feature_template_dict[ feature_template['templateName']]['templateId']) vmanage.result['changed'] = True vmanage.result['updates'] = feature_template_updates vmanage.exit_json(**vmanage.result)
def import_templates_from_file(self, file, update=False, check_mode=False, name_list=None, template_type=None): vmanage_device_templates = DeviceTemplates(self.session, self.host, self.port) vmanage_feature_templates = FeatureTemplates(self.session, self.host, self.port) feature_template_updates = [] device_template_updates = [] template_data = {} # Read in the datafile if not os.path.exists(file): raise Exception(f"Cannot find file {file}") with open(file) as f: if file.endswith('.yaml') or file.endswith('.yml'): template_data = yaml.safe_load(f) else: template_data = json.load(f) if 'vmanage_feature_templates' in template_data: imported_feature_template_list = template_data[ 'vmanage_feature_templates'] else: imported_feature_template_list = [] imported_device_template_list = [] #pylint: disable=too-many-nested-blocks if template_type != 'feature': # Import the device templates and associated feature templates if 'vmanage_device_templates' in template_data: imported_device_template_list = template_data[ 'vmanage_device_templates'] if name_list: feature_name_list = [] pruned_device_template_list = [] for device_template in imported_device_template_list: if device_template['templateName'] in name_list: pruned_device_template_list.append(device_template) if 'generalTemplates' in device_template: for general_template in device_template[ 'generalTemplates']: if 'templateName' in general_template: feature_name_list.append( general_template['templateName']) if 'subTemplates' in general_template: for sub_template in general_template[ 'subTemplates']: if 'templateName' in sub_template: feature_name_list.append( sub_template['templateName']) imported_device_template_list = pruned_device_template_list name_list = list(set(feature_name_list)) # Since device templates depend on feature templates, we always add them. if name_list: pruned_feature_template_list = [] imported_feature_template_dict = self.list_to_dict( imported_feature_template_list, key_name='templateName', remove_key=False) for feature_template_name in name_list: if feature_template_name in imported_feature_template_dict: pruned_feature_template_list.append( imported_feature_template_dict[feature_template_name]) # Otherwise, we hope the feature list is already there (e.g. Factory Default) imported_feature_template_list = pruned_feature_template_list # Process the feature templates feature_template_updates = vmanage_feature_templates.import_feature_template_list( imported_feature_template_list, check_mode=check_mode, update=update) # Process the device templates device_template_updates = vmanage_device_templates.import_device_template_list( imported_device_template_list, check_mode=check_mode, update=update) return { 'feature_template_updates': feature_template_updates, 'device_template_updates': device_template_updates, }