def run_module():
    # define available arguments/parameters a user can pass to the module
    argument_spec = viptela_argument_spec()
    argument_spec.update(organization=dict(type='str'),
                         vbond=dict(type='str'),
                         vbond_port=dict(type='int', default=12346),
                         root_cert=dict(type='str'),
                         push=dict(type='bool'))

    # 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,
    )
    viptela = viptelaModule(module)
    viptela.result['what_changed'] = []

    if viptela.params['push']:
        viptela.push_certificates()

    if viptela.result['what_changed']:
        viptela.result['changed'] = True

    viptela.exit_json(**viptela.result)
def run_module():
    # define available arguments/parameters a user can pass to the module
    argument_spec = viptela_argument_spec()
    argument_spec.update(id=dict(type='str', required=True), )

    # 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,
    )
    viptela = viptelaModule(module)

    response = viptela.request('/dataservice/device/action/status/{0}'.format(
        viptela.params['id']))
    if response.json:
        viptela.result['json'] = response.json

    viptela.exit_json(**viptela.result)
Beispiel #3
0
def run_module():
    # define available arguments/parameters a user can pass to the module
    argument_spec = viptela_argument_spec()
    argument_spec.update(vedge=dict(type='str', required=True),
                         dst_ip=dict(type='str', required=True, alias='host'),
                         vpn=dict(type='int', default=0, required=False),
                         src_interface=dict(type='str', required=False, alias='source'),
                         probe_type=dict(type='str', required=False, default='icmp', alias='probeType'),
                         count=dict(type='str', required=False),
                         size=dict(type='str', required=False),
                         df=dict(type='str', required=False),
                         rapid=dict(type='bool', required=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,
                           )
    viptela = viptelaModule(module)
    device_dict = viptela.get_device_dict('vedge')

    if viptela.params['vedge'] in device_dict:
        system_ip = device_dict[viptela.params['vedge']]['system-ip']
    else:
        viptela.fail_json(msg="Cannot find vedge {0}".format(viptela.params['vedge']))

    payload = {
        'host': viptela.params['dst_ip'],
        'vpn': str(viptela.params['vpn']),
        'probeType': viptela.params['probe_type'],
    }
    if viptela.params['src_interface']:
        payload['source'] = viptela.params['src_interface']
    if viptela.params['count']:
        payload['count'] = viptela.params['count']
    if viptela.params['size']:
        payload['size'] = viptela.params['size']
    if viptela.params['df']:
        payload['df'] = viptela.params['df']
    if viptela.params['rapid']:
        payload['rapid'] = "true" if viptela.params['rapid'] else "false"

    response = viptela.request('/dataservice/device/tools/nping/{0}'.format(system_ip), method='POST', payload=payload)
    if response.json:
        viptela.result['json'] = response.json

    viptela.exit_json(**viptela.result)
Beispiel #4
0
def run_module():
    # define available arguments/parameters a user can pass to the module
    argument_spec = viptela_argument_spec()
    argument_spec.update(file=dict(type='str', required=True), )

    # 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,
    )
    viptela = viptelaModule(module)

    filename = os.path.basename(module.params['file'])

    payload = {
        'Content-Type': 'application/x-tar',
        'Content-Disposition': 'form-data; name="file"; filename=' + filename
    }

    if not module.check_mode:
        response = viptela.request(
            '/dataservice/device/action/software/package/virtualmachine',
            method='POST',
            files={'file': open(module.params['file'], 'rb')},
            data={
                'validity': 'valid',
                'upload': 'true'
            },
            headers=None)

        if response.status_code == 200:
            viptela.exit_json(changed=True)
        else:
            viptela.fail_json(msg="Upload failed")
def run_module():
    # define available arguments/parameters a user can pass to the module
    argument_spec = viptela_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,
    )
    viptela = viptelaModule(module)

    # if the user is working with this module in only check mode we do not
    # want to make any changes to the environment, just return the current
    # state with no modifications
    if module.check_mode:
        return result

    feature_templates = viptela.get_feature_template_list(
        factory_default=viptela.params['factory_default'])
    device_templates = viptela.get_device_template_list(
        factory_default=viptela.params['factory_default'])

    templates = {
        "feature_templates": feature_templates,
        "device_templates": device_templates,
    }

    viptela.logout()

    viptela.result['templates'] = templates
    viptela.exit_json(**viptela.result)
