def search_rule(self, search): """ Search a rule for a rule tag or name value Result will be the meta data for rule (name, href, type) Searching for a rule in specific policy:: f = FirewallPolicy(policy) search = f.search_rule(searchable) :param str search: search string :return: rule elements matching criteria :rtype: list(Element) """ result = self.make_request( resource='search_rule', params={'filter': search}) if result: results = [] for data in result: typeof = data.get('type') if 'ethernet' in typeof: klazz = lookup_class('ethernet_rule') elif typeof in [ 'ips_ipv4_access_rule', 'l2_interface_ipv4_access_rule']: klazz = lookup_class('layer2_ipv4_access_rule') else: klazz = lookup_class(typeof) results.append(klazz(**data)) return results return []
def search_rule(self, search): """ Search a rule for a rule tag or name value Result will be the meta data for rule (name, href, type) Searching for a rule in specific policy:: f = FirewallPolicy(policy) search = f.search_rule(searchable) :param str search: search string :return: rule elements matching criteria :rtype: list(Element) """ result = self.make_request(resource='search_rule', params={'filter': search}) if result: results = [] for data in result: typeof = data.get('type') if 'ethernet' in typeof: klazz = lookup_class('ethernet_rule') elif typeof in [ 'ips_ipv4_access_rule', 'l2_interface_ipv4_access_rule' ]: klazz = lookup_class('layer2_ipv4_access_rule') else: klazz = lookup_class(typeof) results.append(klazz(**data)) return results return []
def delete_routing(self, engine): """ Iterate through specified routes and remove and log the state. Catch exceptions so overall state can be reported after run. :rtype: bool """ changed = False for element in route_element: for it in getattr(self, element): if 'interface_id' not in it: break try: if 'antispoofing_network' in element: iface = engine.antispoofing.get(it.get('interface_id')) for dest in it.get('destination', []): klazz = lookup_class(dest.get('type')) modified = iface.remove(klazz(dest.get('name'))) if modified: self.results['state'].append( dict(action='deleted', name=dest.get('name'), type='antispoofing')) changed = True else: if 'name' not in it: break iface = engine.routing.get(it.get('interface_id')) klazz = lookup_class(element) if element != 'static_route'\ else lookup_class('router') modified = iface.remove_route_gateway(klazz(it.get('name'))) if modified: self.results['state'].append( dict(action='deleted', name=it.get('name'), type=klazz.typeof)) changed = True except InterfaceNotFound: self.results['state'].append( dict(action='Cannot find specified interface', name=it.get('interface_id'), type='interface')) except SMCException as e: self.results['state'].append( dict(action='Failed to delete with reason: %s' % str(e), name=it.get('name'), type=klazz.typeof)) return changed
def create_or_update_element(self, element): """ Create the element. :param dict element: the element dict from elements """ changed = False for typeof, values in element.items(): klazz = lookup_class(typeof) if ('access_list' in klazz.typeof or 'prefix_list' in klazz.typeof)\ and self.overwrite_existing: obj, modified, created = klazz.update_or_create( with_status=True, overwrite_existing=True, **values) else: obj, modified, created = klazz.update_or_create( with_status=True, **values) if created: self.results['state'].append( {'name': obj.name, 'type': obj.typeof, 'action': 'created'}) elif modified: self.results['state'].append( {'name': obj.name, 'type': obj.typeof, 'action': 'modified'}) changed = created or modified return changed
def exec_module(self, **kwargs): state = kwargs.pop('state', 'present') for name, value in kwargs.items(): setattr(self, name, value) changed = False try: if state == 'present': self.cache = Cache() self.check_elements() # Any missing dependencies.. if self.cache.missing: self.fail(msg='Missing dependent elements that are not created within this ' 'playbook: %s' % self.cache.missing) deferrals, elements = self.resolve_references(self.elements) if self.cache.missing: self.fail(msg='Missing elements that have a dependency, cannot continue: %s' % self.cache.missing) if self.check_mode: return self.results for element in elements: if self.create_or_update_element(element): changed = True if deferrals: _, ospf_elements = self.resolve_references(deferrals) for element in ospf_elements: if self.create_or_update_element(element): changed = True else: # No need to validate elements beyond type and name for element in self.elements: for typeof, values in element.items(): klazz = lookup_class(typeof) name = values.get('name') if name: try: klazz(name).delete() result = {'name': name, 'type': klazz.typeof, 'action': 'deleted'} changed = True except SMCException as e: result = {'name': name, 'type': klazz.typeof, 'action': 'failed to delete ' 'with reason: %s' % str(e)} finally: self.results['state'].append(result) except SMCException as err: self.fail(msg=str(err), exception=traceback.format_exc()) self.results['changed'] = changed return self.results
def allowed_args_by_lookup(typeof, method=None): """ Return the allowed arguments and kwargs by name based on the classes typeof attribute. You should validate that the typeof is valid descendent of `smc.base.model.Element` before calling this method :return: list of argument names :rtype: list """ clazz = lookup_class(typeof) return allowed_args(clazz, method)
def exec_module(self, **kwargs): state = kwargs.pop('state', 'present') for name, value in kwargs.items(): setattr(self, name, value) changed = False try: if state == 'present': self.check_elements() # Defer ExternalBGPPeer as it's dependent on having a valid # AutonomousSystem element, but only if the AS doesn't already exist deferrals, elements = self.resolve_references(self.elements) if self.check_mode: return self.results for element in elements: if self.create_or_update_element(element): changed = True if deferrals: empty, bgp_peers = self.resolve_references(deferrals) for element in bgp_peers: if self.create_or_update_element(element): changed = True else: # No need to validate elements beyond type and name for element in self.elements: for typeof, values in element.items(): klazz = lookup_class(typeof) name = values.get('name') if name: try: klazz(name).delete() self.results['state'].append( {'name': name, 'type': klazz.typeof, 'action': 'deleted'}) changed = True except SMCException as e: self.results['state'].append( {'name': name, 'type': klazz.typeof, 'action': 'failed to delete ' 'with reason: %s' % str(e)}) except SMCException as err: self.fail(msg=str(err), exception=traceback.format_exc()) self.results['changed'] = changed return self.results
def test_InterfaceFactory(self): # Test the interface factory. Should return the right class given the # 'typeof' attribute setting import smc.core.interfaces for i in [smc.core.interfaces]: # smc.core.sub_interfaces]: for _, klazz in inspect.getmembers(i, inspect.isclass): if hasattr(klazz, 'typeof'): rc = SubInterface.get_subinterface(klazz.typeof) if rc: self.assertEqual(rc, klazz) else: #rc = InterfaceFactory(klazz.typeof) rc = lookup_class(klazz.typeof, Interface) self.assertEqual(rc, klazz)
def exec_module(self, **kwargs): state = kwargs.pop('state', 'present') for name, value in kwargs.items(): setattr(self, name, value) # Validate whether the element type is valid entry_points = Search.object_types() for element in self.elements: for typeof, element_data in element.items(): if typeof not in entry_points: self.fail(msg='The specified element type: %s is not valid. ' 'Data provided: %s' % (typeof, element)) if 'name' not in element_data: self.fail(msg='The name field is required to operate on all ' 'elements. Data provided: %s' % element) try: if self.check_mode: return self.results for element in self.elements: for typeof, data in element.items(): try: instance, updated, created = lookup_class(typeof).update_or_create( with_status=True, **data) action = 'none' if updated: action = 'updated' elif created: action = 'created' if updated or created: self.results['changed'] = True self.results['state'].append(dict(name=instance.name, typeof=instance.typeof, action=action)) except SMCException as e: self.results['state'].append(dict(name=data.get('name'), typeof=typeof, action='error', reason=str(e))) except SMCException as err: self.fail(msg=str(err), exception=traceback.format_exc()) return self.results
def exec_module(self, **kwargs): for name, value in kwargs.items(): setattr(self, name, value) result = self.search_by_type(lookup_class(self.element)) if self.filter: if self.as_yaml: elements = [convert_to_dict(element) for element in result if element.name == self.filter] else: elements = [convert_to_dict(element) for element in result] else: elements = [{'name': element.name, 'type': element.typeof} for element in result] self.results['ansible_facts']['bgp_element'] = [{'elements': elements}]\ if elements else [] return self.results
def create_or_update_element(self, element): """ Create the element. :param dict element: the element dict from elements """ changed = False for typeof, values in element.items(): klazz = lookup_class(typeof) s_values = self.serialize_fields(typeof, values) obj, modified, created = klazz.update_or_create( with_status=True, **s_values) if created or modified: self.results['state'].append( {'name': obj.name, 'type': obj.typeof, 'action': 'created' if created else 'modified'}) changed = created or modified return changed
def __unicode__(self): return u'{0}(name={1})'.format( lookup_class(self.type).__name__, self.name)