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)
Ejemplo n.º 2
0
class ResetVmanage(object):
    """Reset all configuratios on a vManage instance.

    Executes the necessary REST calls in specific order to remove
    configurations applied to a vManage instance.

    """
    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 active_count_delay(self):

        activeCount = 1
        while activeCount != 0:
            time.sleep(1.0)
            data = self.utilities.get_active_count()
            activeCount = data["activeTaskCount"]

    def execute(self):

        # Step 1 - Deactivate Centralized Policy
        data = self.cen_pol.get_centralized_policy()
        for policy in data:
            if policy['isPolicyActivated']:
                policyId = policy['policyId']
                self.cen_pol.deactivate_centralized_policy(policyId)
        self.active_count_delay()

        # Step 2 - Detach vedges from template
        data = self.inventory.get_device_list('vedges')
        for device in data:
            if (('deviceIP' in device)
                    and (device['configOperationMode'] == 'vmanage')):
                deviceId = device['uuid']
                deviceIP = device['deviceIP']
                deviceType = device['deviceType']
                self.inventory.post_device_cli_mode(deviceId, deviceIP,
                                                    deviceType)
        self.active_count_delay()

        # Step 3 - Detach controllers from template
        data = self.inventory.get_device_list('controllers')
        for device in data:
            if (('deviceIP' in device)
                    and (device['configOperationMode'] == 'vmanage')):
                deviceId = device['uuid']
                deviceIP = device['deviceIP']
                deviceType = device['deviceType']
                self.inventory.post_device_cli_mode(deviceId, deviceIP,
                                                    deviceType)
                # Requires pause between controllers
                self.active_count_delay()
        self.active_count_delay()

        # Step 4 - Delete All Device Templates
        data = self.dev_temps.get_device_templates()
        for device in data:
            templateId = device['templateId']
            self.dev_temps.delete_device_template(templateId)
        self.active_count_delay()

        # Step 5 - Delete All Feature Templates
        data = self.fet_temps.get_feature_templates()
        for device in data:
            #pylint: disable=no-else-continue
            if device['factoryDefault']:
                continue
            else:
                templateId = device['templateId']
                self.fet_temps.delete_feature_template(templateId)
        self.active_count_delay()

        # Step 6 - Delete All Centralized Policies
        data = self.cen_pol.get_centralized_policy()
        for policy in data:
            policyId = policy['policyId']
            self.cen_pol.delete_centralized_policy(policyId)
        self.active_count_delay()

        # Step 7 - Delete All Topology, Traffic, Cflowd Policies
        definitionList = [
            'control', 'mesh', 'hubandspoke', 'vpnmembershipgroup', 'approute',
            'data', 'cflowd'
        ]
        for definition in definitionList:
            data = self.cen_pol.get_policy_definition(definition)
            if data:
                for policy in data:
                    definitionId = policy['definitionId']
                    self.cen_pol.delete_policy_definition(
                        definition, definitionId)
        self.active_count_delay()

        # Step 8 - Delete All Localized Policies
        data = self.loc_pol.get_localized_policy()
        for policy in data:
            policyId = policy['policyId']
            self.loc_pol.delete_localized_policy(policyId)
        self.active_count_delay()

        # Step 9 - Delete All Localized Specific Definitions
        definitionList = [
            'qosmap', 'rewriterule', 'acl', 'aclv6', 'vedgeroute'
        ]
        for definition in definitionList:
            data = self.loc_pol.get_localized_definition(definition)
            if data:
                for policy in data:
                    definitionId = policy['definitionId']
                    self.loc_pol.delete_localized_definition(
                        definition, definitionId)
        self.active_count_delay()

        # Step 10 - Delete All Security Policies
        version = self.utilities.get_vmanage_version()
        if version >= '18.2.0':
            data = self.sec_pol.get_security_policy()
            for policy in data:
                policyId = policy['policyId']
                self.sec_pol.delete_security_policy(policyId)
            self.active_count_delay()

        # Step 11 - Delete All UTD Specific Security Policies
        version = self.utilities.get_vmanage_version()
        definitionList = []
        # TODO: implement a proper semver comparison, this will fail if version is 18.30.0
        if version >= '18.4.0':
            definitionList = [
                'zonebasedfw', 'urlfiltering', 'dnssecurity',
                'intrusionprevention', 'advancedMalwareProtection'
            ]
        #pylint: disable=chained-comparison
        if version < '18.4.0' and version >= '18.2.0':
            definitionList = ['zonebasedfw']

        if definitionList:
            for definition in definitionList:
                data = self.sec_pol.get_security_definition(definition)
                if data:
                    for policy in data:
                        definitionId = policy['definitionId']
                        self.sec_pol.delete_security_definition(
                            definition, definitionId)
        self.active_count_delay()

        # Step 12 - Delete All Lists

        data = self.pol_lists.get_policy_list_all()
        for policy_list in data:
            owner = policy_list['owner']

            if owner != 'system':
                listType = policy_list['type'].lower()
                listId = policy_list['listId']
                self.pol_lists.delete_policy_list(listType, listId)

        return ('Reset Complete')