Beispiel #6
0
def run_module():
    # define available arguments/parameters a user can pass to the module
    argument_spec = viptela_argument_spec()
    argument_spec.update(file=dict(type='str', required=True), )

    # 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,
    )
    viptela = viptelaModule(module)

    if not module.check_mode:
        response = viptela.request(
            '/dataservice/system/device/fileupload',
            method='POST',
            files={'file': open(module.params['file'], 'rb')},
            data={
                'validity': 'valid',
                'upload': 'true'
            },
            headers=None)

        viptela.result['msg'] = response.json['vedgeListUploadStatus']
        if 'successfully' in response.json['vedgeListUploadStatus']:
            viptela.result['changed'] = True

    viptela.exit_json()
def run_module():
    # define available arguments/parameters a user can pass to the module
    argument_spec = viptela_argument_spec()
    argument_spec.update(state=dict(type='str',
                                    choices=['absent', 'present'],
                                    default='present'),
                         name=dict(type='str'),
                         transport_ip=dict(type='str',
                                           aliases=['device_ip', 'system_ip']),
                         uuid=dict(type='str', alias='deviceIP'),
                         personality=dict(
                             type='str',
                             choices=['vmanage', 'vsmart', 'vbond', 'vedge'],
                             default='vedge'),
                         device_username=dict(type='str', alias='device_user'),
                         device_password=dict(type='str'))

    # 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,
    )
    viptela = viptelaModule(module)
    viptela.result['what_changed'] = []

    if viptela.params['personality'] == 'vedge':
        device_type = 'vedges'
    else:
        device_type = 'controllers'

    device = {}
    if viptela.params['uuid']:
        device = viptela.get_device_status(viptela.params['uuid'], key='uuid')
    # See if we can find the device by deviceIP
    if not device and viptela.params['transport_ip']:
        device = viptela.get_device_status(viptela.params['transport_ip'])
    # If we could not find the device by deviceIP, see if we can find it be (host)name
    if not device and viptela.params['name']:
        device = viptela.get_device_status(viptela.params['name'],
                                           key='host-name')

    viptela.result['device'] = device
    if viptela.params['state'] == 'present':
        if device:
            # Can't really change anything
            pass
        else:
            viptela.result['what_changed'].append('new')
            if not viptela.params['device_username'] or not viptela.params[
                    'device_password']:
                viptela.fail_json(
                    msg=
                    "device_username and device_password must be specified when add a new device"
                )
            if not module.check_mode:
                response = viptela.create_controller(
                    viptela.params['transport_ip'],
                    viptela.params['personality'],
                    viptela.params['device_username'],
                    viptela.params['device_password'])
                viptela.result['response'] = response
    else:
        if device and device_type == 'controllers':
            if not module.check_mode:
                viptela.delete_controller(device['uuid'])
        elif device and device_type == 'vedges':
            device_config = viptela.get_device_by_uuid(device['uuid'],
                                                       type=device_type)
            if 'vedgeCertificateState' in device_config and device_config[
                    'vedgeCertificateState'] != 'tokengenerated':
                viptela.result['what_changed'].append('delete')
                if not module.check_mode:
                    viptela.decommision_device(device['uuid'])

    if viptela.result['what_changed']:
        viptela.result['changed'] = True

    viptela.exit_json(**viptela.result)
Beispiel #8
0
def run_module():
    # define available arguments/parameters a user can pass to the module
    argument_spec = viptela_argument_spec()
    argument_spec.update(state=dict(type='str', choices=['csr', 'cert', 'push'], default='cert'),
                         name=dict(type='str'),
                         transport_ip=dict(type='str', aliases=['device_ip', 'system_ip']),
                         cert=dict(type='str', alias='deviceEnterpriseCertificate'),
                         )

    # 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,
                           )
    viptela = viptelaModule(module)
    viptela.result['what_changed'] = []

    device = {}
    # See if we can find the device by deviceIP
    if viptela.params['transport_ip']:
        device = viptela.get_device_by_device_ip(viptela.params['transport_ip'], type='controllers')
    # If we could not find the device by deviceIP, see if we can find it be (host)name
    if not device:
        device = viptela.get_device_by_name(viptela.params['name'], type='controllers')

    if viptela.params['state'] == 'cert':
        if device:
            if not viptela.params['cert']:
                viptela.fail_json(msg="'cert' is required when added a certificate to a device")
            if device:
                if ('deviceEnterpriseCertificate' not in device) or (viptela.params['cert'] != device['deviceEnterpriseCertificate']):
                    viptela.result['what_changed'].append('deviceEnterpriseCertificate')
                    if not module.check_mode:
                        viptela.install_device_cert(viptela.params['cert'])
            else:
                viptela.fail_json(msg="Device must exist to add it's certificate")
        else:
            viptela.fail_json(msg="Device not found")
    elif viptela.params['state'] == 'csr':
        if 'deviceCSR' in device:
            viptela.result['deviceCSR'] = device['deviceCSR']
        else:
            viptela.result['what_changed'].append('csr')
            if not module.check_mode:
                if 'deviceIP' in device:
                    viptela.result['deviceCSR'] = viptela.generate_csr(device['deviceIP'])
                else:
                    viptela.fail_json(msg="Cannot find deviceIP for {0}".format(viptela.params['name']))
    elif viptela.params['state'] == 'push':
        viptela.push_certificates()

    if viptela.result['what_changed']:
        viptela.result['changed'] = True

    viptela.exit_json(**viptela.result)
def run_module():
    # define available arguments/parameters a user can pass to the module
    argument_spec = viptela_argument_spec()
    argument_spec.update(organization=dict(type='str'),
                         vbond=dict(type='str'),
                         vbond_port=dict(type='str', default='12346'),
                         root_cert=dict(type='str'),
                         ca_type=dict(type='str'))

    # 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,
    )
    viptela = viptelaModule(module)
    viptela.result['what_changed'] = []

    if viptela.params['organization']:
        current = viptela.get_vmanage_org()
        if viptela.params['organization'] != current:
            viptela.result['what_changed'].append('organization')
            if not module.check_mode:
                viptela.set_vmanage_org(viptela.params['organization'])

    if viptela.params['vbond']:
        current = viptela.get_vmanage_vbond()
        if viptela.params['vbond'] != current['vbond'] or viptela.params[
                'vbond_port'] != current['vbond_port']:
            viptela.result['what_changed'].append('vbond')
            if not module.check_mode:
                viptela.set_vmanage_vbond(viptela.params['vbond'],
                                          viptela.params['vbond_port'])

    if viptela.params['ca_type']:
        current = viptela.get_vmanage_ca_type()
        if viptela.params['ca_type'] != current:
            viptela.result['what_changed'].append('ca_type')
            if not module.check_mode:
                viptela.set_vmanage_ca_type(viptela.params['ca_type'])

    if viptela.params['root_cert']:
        current = viptela.get_vmanage_root_cert()
        if viptela.params['root_cert'] not in current:
            viptela.result['what_changed'].append('root_cert')
            if not module.check_mode:
                viptela.set_vmanage_root_cert(viptela.params['root_cert'])

    if viptela.result['what_changed']:
        viptela.result['changed'] = True

    viptela.exit_json(**viptela.result)
def run_module():
    # define available arguments/parameters a user can pass to the module
    argument_spec = viptela_argument_spec()
    argument_spec.update(devices=dict(type='list'),
                         deviceType=dict(type='str',
                                         choices=['controller', 'vedge'],
                                         default='vedge'),
                         version=dict(type='str'),
                         activate=dict(type='bool'),
                         set_default=dict(type='bool'))

    # 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,
    )
    viptela = viptelaModule(module)

    # It seems to me that the software operations on the vManage are already idempotent
    # This is why at least in this phase we are not implementing other idempotency checks
    # In future it might make sense to implement them to avoid generating useless tasks
    # on the vManage. This would streamline operations.
    # TODO Add idempotency cheks to this module

    devices = module.params['devices']
    deviceType = module.params['deviceType']
    version = module.params['version']
    data = [{"family": "vedge-x86", "version": version}]
    reboot = module.params['activate']
    set_default = module.params['set_default']

    # Verify if the target software (version) is available in the vManage and set flag
    vManage_software_list = viptela.get_software_images_list()
    software_present_on_vManage = False
    for software in vManage_software_list:
        if version == software['versionName']:
            software_present_on_vManage = True

    # If we have found the software we can move on and perform the operation
    if software_present_on_vManage:
        viptela.software_install(devices, deviceType, data, reboot)

        if set_default:
            for device in devices:
                device.update({'version': version})
            viptela.set_default_partition(devices, deviceType)

    # If not, we fail
    else:
        module.fail_json(msg="We don't have this software, I am sorry")

    viptela.exit_json(**viptela.result)