Ejemplo n.º 3
0
class CleanVmanage(object):
    """Reset all configuratios on a vManage instance.

    Executes the necessary REST calls in specific order to remove
    configurations applied to a vManage instance.

    """
    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.central_policy = CentralPolicy(self.session, self.host)
        self.local_policy = LocalPolicy(self.session, self.host)
        self.device = Device(self.session, self.host)
        self.device_templates = DeviceTemplates(self.session, self.host)
        self.feature_templates = FeatureTemplates(self.session, self.host)
        self.sec_pol = SecurityPolicy(self.session, self.host)
        self.policy_definitions = PolicyDefinitions(self.session, self.host)
        self.policy_lists = PolicyLists(self.session, self.host)

    def active_count_delay(self):
        """Delay while there are active tasks.

        """
        activeCount = 1
        while activeCount != 0:
            time.sleep(1.0)
            data = self.utilities.get_active_count()
            activeCount = data["activeTaskCount"]

    def clean_vedge_attachments(self):
        """Clean all vedge attachments

        """
        data = self.device.get_device_list('vedges')
        for device in data:
            if (('deviceIP' in device) and (device['configOperationMode'] == 'vmanage')):
                deviceId = device['uuid']
                deviceIP = device['deviceIP']
                deviceType = device['deviceType']
                self.device.post_device_cli_mode(deviceId, deviceIP, deviceType)
        self.active_count_delay()

    def clean_controller_attachments(self):
        """Clean all controller attachments

        """
        data = self.device.get_device_list('controllers')
        for device in data:
            if (('deviceIP' in device) and (device['configOperationMode'] == 'vmanage')):
                deviceId = device['uuid']
                deviceIP = device['deviceIP']
                deviceType = device['deviceType']
                self.device.post_device_cli_mode(deviceId, deviceIP, deviceType)
                # Requires pause between controllers
                self.active_count_delay()
        self.active_count_delay()

    def clean_device_templates(self):
        """Clean all device templates

        """
        data = self.device_templates.get_device_templates()
        for device in data:
            templateId = device['templateId']
            self.device_templates.delete_device_template(templateId)
        self.active_count_delay()

    def clean_feature_templates(self):
        """Clean all feature templates

        """
        data = self.feature_templates.get_feature_templates()
        for device in data:
            #pylint: disable=no-else-continue
            if device['factoryDefault']:
                continue
            else:
                templateId = device['templateId']
                self.feature_templates.delete_feature_template(templateId)
        self.active_count_delay()

    def clean_central_policy(self):
        """Clean all central policy

        """
        data = self.central_policy.get_central_policy()
        for policy in data:
            policy_id = policy['policyId']
            if policy['isPolicyActivated']:
                action_id = self.central_policy.deactivate_central_policy(policy_id)
                if action_id:
                    self.utilities.waitfor_action_completion(action_id)
            self.central_policy.delete_central_policy(policy_id)
        self.active_count_delay()

    def clean_local_policy(self):
        """Clean all local policy

        """
        data = self.local_policy.get_local_policy()
        for policy in data:
            policyId = policy['policyId']
            self.local_policy.delete_local_policy(policyId)
        self.active_count_delay()

    def clean_policy_definitions(self):
        """Clean all policy definitions

        """
        policy_definition_list = self.policy_definitions.get_policy_definition_list()
        for policy_definition in policy_definition_list:
            self.policy_definitions.delete_policy_definition(policy_definition['type'],
                                                             policy_definition['definitionId'])
        self.active_count_delay()

    def clean_policy_lists(self):
        """Clean all policy lists

        """
        policy_list_list = self.policy_lists.get_policy_list_list()
        for policy_list in policy_list_list:
            if not policy_list['readOnly'] and policy_list['owner'] != 'system':
                self.policy_lists.delete_policy_list(policy_list['type'], policy_list['listId'])
        self.active_count_delay()

    def clean_security_policy(self):
        """Clean all security policy

        """
        version = self.utilities.get_vmanage_version()
        if version >= '18.2.0':
            data = self.sec_pol.get_security_policy()
            for policy in data:
                policyId = policy['policyId']
                self.sec_pol.delete_security_policy(policyId)
            self.active_count_delay()

        # # Step 11 - Delete All UTD Specific Security Policies
        # version = self.utilities.get_vmanage_version()
        # definitionList = []
        # # TODO: implement a proper semver comparison, this will fail if version is 18.30.0
        # if version >= '18.4.0':
        #     definitionList = [
        #         'zonebasedfw', 'urlfiltering', 'dnssecurity', 'intrusionprevention', 'advancedMalwareProtection'
        #     ]
        # #pylint: disable=chained-comparison
        # if version < '18.4.0' and version >= '18.2.0':
        #     definitionList = ['zonebasedfw']

        # if definitionList:
        #     for definition in definitionList:
        #         data = self.sec_pol.get_security_definition(definition)
        #         if data:
        #             for policy in data:
        #                 definitionId = policy['definitionId']
        #                 self.sec_pol.delete_security_definition(definition, definitionId)
        # self.active_count_delay()

        # # Step 12 - Delete All Lists

        # data = self.pol_lists.get_policy_list_all()
        # for policy_list in data:
        #     owner = policy_list['owner']

        #     if owner != 'system':
        #         listType = policy_list['type'].lower()
        #         listId = policy_list['listId']
        #         self.pol_lists.delete_policy_list(listType, listId)

    def clean_all(self):
        """Clean everything in vManage

        """
        # Step 1 - Deactivate Central Policy
        self.clean_central_policy()

        # Step 2 - Detach vedges from template
        self.clean_vedge_attachments()

        # Step 3 - Detach controllers from template
        self.clean_controller_attachments()

        # Step 4 - Delete All Device Templates
        self.clean_device_templates()

        # Step 5 - Delete All Feature Templates
        self.clean_feature_templates()

        # Step 6 - Delete All Centralized Policies
        self.clean_central_policy()

        # Step 7 - Delete All Policy Definitions
        self.clean_policy_definitions()

        # Step 8 - Delete All Policy Lists
        self.clean_policy_lists()

        # Step 9 - Delete All Local Policies
        self.clean_local_policy()

        # Step 10 - Delete All Security Policies
        self.clean_security_policy()

        return ('Reset Complete')