def run_module():
    action_id = None
    action_status = None
    action_activity = None
    action_config = None

    # define available arguments/parameters a user can pass to the module
    argument_spec = viptela_argument_spec()
    argument_spec.update(
        state=dict(type='str',
                   choices=['absent', 'present', 'query'],
                   default='present'),
        device_name=dict(type='str', aliases=['device', 'host-name']),
        device_ip=dict(type='str', aliases=['system_ip']),
        site_id=dict(type='str'),
        uuid=dict(type='str'),
        personality=dict(type='str',
                         choices=['vmanage', 'vsmart', 'vbond', 'vedge'],
                         default='vedge'),
        template=dict(type='str'),
        variables=dict(type='dict', default={}),
        wait=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,
    )
    viptela = viptelaModule(module)
    viptela.result['what_changed'] = []

    if viptela.params['personality'] == 'vedge':
        device_type = 'vedges'
    else:
        device_type = 'controllers'

    if viptela.params['uuid']:
        device_data = viptela.get_device_by_uuid(viptela.params['uuid'],
                                                 type=device_type)
        if 'uuid' not in device_data:
            viptela.fail_json(msg='Cannot find device with UUID: {0}.'.format(
                viptela.params['uuid']))
        # If this is a preallocation, we need to set these things.
        if 'system-ip' not in device_data or len(
                device_data['system-ip']) == 0:
            if viptela.params['system_ip']:
                device_data['system-ip'] = viptela.params['system_ip']
            else:
                viptela.fail_json(
                    msg='system_ip is needed when pre-attaching templates')
        if 'deviceIP' not in device_data or len(device_data['deviceIP']) == 0:
            if viptela.params['system_ip']:
                device_data['deviceIP'] = viptela.params['system_ip']
            else:
                viptela.fail_json(
                    msg='system_ip is needed when pre-attaching templates')
        if 'site-id' not in device_data or len(device_data['site-id']) == 0:
            if viptela.params['site_id']:
                device_data['site-id'] = viptela.params['site_id']
            else:
                viptela.fail_json(
                    msg='site_id is needed when pre-attaching templates')
        if 'host-name' not in device_data or len(
                device_data['host-name']) == 0:
            if viptela.params['device_name']:
                device_data['host-name'] = viptela.params['device_name']
            else:
                viptela.fail_json(
                    msg='device_name is needed when pre-attaching templates')
    elif viptela.params['device_name']:
        device_status = viptela.get_device_status(
            viptela.params['device_name'], key='host-name')
        if 'uuid' in device_status:
            device_type = 'controllers' if device_status['personality'] in [
                'vmanage', 'vbond', 'vsmart'
            ] else 'vedges'
            device_data = viptela.get_device_by_uuid(device_status['uuid'],
                                                     type=device_type)
        else:
            viptela.fail_json(msg='Cannot find device with name: {0}.'.format(
                viptela.params['device']))

    if viptela.params['state'] == 'present':
        if 'system-ip' not in device_data:
            viptela.fail_json(msg='system-ip must be defined for {0}.'.format(
                viptela.params['device']))
        if 'site-id' not in device_data:
            viptela.fail_json(msg='site-id must be defined for {0}.'.format(
                viptela.params['device']))

        # Get template data and see if it is a real template
        device_template_dict = viptela.get_device_template_dict(
            factory_default=True)
        if viptela.params['template']:
            if viptela.params['template'] not in device_template_dict:
                viptela.fail_json(msg='Template {0} not found.'.format(
                    viptela.params['template']))
            template_data = device_template_dict[viptela.params['template']]
        else:
            viptela.fail_json(msg='Must specify a template with state present')

        # Make sure they passed in the required variables
        # get_template_variables provides a variable name -> property mapping
        template_variables = viptela.get_template_variables(
            device_template_dict[viptela.params['template']]['templateId'])
        optional_template_variables = viptela.get_template_optional_variables(
            device_template_dict[viptela.params['template']]['templateId'])
        mandatory_template_variables = {
            k: template_variables[k]
            for k in set(template_variables) - set(optional_template_variables)
        }
        if mandatory_template_variables:
            if viptela.params['variables']:
                for variable in mandatory_template_variables:
                    if variable not in viptela.params['variables']:
                        viptela.fail_json(
                            msg='Template {0} requires variables: {1}'.format(
                                viptela.params['template'], ', '.join(
                                    template_variables)))

        viptela.result['template_variables'] = template_variables

        # Construct the variable payload
        device_template_variables = {
            "csv-status": "complete",
            "csv-deviceId": device_data['uuid'],
            "csv-deviceIP": device_data['deviceIP'],
            "csv-host-name": device_data['host-name'],
            '//system/host-name': device_data['host-name'],
            '//system/system-ip': device_data['system-ip'],
            '//system/site-id': device_data['site-id'],
        }

        # For each of the variables passed in, match them up with the names of the variables requires in the
        # templates and add them with the corresponding property.  The the variables is not in template_variables,
        # just leave it out since it is not required.
        for key, value in viptela.params['variables'].items():
            if key in template_variables:
                property_value = template_variables[key]
                device_template_variables[property_value] = viptela.params[
                    'variables'][key]

        # When dealing with optional parameters if we do not have explicitely set a value for it
        # we must add the optional parameter to the payload with { key: 'TEMPLATE_IGNORE'}
        for key, value in optional_template_variables.items():
            property_value = template_variables[key]
            if property_value not in device_template_variables:
                device_template_variables[property_value] = 'TEMPLATE_IGNORE'

        attached_uuid_list = viptela.get_template_attachments(
            template_data['templateId'], key='uuid')

        if device_data['uuid'] in attached_uuid_list:
            # Add the template ID to the device's variable payload because we'll need it for comparison and update.
            # device_template_variables['csv-templateId'] = template_data['templateId']
            # The device is already attached to the template.  We need to see if any of the input changed, so we make
            # an API call to get the input on last attach
            payload = {
                "templateId": template_data['templateId'],
                "deviceIds": [device_data['uuid']],
                "isEdited": "true",
                "isMasterEdited": "false"
            }
            response = viptela.request(
                '/dataservice/template/device/config/input/',
                method='POST',
                payload=payload)
            if response.json and 'data' in response.json:
                current_variables = response.json['data'][0]
                # viptela.result['old'] = current_variables
                # viptela.result['new'] = device_template_variables
                # Convert both to a string and compare.  For some reason, there can be an int/str
                # mismatch.  It might be indicative of a problem...
                for property in device_template_variables:
                    if str(device_template_variables[property]) != str(
                            current_variables[property]):
                        viptela.result['changed'] = True
        else:
            viptela.result['changed'] = True

        if not module.check_mode and viptela.result['changed']:
            payload = {
                "deviceTemplateList": [{
                    "templateId":
                    template_data['templateId'],
                    "device": [device_template_variables],
                    "isEdited":
                    False,
                    "isMasterEdited":
                    False
                }]
            }
            response = viptela.request(
                '/dataservice/template/device/config/attachfeature',
                method='POST',
                payload=payload)
            if response.json:
                action_id = response.json['id']
            else:
                viptela.fail_json(
                    msg=
                    'Did not get action ID after attaching device to template.'
                )
    elif viptela.params['state'] == 'absent':
        if 'templateId' in device_data:
            viptela.result['changed'] = True
            payload = {
                "deviceType":
                device_data['deviceType'],
                "devices": [{
                    "deviceId": device_data['uuid'],
                    "deviceIP": device_data['deviceIP']
                }]
            }
            if not module.check_mode:
                response = viptela.request(
                    '/dataservice/template/config/device/mode/cli',
                    method='POST',
                    payload=payload)
                if response.json:
                    action_id = response.json['id']
                else:
                    viptela.fail_json(
                        msg=
                        'Did not get action ID after attaching device to template.'
                    )

    elif viptela.params['state'] == 'query':
        # Get template data and see if it is a real template
        device_template_dict = viptela.get_device_template_dict(
            factory_default=True)
        if viptela.params['template']:
            if viptela.params['template'] not in device_template_dict:
                viptela.fail_json(msg='Template {0} not found.'.format(
                    viptela.params['template']))
            template_data = device_template_dict[viptela.params['template']]
        else:
            viptela.fail_json(msg='Must specify a template with state query')

        # get_template_variables provides a variable name -> property mapping
        template_variables = viptela.get_template_variables(
            device_template_dict[viptela.params['template']]['templateId'])
        optional_template_variables = viptela.get_template_optional_variables(
            device_template_dict[viptela.params['template']]['templateId'])
        viptela.result['template_variables'] = template_variables
        viptela.result[
            'optional_template_variables'] = optional_template_variables
        viptela.result['mandatory_template_variables'] = {
            k: template_variables[k]
            for k in set(template_variables) - set(optional_template_variables)
        }
    # If told, wait for the status of the request and report it
    if viptela.params['wait'] and action_id:
        viptela.waitfor_action_completion(action_id)

    viptela.logout()
    viptela.exit_json(**viptela.result)
Beispiel #12
0
def run_module():
    # define available arguments/parameters a user can pass to the module
    argument_spec = viptela_argument_spec()
    argument_spec.update(
        name=dict(type='str'),
        device_ip=dict(type='str', alias='deviceIP'),
        uuid=dict(type='str'),
        model=dict(type='str'),
    )

    # 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,
    )
    viptela = viptelaModule(module)
    viptela.result['what_changed'] = []
    viptela.result['bootstrap'] = {}
    device = {}
    uuid = None
    if viptela.params['uuid']:
        uuid = viptela.params['uuid']
        device = viptela.get_device_by_uuid(viptela.params['uuid'])
    elif viptela.params['device_ip']:
        # See if we can find the device by deviceIP
        device = viptela.get_device_by_device_ip(viptela.params['device_ip'])
        if 'uuid' in device:
            uuid = device['uuid']
    elif viptela.params['name']:
        device = viptela.get_device_by_name(viptela.params['name'])
        if 'uuid' in device:
            uuid = device['uuid']

    if uuid:
        if device['vedgeCertificateState'] in [
                'tokengenerated', 'bootstrapconfiggenerated'
        ]:
            # We can only generate bootstrap in these two states.  Otherwise, the
            # device is in-use and cannot be bootstrapped.
            viptela.result['what_changed'].append('bootstrap')
            if not module.check_mode:
                bootstrap = viptela.generate_bootstrap(uuid)
                viptela.result['uuid'] = uuid
                viptela.result['bootstrap'] = bootstrap
        # else:
        #     viptela.fail_json(msg="Could not generate bootstrap for UUID: {0}. 'vedgeCertificateState' not 'tokengenerated' or 'bootstrapconfiggenerated'".format(uuid))
    elif viptela.params['model']:
        # if no uuid was specified, just grab the first free device
        device = viptela.get_unused_device(viptela.params['model'])
        if not device:
            viptela.fail_json(msg="Could not find available device")
        viptela.result['what_changed'].append('bootstrap')
        if not module.check_mode:
            bootstrap = viptela.generate_bootstrap(device['uuid'])
            viptela.result['bootstrap'] = bootstrap
    else:
        viptela.fail_json(msg="Could not find UUID with supplied arguments")

    if viptela.result['what_changed']:
        viptela.result['changed'] = True

    viptela.exit_json(**viptela.result)
def run_module():
    # define available arguments/parameters a user can pass to the module
    argument_spec = viptela_argument_spec()
    argument_spec.update(state=dict(type='str',
                                    choices=['absent', 'present'],
                                    default='present'),
                         file=dict(type='str'),
                         aggregate=dict(type='list'))

    # 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,
    )
    viptela = viptelaModule(module)

    if viptela.params['aggregate']:
        upload_software_list = viptela.params['aggregate']
    else:
        upload_software_list = [{'file': module.params['file']}]

    # THIS MODULE IS DESIGNED TO UPLOAD UPGRADE IMAGES TO THE VMANAGE
    # Software in SD-WAN varies depending on what you want to upgrade.
    # This is a complication for what concern idempotency of this module
    # Files to upgrade vmanage will look like: vmanage-XX.YY.ZZ-<platform>.tar.gz
    # Files to upgrade vedge cloud/vedge 5k/vbond/vsmart will look like: viptela-XX.YY.ZZ-<platform>.tar.gz
    # Physical appliances will NOT have incremental upgrade images
    # CISCO Physical appliances will be upgraded via a new .bin file
    # VIPTELA Physical appliances will be upgraded via a new .tar.gz file

    viptela.result['changed'] = False

    vManage_software_list = viptela.get_software_images_list()

    if viptela.params['state'] == 'present':

        for software_to_upload in upload_software_list:

            try:
                present = False
                path_software_to_be_uploaded = software_to_upload['file']

                if not os.path.exists(path_software_to_be_uploaded):
                    module.fail_json(msg="File does not exists")

                filename_software_to_be_uploaded = os.path.basename(
                    path_software_to_be_uploaded)

                for software in vManage_software_list:
                    availabe_files_list = software["availableFiles"].split(
                        ', ')
                    if filename_software_to_be_uploaded in availabe_files_list:
                        present = True

                if not module.check_mode and not present:
                    response = viptela.request(
                        '/dataservice/device/action/software/package',
                        method='POST',
                        files={
                            'file': open(path_software_to_be_uploaded, 'rb')
                        },
                        data={
                            'validity': 'valid',
                            'upload': 'true'
                        },
                        headers=None)

                    viptela.result['changed'] = True
            except Exception as e:
                module.fail_json(msg="General Error {0}".format(e))

    else:
        # absent to be added
        pass

    viptela.exit_json(**viptela.result)