Ejemplo n.º 1
0
def main():
    ansible_module = AnsibleModule(
        argument_spec=get_argument_spec(),
        supports_check_mode=True,
        required_together=[("keepalive_src_ip", "keepalive_peer_ip")],
    )

    result = dict(changed=False)

    if ansible_module.check_mode:
        ansible_module.exit_json(**result)

    params = ansible_module.params.copy()
    state = params.pop("state")

    # NOTE: remove all values that are unspecified in playbook
    vsx_kw = {k: v for k, v in params.items() if v is not None}

    session = get_pyaoscx_session(ansible_module)

    # Get Pyaoscx device to handle switch configuration
    device = Device(session)

    vsx = device.vsx(**vsx_kw)
    result["changed"] = vsx.modified

    if state == "delete":
        vsx.delete()
        result["changed"] = not result["changed"]

    ansible_module.exit_json(**result)
Ejemplo n.º 2
0
def main():
    module_args = dict(code_point=dict(type="int",
                                       required=True,
                                       default=None,
                                       choices=[0, 1, 2, 3, 4, 5, 6, 7]),
                       color=dict(type="str",
                                  required=False,
                                  choices=["green", "yellow", "red"]),
                       description=dict(type="str", required=False),
                       local_priority=dict(type="int", required=False))

    module_args.update(aoscx_http_argument_spec)

    ansible_module = AnsibleModule(argument_spec=module_args,
                                   supports_check_mode=True)

    result = dict(changed=False)

    # Get session's serialized information
    ansible_module_session = Session(ansible_module)
    ansible_module_session_info = ansible_module_session.get_session()

    # Create pyaoscx session object
    requests_session = ansible_module_session_info["s"]
    base_url = ansible_module_session_info["url"]
    session = Pyaoscx_Session.from_session(requests_session, base_url)

    # Get playbook's arguments
    code_point = ansible_module.params["code_point"]
    color = ansible_module.params["color"]
    description = ansible_module.params["description"]
    local_priority = ansible_module.params["local_priority"]

    # Get Pyaoscx device to handle switch configuration
    device = Device(session)

    # Create QosCos object with incoming code_point
    qos_cos = device.qos_cos(code_point)

    _change_needed = False
    if color is not None:
        qos_cos.color = color
        _change_needed = True

    if description is not None:
        qos_cos.description = description
        _change_needed = True

    if local_priority is not None:
        qos_cos.local_priority = local_priority
        _change_needed = True

    if _change_needed:
        result["changed"] = qos_cos.apply()

    # Exit
    ansible_module.exit_json(**result)
Ejemplo n.º 3
0
def main():
    ansible_module = AnsibleModule(
        argument_spec=get_argument_spec(),
        supports_check_mode=True,
    )

    result = dict(changed=False)

    if ansible_module.check_mode:
        ansible_module.exit_json(**result)

    session = get_pyaoscx_session(ansible_module)

    # Get Ansible module's parameters
    name = ansible_module.params["name"]
    vsx_sync = ansible_module.params["vsx_sync"]
    state = ansible_module.params["state"]

    kwargs = {}
    if vsx_sync:
        kwargs["vsx_sync"] = vsx_sync

    q_profile = QueueProfile(session, name, **kwargs)
    try:
        q_profile.get()
        exists = True
    except Exception as exc:
        exists = False

    if state == "delete":
        device = Device(session)
        if not device.materialized:
            device.get()
        if device.q_profile_default == name:
            msg = ("Skipping, cannot delete Queue Profile, while it is set "
                   "as global.")
            result["msg"] = msg
            result["skipped"] = True
        else:
            if exists:
                q_profile.delete()
            result["changed"] = exists
    else:
        if not exists:
            result["changed"] = True
        for k, v in kwargs.items():
            if hasattr(q_profile, k):
                result["changed"] |= getattr(q_profile, k) != v
            else:
                result["changed"] = True
            setattr(q_profile, k, v)
        if not exists or result["changed"]:
            q_profile.apply()

    # Exit
    ansible_module.exit_json(**result)
Ejemplo n.º 4
0
    def device(self):
        """
        Create a Device class, to obtain common device configuration,
        capacities, capabilities, among other information related.
        :return: Device object
        """

        switch = Device(self.session)
        # Get Partial configuration attributes
        switch.get()
        return switch
Ejemplo n.º 5
0
def main():
    ansible_module = AnsibleModule(
        argument_spec=get_argument_spec(),
        supports_check_mode=True,
    )

    result = dict(changed=False)

    if ansible_module.check_mode:
        ansible_module.exit_json(**result)

    # Get playbook's arguments
    params = ansible_module.params.copy()

    code_point = params.pop("code_point")

    if code_point not in range(0, 64):
        ansible_module.fail_json(
            msg="code_point must be an integer in the [0, 63] interval, "
            "that is, an integer no lower than 0, and no higher than 63")

    session = get_pyaoscx_session(ansible_module)

    device = Device(session)

    supports_cos = device.is_capable("qos_cos_based_queueing")
    supports_dscp_cos = device.is_capable("qos_dscp_map_cos_override")

    if not supports_cos and supports_dscp_cos:
        # Unlike CLI the REST API uses 'priority_code_point' instead of 'cos',
        # so this value must be renamed
        params["priority_code_point"] = params.pop("cos", None)

    # Avoid passing None, as it could delete config
    for key in list(params):
        if params[key] is None:
            del params[key]

    qos_dscp = QosDscp(session, code_point, **params)
    qos_dscp.get()

    for key, value in params.items():
        present = getattr(qos_dscp, key)
        if present != value:
            result["changed"] = True
        setattr(qos_dscp, key, value)
    qos_dscp.apply()

    # Exit
    ansible_module.exit_json(**result)
Ejemplo n.º 6
0
def main():
    ansible_module = AnsibleModule(
        argument_spec=get_argument_spec(),
        supports_check_mode=True,
    )

    result = dict(changed=False)

    if ansible_module.check_mode:
        ansible_module.exit_json(**result)

    session = get_pyaoscx_session(ansible_module)

    # Get playbook's arguments
    name = ansible_module.params["name"]
    state = ansible_module.params["state"]
    vsx_sync = ansible_module.params["vsx_sync"]

    device = Device(session)

    schedule_profile_kw = {}
    if vsx_sync:
        schedule_profile_kw["vsx_sync"] = vsx_sync

    if state == "delete":
        if not device.materialized:
            device.get()
        if device.qos_default == name:
            msg = ("Skipping, cannot delete Schedule Profile, while it is set "
                   "as global.")
            result["msg"] = msg
            result["skipped"] = True
        else:
            sched_profile = device.qos(name)
            result["changed"] = sched_profile.was_modified()
            sched_profile.delete()
            # only report deletion if object existed before call to ansible
            result["changed"] = not result["changed"]
    else:
        sched_profile = device.qos(name, **schedule_profile_kw)
        result["changed"] = sched_profile.was_modified()

    # Exit
    ansible_module.exit_json(**result)
Ejemplo n.º 7
0
def main():
    module_args = dict(acl_name=dict(type='str', required=True),
                       acl_type=dict(type='str',
                                     required=True,
                                     choices=['ipv4', 'ipv6', 'mac']),
                       acl_interface_list=dict(type='list', required=True),
                       acl_direction=dict(type='str',
                                          default='in',
                                          choices=['in', 'out']),
                       state=dict(type='str',
                                  default='create',
                                  choices=['create', 'delete']))

    # Version management
    try:

        from ansible.module_utils.aoscx_pyaoscx import Session
        from pyaoscx.session import Session as Pyaoscx_Session
        from pyaoscx.device import Device

        USE_PYAOSCX_SDK = True

    except ImportError:
        USE_PYAOSCX_SDK = False

    # Use PYAOSCX SDK
    if USE_PYAOSCX_SDK:
        from ansible.module_utils.basic import AnsibleModule

        # ArubaModule
        ansible_module = AnsibleModule(argument_spec=module_args,
                                       supports_check_mode=True)

        # Session
        session = Session(ansible_module)

        # Set Variables
        acl_name = ansible_module.params['acl_name']
        acl_interface_list = ansible_module.params[
            'acl_interface_list']  # NOQA
        acl_type = ansible_module.params['acl_type']
        acl_direction = ansible_module.params['acl_direction']
        state = ansible_module.params['state']

        result = dict(changed=False)

        if ansible_module.check_mode:
            ansible_module.exit_json(**result)

        # Get session serialized information
        session_info = session.get_session()
        # Create pyaoscx.session object
        s = Pyaoscx_Session.from_session(session_info['s'],
                                         session_info['url'])

        # Create a Device Object
        device = Device(s)

        for interface_name in acl_interface_list:
            if state == 'delete':
                # Create ACL Object
                interface = device.interface(interface_name)
                # Delete it
                interface.clear_acl(acl_type)
                # Changed
                result['changed'] = True

            if state == 'create' or state == 'update':
                # Create ACL Object
                interface = device.interface(interface_name)
                # Verify if interface was create
                if interface.was_modified():
                    # Changed
                    result['changed'] = True

                # Modified variables
                modified_op1 = False
                modified_op2 = False
                # Update ACL inside Interface
                if acl_direction == 'in':
                    modified_op1 = interface.update_acl_in(acl_name, acl_type)
                if acl_direction == 'out':
                    modified_op2 = interface.update_acl_out(acl_name, acl_type)
                if modified_op1 or modified_op2:
                    # Changed
                    result['changed'] = True

        # Exit
        ansible_module.exit_json(**result)

    # Use Older version
    else:

        aruba_ansible_module = ArubaAnsibleModule(module_args)

        acl_name = aruba_ansible_module.module.params['acl_name']
        acl_interface_list = aruba_ansible_module.module.params[
            'acl_interface_list']  # NOQA
        acl_type = aruba_ansible_module.module.params['acl_type']
        acl_direction = aruba_ansible_module.module.params['acl_direction']
        state = aruba_ansible_module.module.params['state']

        interface = Interface()
        port = Port()

        for interface_name in acl_interface_list:
            if not port.check_port_exists(aruba_ansible_module,
                                          interface_name):
                aruba_ansible_module.module.fail_json(
                    msg="Interface {int} is not configured".format(
                        int=interface_name))

            if (state == 'create') or (state == 'update'):
                update_type = 'insert'
            elif (state == 'delete'):
                update_type = 'delete'
            aruba_ansible_module = interface.update_interface_acl_details(
                aruba_ansible_module, interface_name, acl_name, acl_type,
                acl_direction, update_type)

            if update_type == 'insert':
                aruba_ansible_module.module.log(
                    msg="Attached ACL {acl} of type "
                    "{type} to interface {int}"
                    "".format(acl=acl_name, type=acl_type, int=interface_name))

            if update_type == 'update':
                aruba_ansible_module.module.log(
                    msg="Updated ACL {acl} of type "
                    "{type} attached to interface"
                    " {int}"
                    "".format(acl=acl_name, type=acl_type,
                              int=interface_name))  # NOQA

            if (update_type == 'absent') or (update_type == 'delete'):
                aruba_ansible_module.module.log(
                    msg="Removed ACL {acl} of type"
                    " {type} from interface"
                    " {int}"
                    "".format(acl=acl_name, type=acl_type, int=interface_name))

        aruba_ansible_module.update_switch_config()
Ejemplo n.º 8
0
def main():
    module_args = dict(vlan_id=dict(type='int', required=True),
                       name=dict(type='str', default=None),
                       description=dict(type='str', default=None),
                       admin_state=dict(type='str',
                                        default=None,
                                        choices=['up', 'down']),
                       state=dict(type='str',
                                  default='create',
                                  choices=['create', 'delete', 'update']))

    # Version management
    try:

        from ansible.module_utils.aoscx_pyaoscx import Session
        from pyaoscx.session import Session as Pyaoscx_Session
        from pyaoscx.device import Device

        USE_PYAOSCX_SDK = True

    except ImportError:
        USE_PYAOSCX_SDK = False

    # Use PYAOSCX SDK
    if USE_PYAOSCX_SDK:
        from ansible.module_utils.basic import AnsibleModule

        # ArubaModule
        ansible_module = AnsibleModule(argument_spec=module_args,
                                       supports_check_mode=True)

        # Session
        session = Session(ansible_module)

        # Set Variables
        vlan_id = ansible_module.params['vlan_id']
        vlan_name = ansible_module.params['name']
        if vlan_name is None:
            vlan_name = "VLAN{vlan_id}".format(vlan_id=vlan_id)
        description = ansible_module.params['description']
        admin_state = ansible_module.params['admin_state']
        state = ansible_module.params['state']

        result = dict(changed=False)

        if ansible_module.check_mode:
            ansible_module.exit_json(**result)

        # Get session serialized information
        session_info = session.get_session()
        # Create pyaoscx.session object
        s = Pyaoscx_Session.from_session(session_info['s'],
                                         session_info['url'])

        # Create a Device Object
        device = Device(s)

        if state == 'delete':
            # Create Vlan Object
            vlan = device.vlan(vlan_id)
            # Delete it
            vlan.delete()
            # Changed
            result['changed'] = True

        elif state == 'update' or state == 'create':
            # Create Vlan with incoming attributes, in case VLAN does not exist
            # inside device
            vlan = device.vlan(vlan_id, vlan_name, description, "static",
                               admin_state)

            if vlan.was_modified():
                # Changed
                result['changed'] = True

        # Exit
        ansible_module.exit_json(**result)

    # Use Older version
    else:

        aruba_ansible_module = ArubaAnsibleModule(module_args=module_args)

        vlan_id = aruba_ansible_module.module.params['vlan_id']
        vlan_name = aruba_ansible_module.module.params['name']
        description = aruba_ansible_module.module.params['description']
        admin_state = aruba_ansible_module.module.params['admin_state']
        state = aruba_ansible_module.module.params['state']

        vlan = VLAN()

        if state == 'delete':
            aruba_ansible_module = vlan.delete_vlan(aruba_ansible_module,
                                                    vlan_id)

        if state == 'create':
            aruba_ansible_module = vlan.create_vlan(aruba_ansible_module,
                                                    vlan_id)

            if vlan_name is not None:
                name = vlan_name
            else:
                name = "VLAN " + str(vlan_id)

            if admin_state is None:
                admin_state = 'up'

            vlan_fields = {
                "name": name,
                "admin": admin_state,
                "type": "static"
            }
            if description is not None:
                vlan_fields["description"] = description
            aruba_ansible_module = vlan.update_vlan_fields(
                aruba_ansible_module,
                vlan_id,
                vlan_fields,
                update_type='insert')

        if state == 'update':
            vlan_fields = {}
            if admin_state is not None:
                vlan_fields['admin'] = admin_state

            if description is not None:
                vlan_fields['description'] = description

            if state is not None:
                vlan_fields['state'] = state

            aruba_ansible_module = vlan.update_vlan_fields(
                aruba_ansible_module,
                vlan_id,
                vlan_fields,
                update_type='update')

        aruba_ansible_module.update_switch_config()
Ejemplo n.º 9
0
def main():
    module_args = dict(
        vlan_id=dict(type='str', required=True),
        admin_state=dict(type='str', required=False, choices=['up', 'down']),
        state=dict(default='create', choices=['create', 'delete', 'update']),
        ipv4=dict(type='list', default=None),
        description=dict(type='str', default=None),
        ipv6=dict(type='list', default=None),
        vrf=dict(type='str', default=None),
        ip_helper_address=dict(type='list', default=None),
        active_gateway_ip=dict(type='str', default=None),
        active_gateway_mac_v4=dict(type='str', default=None),
    )

    # Version management
    try:
        from ansible.module_utils.aoscx_pyaoscx import Session
        from pyaoscx.session import Session as Pyaoscx_Session
        from pyaoscx.device import Device

        USE_PYAOSCX_SDK = True

    except ImportError:

        USE_PYAOSCX_SDK = False

    if USE_PYAOSCX_SDK:
        from ansible.module_utils.basic import AnsibleModule

        # ArubaModule
        ansible_module = AnsibleModule(argument_spec=module_args,
                                       supports_check_mode=True)

        vlan_id = ansible_module.params['vlan_id']
        admin_state = ansible_module.params['admin_state']
        ipv4 = ansible_module.params['ipv4']
        ipv6 = ansible_module.params['ipv6']
        vrf = ansible_module.params['vrf']
        description = ansible_module.params['description']
        ip_helper_address = ansible_module.params['ip_helper_address']  # NOQA
        active_gateway_ip = ansible_module.params['active_gateway_ip']
        active_gateway_mac_v4 = ansible_module.params['active_gateway_mac_v4']
        state = ansible_module.params['state']

        # Set IP variable as empty arrays
        if ipv4 == ['']:
            ipv4 = []
        if ipv6 == ['']:
            ipv6 = []

        # Session
        session = Session(ansible_module)

        # Set variables
        vlan_interface_id = "vlan" + vlan_id
        if admin_state is None:
            admin_state = 'up'
        if vrf is not None:
            vrf_name = vrf
        else:
            vrf_name = "default"

        # Set result var
        result = dict(changed=False)

        if ansible_module.check_mode:
            ansible_module.exit_json(**result)

        # Get session serialized information
        session_info = session.get_session()
        # Create pyaoscx.session object
        s = Pyaoscx_Session.from_session(session_info['s'],
                                         session_info['url'])

        # Create a Device Object
        device = Device(s)

        if state == 'delete':
            # Create Interface Object
            vlan_interface = device.interface(vlan_interface_id)
            # Delete it
            vlan_interface.delete()
            # Changed
            result['changed'] = True

        if state == 'create' or state == 'update':
            # Create Interface with incoming attributes
            vlan_interface = device.interface(vlan_interface_id)
            # Verify if interface was create
            if vlan_interface.was_modified():
                # Changed
                result['changed'] = True

            # Configure SVI
            # Verify if object was changed
            modified_op = vlan_interface.configure_svi(vlan=int(vlan_id),
                                                       ipv4=ipv4,
                                                       ipv6=ipv6,
                                                       vrf=vrf,
                                                       description=description,
                                                       user_config=admin_state)

            if active_gateway_ip is not None and active_gateway_mac_v4 is not None:
                modified_op2 = vlan_interface.set_active_gateaway(
                    active_gateway_ip, active_gateway_mac_v4)
                modified_op = modified_op2 or modified_op

            if ip_helper_address is not None:
                # Create DHCP_Relay object
                dhcp_relay = device.dhcp_relay(vrf=vrf, port=vlan_interface_id)
                # Add helper addresses
                modified_dhcp_relay = dhcp_relay.add_ipv4_addresses(
                    ip_helper_address)
                modified_op = modified_op or modified_dhcp_relay

            if modified_op:
                # Changed
                result['changed'] = True

        # Exit
        ansible_module.exit_json(**result)

    # Use Older version
    else:
        aruba_ansible_module = ArubaAnsibleModule(module_args)

        vlan_id = aruba_ansible_module.module.params['vlan_id']
        admin_state = aruba_ansible_module.module.params['admin_state']
        ipv4 = aruba_ansible_module.module.params['ipv4']
        ipv6 = aruba_ansible_module.module.params['ipv6']
        vrf = aruba_ansible_module.module.params['vrf']
        description = aruba_ansible_module.module.params['description']
        ip_helper_address = aruba_ansible_module.module.params[
            'ip_helper_address']
        active_gateway_ip = aruba_ansible_module.module.params[
            'active_gateway_ip']
        active_gateway_mac_v4 = aruba_ansible_module.module.params[
            'active_gateway_mac_v4']  # NOQA
        state = aruba_ansible_module.module.params['state']

        vlan = VLAN()
        port = Port()
        interface = Interface()
        vlan_interface_id = "vlan" + vlan_id
        if not vlan.check_vlan_exist(aruba_ansible_module, vlan_id):
            aruba_ansible_module.module.fail_json(
                msg="VLAN {id} does not exist. "
                "VLAN needs to be created "
                "before adding or deleting "
                "interfaces"
                "".format(id=vlan_id))

        if state == 'create':
            aruba_ansible_module = port.create_port(aruba_ansible_module,
                                                    vlan_interface_id)
            aruba_ansible_module = interface.create_interface(
                aruba_ansible_module, vlan_interface_id, type='vlan')

            if admin_state is None:
                admin_state = 'up'

            user_config = {
                "admin": admin_state,
            }

            interface_fields = {
                "name": vlan_interface_id,
                "type": "vlan",
                "user_config": user_config
            }
            aruba_ansible_module = interface.update_interface_fields(
                aruba_ansible_module, vlan_interface_id,
                interface_fields)  # NOQA

            if vrf is not None:
                vrf_name = vrf
            else:
                vrf_name = "default"

            port_fields = {
                "interfaces": [vlan_interface_id],
                "vlan_tag": vlan_id,
                "vrf": vrf_name,
                "admin": admin_state
            }
            aruba_ansible_module = port.update_port_fields(
                aruba_ansible_module, vlan_interface_id, port_fields)

        if (state == 'create') or (state == 'update'):

            if not port.check_port_exists(aruba_ansible_module,
                                          vlan_interface_id):
                aruba_ansible_module.module.fail_json(
                    msg="VLAN interface does not"
                    " exist")

            if admin_state is not None:
                port_fields = {"admin": admin_state}
                user_config = {"admin": admin_state}
                interface_fields = {"user_config": user_config}

            aruba_ansible_module = port.update_port_fields(
                aruba_ansible_module, vlan_interface_id, port_fields)
            aruba_ansible_module = interface.update_interface_fields(
                aruba_ansible_module, vlan_interface_id,
                interface_fields)  # NOQA

            if description is not None:
                port_fields = {"description": description}

                aruba_ansible_module = port.update_port_fields(
                    aruba_ansible_module, vlan_interface_id,
                    port_fields)  # NOQA

            if ipv4 is not None:
                l3_interface = L3_Interface()
                aruba_ansible_module = l3_interface.update_interface_ipv4_address(
                    aruba_ansible_module, vlan_interface_id, ipv4)  # NOQA

            if ipv6 is not None:
                l3_interface = L3_Interface()
                aruba_ansible_module = l3_interface.update_interface_ipv6_address(
                    aruba_ansible_module, vlan_interface_id, ipv6)  # NOQA

            if ip_helper_address is not None:
                l3_interface = L3_Interface()
                if vrf is None:
                    vrf = "default"
                aruba_ansible_module = l3_interface.update_interface_ip_helper_address(
                    aruba_ansible_module, vrf, vlan_interface_id,
                    ip_helper_address)  # NOQA

            if vrf is not None:
                l3_interface = L3_Interface()
                aruba_ansible_module = l3_interface.update_interface_vrf_details_from_l3(
                    aruba_ansible_module,
                    vrf,
                    vlan_interface_id,
                    update_type="insert")  # NOQA

            if (active_gateway_ip
                    is not None) and (active_gateway_mac_v4 is None):
                aruba_ansible_module.module.fail_json(
                    msg=
                    " Both active_gateway_ip and active_gateway_mac_v4 are required for configure active gateway."
                )  # NOQA
            elif (active_gateway_ip is None) and (active_gateway_mac_v4
                                                  is not None):  # NOQA
                aruba_ansible_module.module.fail_json(
                    msg=
                    " Both active_gateway_ip and active_gateway_mac_v4 are required for configure active gateway."
                )  # NOQA
            elif (active_gateway_ip is not None) and (active_gateway_mac_v4
                                                      is not None):  # NOQA
                port_fields = {
                    "vsx_virtual_ip4": active_gateway_ip,
                    "vsx_virtual_gw_mac_v4": active_gateway_mac_v4
                }
                aruba_ansible_module = port.update_port_fields(
                    aruba_ansible_module, vlan_interface_id,
                    port_fields)  # NOQA

        if state == 'delete':
            aruba_ansible_module = port.delete_port(aruba_ansible_module,
                                                    vlan_interface_id)
            aruba_ansible_module = interface.delete_interface(
                aruba_ansible_module, vlan_interface_id, type='vlan')

        aruba_ansible_module.update_switch_config()
Ejemplo n.º 10
0
def main():
    module_args = dict(
        partition_name=dict(type='str', default='primary',
                            choices=['primary', 'secondary']),
    )

    # Version management
    try:

        from ansible.module_utils.aoscx_pyaoscx import Session
        from pyaoscx.session import Session as Pyaoscx_Session
        from pyaoscx.device import Device

        USE_PYAOSCX_SDK = True

    except ImportError:
        USE_PYAOSCX_SDK = False

    # Use PYAOSCX SDK
    if USE_PYAOSCX_SDK:
        from ansible.module_utils.basic import AnsibleModule

        # ArubaModule
        ansible_module = AnsibleModule(
            argument_spec=module_args,
            supports_check_mode=True)

        # Session
        session = Session(ansible_module)

        # Set Variables
        partition_name = ansible_module.params['partition_name']

        result = dict(
            changed=False
        )

        if ansible_module.check_mode:
            ansible_module.exit_json(**result)

        # Get session serialized information
        session_info = session.get_session()
        # Create pyaoscx.session object
        s = Pyaoscx_Session.from_session(
            session_info['s'], session_info['url'])

        # Create a Device Object
        device = Device(s)

        success = device.boot_firmware(partition_name)

        # Changed
        result['changed'] = success

        # Exit
        ansible_module.exit_json(**result)

    # Use Older version
    else:

        aruba_ansible_module = ArubaAnsibleModule(
            module_args=module_args, store_config=False)
        partition_name = aruba_ansible_module.module.params['partition_name']

        url = '/rest/v1/boot?image={part}'.format(part=partition_name)
        post(aruba_ansible_module.module, url)

        result = dict(changed=aruba_ansible_module.changed,
                      warnings=aruba_ansible_module.warnings)
        result["changed"] = True
        aruba_ansible_module.module.exit_json(**result)
Ejemplo n.º 11
0
def main():
    module_args = dict(acl_name=dict(type='str', required=True),
                       acl_type=dict(type='str',
                                     required=True,
                                     choices=['ipv4', 'ipv6', 'mac']),
                       acl_vlan_list=dict(type='list', required=True),
                       acl_direction=dict(type='str',
                                          default='in',
                                          choices=['in', 'out']),
                       state=dict(type='str',
                                  default='create',
                                  choices=['create', 'delete']))

    # Version management
    try:

        from ansible.module_utils.aoscx_pyaoscx import Session
        from pyaoscx.session import Session as Pyaoscx_Session
        from pyaoscx.device import Device

        USE_PYAOSCX_SDK = True

    except ImportError:
        USE_PYAOSCX_SDK = False

    # Use PYAOSCX SDK
    if USE_PYAOSCX_SDK:
        from ansible.module_utils.basic import AnsibleModule

        # ArubaModule
        ansible_module = AnsibleModule(argument_spec=module_args,
                                       supports_check_mode=True)

        # Session
        session = Session(ansible_module)

        # Set Variables
        acl_name = ansible_module.params['acl_name']
        acl_vlan_list = ansible_module.params['acl_vlan_list']  # NOQA
        acl_type = ansible_module.params['acl_type']
        acl_direction = ansible_module.params['acl_direction']
        state = ansible_module.params['state']

        result = dict(changed=False)

        if ansible_module.check_mode:
            ansible_module.exit_json(**result)

        # Get session serialized information
        session_info = session.get_session()
        # Create pyaoscx.session object
        s = Pyaoscx_Session.from_session(session_info['s'],
                                         session_info['url'])

        # Create a Device Object
        device = Device(s)

        for vlan_name in acl_vlan_list:
            if state == 'delete':
                # Create VLAN Object
                vlan = device.vlan(vlan_name)
                # Delete acl
                if acl_direction == 'in':
                    vlan.detach_acl_in(acl_name, acl_type)
                if acl_direction == 'out':
                    vlan.detach_acl_out(acl_name, acl_type)
                # Changed
                result['changed'] = True

            if state == 'create' or state == 'update':
                # Create VLAN Object
                vlan = device.vlan(vlan_name)
                # Verify if interface was create
                if vlan.was_modified():
                    # Changed
                    result['changed'] = True
                # Set variables
                modified_op1 = False
                modified_op2 = False
                # Update ACL inside VLAN
                if acl_direction == 'in':
                    modified_op1 = vlan.attach_acl_in(acl_name, acl_type)
                if acl_direction == 'out':
                    modified_op2 = vlan.attach_acl_out(acl_name, acl_type)
                if modified_op1 or modified_op2:
                    # Changed
                    result['changed'] = True

        # Exit
        ansible_module.exit_json(**result)

    # Use Older version
    else:

        aruba_ansible_module = ArubaAnsibleModule(module_args)

        acl_name = aruba_ansible_module.module.params['acl_name']
        acl_vlan_list = aruba_ansible_module.module.params['acl_vlan_list']
        acl_type = aruba_ansible_module.module.params['acl_type']
        acl_direction = aruba_ansible_module.module.params['acl_direction']
        state = aruba_ansible_module.module.params['state']

        acl_type_prefix = ""
        if acl_type == "ipv4":
            acl_type_prefix = "aclv4"
        elif acl_type == "ipv6":
            acl_type_prefix = "aclv6"
        elif acl_type == "mac":
            acl_type_prefix = "aclmac"

        vlan = VLAN()

        for vlan_id in acl_vlan_list:
            field1 = '{type}_{dir}_cfg'.format(type=acl_type_prefix,
                                               dir=acl_direction)
            value1 = '{name}/{type}'.format(name=acl_name, type=acl_type)
            field2 = '{type}_{dir}_cfg_version'.format(type=acl_type_prefix,
                                                       dir=acl_direction)
            value2 = randint(-900719925474099, 900719925474099)

            vlan_fields = {field1: value1, field2: value2}

            if (state == 'create') or (state == 'update'):

                existing_values = vlan.get_vlan_fields_values(
                    aruba_ansible_module, vlan_id, [field1])

                if field1 in existing_values.keys():
                    if existing_values[field1] != vlan_fields[field1]:
                        aruba_ansible_module = vlan.update_vlan_fields(
                            aruba_ansible_module,
                            vlan_id,
                            vlan_fields,
                            update_type='insert')  # NOQA
                else:
                    aruba_ansible_module = vlan.update_vlan_fields(
                        aruba_ansible_module,
                        vlan_id,
                        vlan_fields,
                        update_type='insert')  # NOQA

                if state == 'create':
                    aruba_ansible_module.module.log(
                        msg=" Inserted ACL {name} of "
                        "type {type} to VLAN {id}"
                        "".format(name=acl_name, type=acl_type,
                                  id=vlan_id))  # NOQA

                if state == 'update':
                    aruba_ansible_module.module.log(
                        msg=" Updated  ACL {name} of "
                        "type {type} to VLAN {id}"
                        "".format(name=acl_name, type=acl_type,
                                  id=vlan_id))  # NOQA
            elif state == 'delete':
                aruba_ansible_module = vlan.update_vlan_fields(
                    aruba_ansible_module,
                    vlan_id,
                    vlan_fields,
                    update_type='delete')  # NOQA
                aruba_ansible_module.module.log(
                    msg="Deleted ACL {name} of type "
                    "{type} from VLAN {id}"
                    "".format(name=acl_name, type=acl_type,
                              id=vlan_id))  # NOQA

        aruba_ansible_module.update_switch_config()
Ejemplo n.º 12
0
def main():
    """
    Main entry point for module execution
    :returns: ansible_facts
    """
    argument_spec = {
        'gather_subset':
        dict(default=[
            'software_info', 'software_images', 'host_name', 'platform_name',
            'management_interface', 'software_version', 'fans',
            'power_supplies', 'product_info', 'physical_interfaces',
            'resource_utilization', 'domain_name'
        ],
             type='list',
             choices=[
                 'software_info', 'software_images', 'host_name',
                 'platform_name', 'management_interface', 'software_version',
                 'config', 'fans', 'power_supplies', 'product_info',
                 'physical_interfaces', 'resource_utilization', 'domain_name'
             ]),
        'gather_network_resources':
        dict(type='list', choices=['interfaces', 'vlans', 'vrfs'])
    }

    # Version Management
    try:

        from ansible.module_utils.aoscx_pyaoscx import Session
        from pyaoscx.session import Session as Pyaoscx_Session
        from pyaoscx.interface import Interface
        from pyaoscx.vlan import Vlan
        from pyaoscx.device import Device
        from pyaoscx.vrf import Vrf

        USE_PYAOSCX_SDK = True

    except ImportError:
        USE_PYAOSCX_SDK = False

    # Use the PYAOSCX SDK
    if USE_PYAOSCX_SDK:

        argument_spec.update(aoscx_http_argument_spec)

        ansible_module = AnsibleModule(argument_spec=argument_spec,
                                       supports_check_mode=True)

        # Get session
        session = Session(ansible_module)

        # Session info
        session_info = session.get_session()

        # Create pyaoscx session object
        s = Pyaoscx_Session.from_session(session_info['s'],
                                         session_info['url'])

        warnings = []
        if ansible_module.params["gather_subset"] == "!config":
            warnings.append(
                'default value for `gather_subset` will be changed '
                'to `min` from `!config` v2.11 onwards')

        # Declare the Ansible facts
        ansible_facts = {}

        # Retrieve variables from module parameters
        network_resource_list = ansible_module.params[
            'gather_network_resources']
        subset_list = ansible_module.params['gather_subset']

        # Retrieve ansible_network_resources
        ansible_network_resources = {}
        if network_resource_list is not None:
            for resource in network_resource_list:
                if resource == 'interfaces':
                    ansible_network_resources.update(
                        {'interfaces': Interface.get_facts(s)})
                elif resource == 'vlans':
                    ansible_network_resources.update(
                        {'vlans': Vlan.get_facts(s)})
                elif resource == 'vrfs':
                    ansible_network_resources.update(
                        {'vrfs': Vrf.get_facts(s)})

        ansible_facts.update(
            {'ansible_network_resources': ansible_network_resources})

        # Retrieve ansible_net_gather_network_resources
        ansible_facts.update(
            {'ansible_net_gather_network_resources': network_resource_list})

        # Retrieve ansible_net_gather_subset
        ansible_facts.update({'ansible_net_gather_subset': subset_list})

        # Retrieve device facts
        switch = Device(s)
        switch.get()
        switch.get_subsystems()  # subsystem

        # Set the subsystem attributes allowed to retrieve as facts
        allowed_subsystem_attributes = [
            'product_info', 'power_supplies', 'interfaces', 'fans',
            'resource_utilization'
        ]

        # Set the default subsets that are always retreived as facts
        default_subset_list = ['management_interface', 'software_version']

        # Extend subset_list with default subsets
        subset_list.extend(default_subset_list)

        # Delete duplicates
        subset_list = list(dict.fromkeys(subset_list))

        # Iterate through given subset arguments in the gather_subset parameter
        # in argument_spec
        for subset in subset_list:

            # Argument translation for management_interface and
            # physical_interfaces
            if subset == 'management_interface':
                subset = 'mgmt_intf_status'
            elif subset == 'physical_interfaces':
                subset = 'interfaces'
            elif subset == 'host_name':
                subset = 'hostname'

            str_subset = 'ansible_net_' + subset

            # Check if current subset is inside the Device object
            if hasattr(switch, subset):

                # Get attribute value and add it to Ansible facts dictionary
                ansible_facts[str_subset] = getattr(switch, subset)

            # Check if current subset is inside the allowed subsystem
            # attributes
            elif subset in allowed_subsystem_attributes:
                ansible_facts.update({str_subset: {}})

                # Iterate through Device subsystems
                for subsystem, value in switch.subsystems.items():

                    # Get attribute value and update the Ansible facts
                    # dictionary
                    ansible_facts[str_subset].update(
                        {subsystem: switch.subsystems[subsystem][subset]})

        ansible_module.exit_json(ansible_facts=ansible_facts,
                                 warnings=warnings)

    # USE OLD VERSION
    else:
        argument_spec.update(aoscx_http_argument_spec)

        module = AnsibleModule(argument_spec=argument_spec,
                               supports_check_mode=True)

        module._connection = get_connection(module)  # noqa

        warnings = []
        if module.params["gather_subset"] == "!config":
            warnings.append(
                'default value for `gather_subset` will be changed '
                'to `min` from `!config` v2.11 onwards')

        result = Facts(module).get_facts()

        ansible_facts, additional_warnings = result
        warnings.extend(additional_warnings)

        module.exit_json(ansible_facts=ansible_facts, warnings=warnings)
Ejemplo n.º 13
0
def main():
    module_args = dict(interface=dict(type='str', required=True),
                       description=dict(type='str', default=None),
                       ipv4=dict(type='list', default=None),
                       ipv6=dict(type='list', default=None),
                       interface_qos_schedule_profile=dict(type='dict',
                                                           default=None),
                       interface_qos_rate=dict(type='dict', default=None),
                       vrf=dict(type='str', default=None),
                       ip_helper_address=dict(type='list', default=None),
                       state=dict(default='create',
                                  choices=['create', 'delete', 'update']))

    if USE_PYAOSCX_SDK:
        ansible_module = AnsibleModule(argument_spec=module_args,
                                       supports_check_mode=True)

        interface_name = ansible_module.params['interface']
        description = ansible_module.params['description']
        ipv4 = ansible_module.params['ipv4']
        ipv6 = ansible_module.params['ipv6']
        vrf = ansible_module.params['vrf']
        ip_helper_addresses = ansible_module.params['ip_helper_address']
        state = ansible_module.params['state']

        # Set IP variable as empty arrays
        if ipv4 == ['']:
            ipv4 = []
        if ipv6 == ['']:
            ipv6 = []

        # Set Variables
        if vrf is None:
            vrf = 'default'

        # Set result var
        result = dict(changed=False)

        if ansible_module.check_mode:
            ansible_module.exit_json(**result)

        session = get_pyaoscx_session(ansible_module)
        device = Device(session)
        if state == 'delete':
            # Create Interface Object
            interface = device.interface(interface_name)
            # Delete it
            interface.delete()

            # Changed
            result['changed'] = True
        else:
            # Create Interface Object
            interface = device.interface(interface_name)
            # Verify if interface was create
            if interface.was_modified():
                # Changed
                result['changed'] = True
            # Configure L4
            # Verify if object was changed
            modified_op = interface.configure_l3(ipv4=ipv4,
                                                 ipv6=ipv6,
                                                 vrf=vrf,
                                                 description=description)

            if ip_helper_addresses is not None:
                # Create DHCP_Relay object
                dhcp_relay = device.dhcp_relay(vrf=vrf, port=interface_name)
                # Add helper addresses
                dhcp_relay.add_ipv4_addresses(ip_helper_addresses)

            if modified_op:
                # Changed
                result['changed'] = True

        # Exit
        ansible_module.exit_json(**result)

    # Use Older version
    else:

        aruba_ansible_module = ArubaAnsibleModule(module_args)

        interface_name = aruba_ansible_module.module.params['interface']
        admin_state = aruba_ansible_module.module.params['admin_state']
        description = aruba_ansible_module.module.params['description']
        ipv4 = aruba_ansible_module.module.params['ipv4']
        ipv6 = aruba_ansible_module.module.params['ipv6']
        interface_qos_rate = aruba_ansible_module.module.params[
            'interface_qos_rate']  # NOQA
        interface_qos_schedule_profile = aruba_ansible_module.module.params[
            'interface_qos_schedule_profile']
        vrf = aruba_ansible_module.module.params['vrf']
        ip_helper_address = aruba_ansible_module.module.params[
            'ip_helper_address']

        state = aruba_ansible_module.module.params['state']

        l3_interface = L3_Interface()
        interface = Interface()
        if state == 'create':
            aruba_ansible_module = l3_interface.create_l3_interface(
                aruba_ansible_module, interface_name)  # NOQA
            if vrf is None:
                vrf = "default"

            if vrf is not None:
                aruba_ansible_module = l3_interface.update_interface_vrf_details_from_l3(
                    aruba_ansible_module, vrf, interface_name)  # NOQA

        if state == 'delete':
            aruba_ansible_module = l3_interface.delete_l3_interface(
                aruba_ansible_module, interface_name)

        if (state == 'update') or (state == 'create'):

            if admin_state is not None:
                aruba_ansible_module = interface.update_interface_admin_state(
                    aruba_ansible_module, interface_name, admin_state)

            if description is not None:
                aruba_ansible_module = interface.update_interface_description(
                    aruba_ansible_module, interface_name, description)

            if vrf is not None and vrf != "default":
                aruba_ansible_module = l3_interface.update_interface_vrf_details_from_l3(
                    aruba_ansible_module, vrf, interface_name)  # NOQA

            if interface_qos_rate is not None:
                aruba_ansible_module = l3_interface.update_interface_qos_rate(
                    aruba_ansible_module, interface_name, interface_qos_rate)

            if interface_qos_schedule_profile is not None:
                aruba_ansible_module = l3_interface.update_interface_qos_profile(
                    aruba_ansible_module, interface_name,
                    interface_qos_schedule_profile)  # NOQA

            if ipv4 is not None:
                aruba_ansible_module = l3_interface.update_interface_ipv4_address(
                    aruba_ansible_module, interface_name, ipv4)  # NOQA

            if ipv6 is not None:
                aruba_ansible_module = l3_interface.update_interface_ipv6_address(
                    aruba_ansible_module, interface_name, ipv6)  # NOQA

            if ip_helper_address is not None:
                if vrf is not None:
                    vrf = 'default'
                aruba_ansible_module = l3_interface.update_interface_ip_helper_address(
                    aruba_ansible_module, vrf, interface_name,
                    ip_helper_address)  # NOQA

        aruba_ansible_module.update_switch_config()
Ejemplo n.º 14
0
def main():
    module_args = dict(name=dict(type='str', required=True),
                       type=dict(type='str',
                                 required=True,
                                 choices=['ipv4', 'ipv6', 'mac']),
                       acl_entries=dict(type='dict', default=None),
                       state=dict(type='str',
                                  default='create',
                                  choices=['create', 'delete', 'update']))

    # Version management
    try:

        from ansible.module_utils.aoscx_pyaoscx import Session
        from pyaoscx.session import Session as Pyaoscx_Session
        from pyaoscx.acl_entry import AclEntry
        from pyaoscx.device import Device

        USE_PYAOSCX_SDK = True

    except ImportError:
        USE_PYAOSCX_SDK = False

    # Use PYAOSCX SDK
    if USE_PYAOSCX_SDK:
        from ansible.module_utils.basic import AnsibleModule

        # ArubaModule
        ansible_module = AnsibleModule(argument_spec=module_args,
                                       supports_check_mode=True)

        # Session
        session = Session(ansible_module)

        # Set Variables
        state = ansible_module.params['state']
        name = ansible_module.params['name']
        list_type = ansible_module.params['type']
        acl_entries = ansible_module.params['acl_entries']

        result = dict(changed=False)

        if ansible_module.check_mode:
            ansible_module.exit_json(**result)

        # Get session serialized information
        session_info = session.get_session()
        # Create pyaoscx.session object
        s = Pyaoscx_Session.from_session(session_info['s'],
                                         session_info['url'])

        device = Device(s)
        if state == 'delete':
            # Create ACL Object
            acl = device.acl(name, list_type)
            # Delete it
            acl.delete()
            # Changed
            result['changed'] = True

        if state == 'create' or state == 'update':
            # Create ACL Object
            acl = device.acl(name, list_type)
            # Verify if interface was create
            if acl.was_modified():
                # Changed
                result['changed'] = True

            # Modified variable
            modified_op = False

            if acl_entries is not None:
                for sequence_number, config in acl_entries.items():
                    acl_entry = AclEntry(acl.session,
                                         sequence_number=int(sequence_number),
                                         parent_acl=acl,
                                         **_remove_invalid_addresses(config))
                    modified_op |= acl_entry.apply()

            # Changed
            if modified_op:
                result['changed'] = True

        # Exit
        ansible_module.exit_json(**result)

    # Use Older version
    else:

        aruba_ansible_module = ArubaAnsibleModule(module_args=module_args)
        acl = ACL()
        state = aruba_ansible_module.module.params['state']
        name = aruba_ansible_module.module.params['name']
        list_type = aruba_ansible_module.module.params['type']
        acl_entries = aruba_ansible_module.module.params['acl_entries']

        if (state == 'create') or (state == 'update'):
            aruba_ansible_module = acl.create_acl(aruba_ansible_module, name,
                                                  list_type)
            if acl_entries is not None:
                for sequence_number in acl_entries.keys():
                    acl_entry = acl_entries[sequence_number]
                    if 'protocol' in acl_entry.keys():
                        translated_protocol_name = translate_acl_entries_protocol(
                            acl_entry['protocol'])
                        if (translated_protocol_name is not None) and (
                                translated_protocol_name != ""):
                            acl_entry['protocol'] = translated_protocol_name
                        elif (translated_protocol_name
                              is not None) and (translated_protocol_name
                                                == ""):
                            acl_entry.pop('protocol')

                    if 'count' in acl_entry.keys():
                        if acl_entry['count'] is False:
                            acl_entry.pop('count')

                    acl_entries[sequence_number] = acl_entry
                for sequence_number in acl_entries.keys():
                    aruba_ansible_module = acl.update_acl_entry(
                        aruba_ansible_module,
                        name,
                        list_type,
                        sequence_number,
                        acl_entries[sequence_number],
                        update_type='insert')

        if state == 'delete':
            aruba_ansible_module = acl.delete_acl(aruba_ansible_module, name,
                                                  list_type)

        aruba_ansible_module.update_switch_config()
Ejemplo n.º 15
0
def main():
    module_args = dict(vrf_name=dict(type='str',
                                     required=False,
                                     default='default'),
                       destination_address_prefix=dict(type='str',
                                                       required=True),
                       type=dict(type='str',
                                 default='forward',
                                 choices=['forward', 'blackhole', 'reject']),
                       distance=dict(type='int', default=1),
                       next_hop_interface=dict(type='str', default=None),
                       next_hop_ip_address=dict(type='str', default=None),
                       state=dict(default='create',
                                  choices=['create', 'delete']))

    # Version management
    try:
        from ansible.module_utils.aoscx_pyaoscx import Session
        from pyaoscx.session import Session as Pyaoscx_Session
        from pyaoscx.device import Device

        USE_PYAOSCX_SDK = True

    except ImportError:

        USE_PYAOSCX_SDK = False

    if USE_PYAOSCX_SDK:

        from ansible.module_utils.basic import AnsibleModule
        # ArubaModule
        ansible_module = AnsibleModule(argument_spec=module_args,
                                       supports_check_mode=True)

        vrf_name = ansible_module.params['vrf_name']
        prefix = ansible_module.params['destination_address_prefix']
        route_type = ansible_module.params['type']
        distance = ansible_module.params['distance']
        next_hop_interface = ansible_module.params['next_hop_interface']
        next_hop_ip_address = ansible_module.params['next_hop_ip_address']
        state = ansible_module.params['state']

        # Session
        session = Session(ansible_module)

        # Set result var
        result = dict(changed=False)

        if ansible_module.check_mode:
            ansible_module.exit_json(**result)

        # Get session serialized information
        session_info = session.get_session()
        # Create pyaoscx.session object
        s = Pyaoscx_Session.from_session(session_info['s'],
                                         session_info['url'])

        # Create a Device Object
        device = Device(s)

        if state == 'delete':
            # Create Static Route Object
            static_route = device.static_route(vrf_name, prefix)
            # Delete it
            static_route.delete()
            # Changed
            result['changed'] = True

        if state == 'create' or state == 'update':
            # Create Static Route object
            static_route = device.static_route(vrf_name, prefix)

            # Add Static Nexthop
            static_route.add_static_nexthop(
                next_hop_ip_address=next_hop_ip_address,
                nexthop_type=route_type,
                distance=distance,
                next_hop_interface=next_hop_interface)

            # Verify if Static Route was created
            if static_route.was_modified():
                # Changed
                result['changed'] = True

        # Exit
        ansible_module.exit_json(**result)
    else:

        aruba_ansible_module = ArubaAnsibleModule(module_args)

        vrf_name = aruba_ansible_module.module.params['vrf_name']
        prefix = aruba_ansible_module.module.params[
            'destination_address_prefix']
        route_type = aruba_ansible_module.module.params['type']
        distance = aruba_ansible_module.module.params['distance']
        next_hop_interface = aruba_ansible_module.module.params[
            'next_hop_interface']
        next_hop_ip_address = aruba_ansible_module.module.params[
            'next_hop_ip_address']
        state = aruba_ansible_module.module.params['state']

        vrf = VRF()

        if vrf_name is None:
            vrf_name = 'default'

        if not vrf.check_vrf_exists(aruba_ansible_module, vrf_name):

            if vrf_name == 'default' and state == 'create':
                aruba_ansible_module = vrf.create_vrf(aruba_ansible_module,
                                                      vrf_name)
            else:
                aruba_ansible_module.module.fail_json(msg="VRF {vrf} is not "
                                                      "configured"
                                                      "".format(vrf=vrf_name))

        encoded_prefix = prefix.replace("/", "%2F")
        encoded_prefix = encoded_prefix.replace(":", "%3A")
        index = vrf_name + '/' + encoded_prefix
        if (state == 'create') or (state == 'update'):
            address_family = 'ipv6' if ':' in prefix else 'ipv4'
            static_route = {}
            static_route[index] = {}
            if address_family is not None:
                static_route[index]["address_family"] = address_family
            if prefix is not None:
                static_route[index]["prefix"] = prefix
            if route_type is not None:
                static_route[index]["static_nexthops"]["0"][
                    "type"] = route_type
                if route_type == 'forward':
                    static_route[index]['static_nexthops'] = {
                        "0": {
                            "bfd_enable": False,
                            "distance": distance
                        }
                    }
                if next_hop_interface is not None:
                    encoded_interface = next_hop_interface.replace('/', '%2F')
                    static_route[index]['static_nexthops']["0"][
                        "port"] = encoded_interface
                if next_hop_ip_address is not None:
                    static_route[index]['static_nexthops']["0"][
                        "ip_address"] = next_hop_ip_address

                aruba_ansible_module = vrf.update_vrf_fields(
                    aruba_ansible_module, vrf_name, 'Static_Route',
                    static_route)

        if (state == 'delete'):
            if not vrf.check_vrf_exists(aruba_ansible_module, vrf_name):
                aruba_ansible_module.module.fail_json(
                    msg="VRF {vrf_name} does not exist".format(
                        vrf_name=vrf_name))
            static_route = vrf.get_vrf_field_value(aruba_ansible_module,
                                                   vrf_name, 'Static_Route')
            if not static_route:
                aruba_ansible_module.warnings.append(
                    "Static route for destination {dest} does not exist in VRF {vrf}"
                    .format(dest=prefix, vrf=vrf_name))
            elif index not in static_route.keys():
                aruba_ansible_module.warnings.append(
                    "Static route for destination {dest} does not exist in VRF {vrf}"
                    .format(dest=prefix, vrf=vrf_name))
            else:
                static_route.pop(index)
                aruba_ansible_module = vrf.update_vrf_fields(
                    aruba_ansible_module, vrf_name, 'Static_Route',
                    static_route)

        aruba_ansible_module.update_switch_config()
Ejemplo n.º 16
0
def main():
    module_args = dict(config_name=dict(type='str', default='running-config'),
                       output_file=dict(type='str', default=None),
                       remote_output_file_tftp_path=dict(type='str',
                                                         default=None),
                       config_type=dict(type='str',
                                        default='json',
                                        choices=['json', 'cli']),
                       vrf=dict(type='str'),
                       sort_json=dict(type='bool', default=True))

    # Version management
    try:

        from ansible.module_utils.aoscx_pyaoscx import Session
        from pyaoscx.session import Session as Pyaoscx_Session
        from pyaoscx.device import Device

        USE_PYAOSCX_SDK = True

    except ImportError:
        USE_PYAOSCX_SDK = False

    # Use PYAOSCX SDK
    if USE_PYAOSCX_SDK:
        from ansible.module_utils.basic import AnsibleModule

        # ArubaModule
        ansible_module = AnsibleModule(argument_spec=module_args,
                                       supports_check_mode=True)

        # Session
        session = Session(ansible_module)

        # Set Variables
        tftp_path = \
            ansible_module.params['remote_output_file_tftp_path']
        vrf = ansible_module.params['vrf']
        config_name = ansible_module.params['config_name']
        config_type = ansible_module.params['config_type']
        config_file = ansible_module.params['output_file']

        result = dict(changed=False)

        if ansible_module.check_mode:
            ansible_module.exit_json(**result)

        # Get session serialized information
        session_info = session.get_session()
        # Create pyaoscx.session object
        s = Pyaoscx_Session.from_session(session_info['s'],
                                         session_info['url'])

        # Create a Device Object
        device = Device(s)

        # Create a Configuration Object
        config = device.configuration()
        success = config.backup_configuration(config_name=config_name,
                                              output_file=config_file,
                                              vrf=vrf,
                                              config_type=config_type,
                                              remote_file_tftp_path=tftp_path)

        # Changed
        result['changed'] = success

        # Exit
        ansible_module.exit_json(**result)

    # Use Older version
    else:

        aruba_ansible_module = ArubaAnsibleModule(module_args=module_args)

        tftp_path = \
            aruba_ansible_module.module.params['remote_output_file_tftp_path']
        vrf = aruba_ansible_module.module.params['vrf']
        config_name = aruba_ansible_module.module.params['config_name']
        config_type = aruba_ansible_module.module.params['config_type']
        config_file = aruba_ansible_module.module.params['output_file']

        if tftp_path is not None:
            if vrf is None:
                aruba_ansible_module.module.fail_json(
                    msg="VRF needs to be provided in order to TFTP "
                    "the configuration from the switch")
            tftp_path_replace = tftp_path.replace("/", "%2F")
            tftp_path_encoded = tftp_path_replace.replace(":", "%3A")
            if config_name != 'running-config' and config_name != 'startup-config':
                aruba_ansible_module.module.fail_json(
                    msg="Only running-config or "
                    "startup-config can be backed-up using TFTP")
            aruba_ansible_module.copy_switch_config_to_remote_location(
                config_name, config_type, tftp_path_encoded, vrf)
        else:

            config_json = aruba_ansible_module.get_switch_config(
                store_config=False)
            with open(config_file, 'w') as to_file:
                formatted_file = json.dumps(config_json, indent=4)
                to_file.write(formatted_file)

        result = dict(changed=aruba_ansible_module.changed,
                      warnings=aruba_ansible_module.warnings)
        result["changed"] = True
        aruba_ansible_module.module.exit_json(**result)
Ejemplo n.º 17
0
def main():
    # Create the Ansible Module
    ansible_module = AnsibleModule(
        argument_spec=get_argument_spec(),
        supports_check_mode=True,
        required_together=[["duplex", "speeds"]],
        mutually_exclusive=[
            ("qos", "no_qos"),
            ("queue_profile", "use_global_queue_profile"),
        ],
    )

    result = dict(changed=False)

    if ansible_module.check_mode:
        ansible_module.exit_json(**result)

    # Get playbook's arguments
    name = ansible_module.params["name"]
    enabled = ansible_module.params["enabled"]
    description = ansible_module.params["description"]
    duplex = ansible_module.params["duplex"]
    speeds = ansible_module.params["speeds"]
    vsx_sync = ansible_module.params["vsx_sync"]
    state = ansible_module.params["state"]
    qos = ansible_module.params["qos"]
    no_qos = ansible_module.params["no_qos"]
    queue_profile = ansible_module.params["queue_profile"]
    use_global_queue_profile = ansible_module.params[
        "use_global_queue_profile"]
    qos_trust_mode = ansible_module.params["qos_trust_mode"]
    qos_rate = ansible_module.params["qos_rate"]

    session = get_pyaoscx_session(ansible_module)
    device = Device(session)

    interface = device.interface(name)
    modified = interface.modified

    if state == "delete":
        interface.delete()
        # report only if created before this run
        result["changed"] = not modified
        ansible_module.exit_json(**result)

    if description:
        interface.description = description
    if enabled is not None:
        interface.admin_state = "up" if enabled else "down"
    if vsx_sync:
        if not device.materialized:
            device.get()
        if not device.vsx_capable():
            ansible_module.module.fail_json(msg="Device doesn't support VSX")
        clean_vsx_features = [
            vsx_sync_features_mapping(feature) for feature in vsx_sync
        ]
        interface.vsx_sync = clean_vsx_features

    modified |= interface.apply()
    if duplex and speeds:
        modified |= interface.speed_duplex_configure(speeds=speeds,
                                                     duplex=duplex)
    if qos:
        modified |= interface.update_interface_qos(qos)
    if no_qos:
        modified |= interface.update_interface_qos(None)
    if queue_profile:
        modified |= interface.update_interface_queue_profile(queue_profile)
    if use_global_queue_profile:
        modified |= interface.update_interface_queue_profile(None)
    if qos_trust_mode:
        modified |= interface.update_interface_qos_trust_mode(qos_trust_mode)
    if qos_rate:
        modified |= interface.update_interface_qos_rate(qos_rate)

    result["changed"] = modified
    ansible_module.exit_json(**result)
Ejemplo n.º 18
0
def main():
    module_args = dict(banner_type=dict(type='str',
                                        required=True,
                                        choices=['banner', 'banner_exec']),
                       banner=dict(type='str', required=False),
                       state=dict(default='create',
                                  choices=['create', 'delete']))

    # Version management
    try:

        from ansible.module_utils.aoscx_pyaoscx import Session
        from pyaoscx.session import Session as Pyaoscx_Session
        from pyaoscx.device import Device

        USE_PYAOSCX_SDK = True

    except ImportError:
        USE_PYAOSCX_SDK = False

    # Use PYAOSCX SDK
    if USE_PYAOSCX_SDK:
        from ansible.module_utils.basic import AnsibleModule

        # ArubaModule
        ansible_module = AnsibleModule(argument_spec=module_args,
                                       supports_check_mode=True)

        # Session
        session = Session(ansible_module)

        # Set Variables
        state = ansible_module.params['state']
        banner_type = ansible_module.params['banner_type']
        banner = ansible_module.params['banner']

        result = dict(changed=False)

        if ansible_module.check_mode:
            ansible_module.exit_json(**result)

        # Get session serialized information
        session_info = session.get_session()
        # Create pyaoscx.session object
        s = Pyaoscx_Session.from_session(session_info['s'],
                                         session_info['url'])

        # Create a Device Object
        device = Device(s)

        if state == 'delete':
            # Delete it
            modified_op = device.delete_banner(banner_type)

        if state == 'create' or state == 'update':
            # Set Banner
            modified_op = device.update_banner(banner, banner_type)

        # Changed
        result['changed'] = modified_op

        # Exit
        ansible_module.exit_json(**result)

    # Use Older version
    else:
        aruba_ansible_module = ArubaAnsibleModule(module_args)
        state = aruba_ansible_module.module.params['state']
        banner_type = aruba_ansible_module.module.params['banner_type']
        banner = aruba_ansible_module.module.params['banner']

        if state == 'delete':
            if 'other_config' in aruba_ansible_module.running_config[
                    'System'].keys():  # NOQA
                if banner_type in aruba_ansible_module.running_config[
                        'System']["other_config"].keys():  # NOQA
                    aruba_ansible_module.running_config['System'][
                        "other_config"].pop(banner_type)  # NOQA
                else:
                    aruba_ansible_module.warnings.append(
                        "{x} has already been "
                        "removed"
                        "".format(x=banner_type))
            else:
                aruba_ansible_module.warnings.append("{x} has already been "
                                                     "removed"
                                                     "".format(x=banner_type))

            aruba_ansible_module.module.log(
                'Banner is removed from the switch.')

        if state == 'create':

            if banner is None:
                banner = ""

            if 'other_config' not in aruba_ansible_module.running_config[
                    'System'].keys():  # NOQA
                aruba_ansible_module.running_config['System'][
                    "other_config"] = {}

            if banner_type not in aruba_ansible_module.running_config[
                    'System']["other_config"].keys():  # NOQA
                aruba_ansible_module.running_config['System']["other_config"][
                    banner_type] = banner  # NOQA

            elif aruba_ansible_module.running_config['System']["other_config"][
                    banner_type] != banner:  # NOQA
                aruba_ansible_module.running_config['System']["other_config"][
                    banner_type] = banner  # NOQA

            aruba_ansible_module.module.log('Banner is added to the switch.')

        aruba_ansible_module.update_switch_config()
Ejemplo n.º 19
0
def main():
    module_args = dict(name=dict(type='str', required=True),
                       state=dict(default='create',
                                  choices=['create', 'delete']))

    # Version management
    try:

        from ansible.module_utils.aoscx_pyaoscx import Session
        from pyaoscx.session import Session as Pyaoscx_Session
        from pyaoscx.device import Device

        USE_PYAOSCX_SDK = True

    except ImportError:
        USE_PYAOSCX_SDK = False

    # Use PYAOSCX SDK
    if USE_PYAOSCX_SDK:
        from ansible.module_utils.basic import AnsibleModule

        # ArubaModule
        ansible_module = AnsibleModule(argument_spec=module_args,
                                       supports_check_mode=True)

        # Session
        session = Session(ansible_module)

        # Set Variables
        vrf_name = ansible_module.params['name']
        state = ansible_module.params['state']

        result = dict(changed=False)

        if ansible_module.check_mode:
            ansible_module.exit_json(**result)

        # Get session serialized information
        session_info = session.get_session()
        # Create pyaoscx.session object
        s = Pyaoscx_Session.from_session(session_info['s'],
                                         session_info['url'])

        # Create a Device Object
        device = Device(s)

        if state == 'delete':
            # Create VRF Object
            vrf = device.vrf(vrf_name)
            # Delete it
            vrf.delete()
            # Changed
            result['changed'] = vrf.was_modified()

        if state == 'create':
            # Create VRF with incoming attributes
            vrf = device.vrf(vrf_name)
            # Changed
            result['changed'] = vrf.was_modified()

        # Exit
        ansible_module.exit_json(**result)

    # Use Older version
    else:
        aruba_ansible_module = ArubaAnsibleModule(module_args)

        vrf_name = aruba_ansible_module.module.params['name']
        state = aruba_ansible_module.module.params['state']

        vrf = VRF()

        if state == 'create':
            aruba_ansible_module = vrf.create_vrf(aruba_ansible_module,
                                                  vrf_name)

        if state == 'delete':
            aruba_ansible_module = vrf.delete_vrf(aruba_ansible_module,
                                                  vrf_name)

        aruba_ansible_module.update_switch_config()
Ejemplo n.º 20
0
def main():
    module_args = dict(
        source_config=dict(type='str', default='running-config'),
        destination_config=dict(type='str', default='startup-config')
    )

    # Version management
    try:

        from ansible.module_utils.aoscx_pyaoscx import Session
        from pyaoscx.session import Session as Pyaoscx_Session
        from pyaoscx.device import Device

        USE_PYAOSCX_SDK = True

    except ImportError:
        USE_PYAOSCX_SDK = False

    # Use PYAOSCX SDK
    if USE_PYAOSCX_SDK:
        from ansible.module_utils.basic import AnsibleModule

        # ArubaModule
        ansible_module = AnsibleModule(
            argument_spec=module_args,
            supports_check_mode=True)

        # Session
        session = Session(ansible_module)

        # Set Variables
        source_config = ansible_module.params['source_config']
        destination_config = ansible_module.params['destination_config']

        result = dict(
            changed=False
        )

        if ansible_module.check_mode:
            ansible_module.exit_json(**result)

        # Get session serialized information
        session_info = session.get_session()
        # Create pyaoscx.session object
        s = Pyaoscx_Session.from_session(
            session_info['s'], session_info['url'])

        # Create a Device Object
        device = Device(s)

        # Create a Configuration Object
        config = device.configuration()
        success = config.create_checkpoint(source_config, destination_config)

        # Changed
        result['changed'] = success

        # Exit
        ansible_module.exit_json(**result)

    # Use Older version
    else:
        aruba_ansible_module = ArubaAnsibleModule(module_args=module_args)

        source_config = aruba_ansible_module.module.params['source_config']
        destination_config = \
            aruba_ansible_module.module.params['destination_config']

        url = '/rest/v1/fullconfigs/{dest}?from=/rest/v1/fullconfigs/{src}'.format(
            dest=destination_config, src=source_config)
        put(aruba_ansible_module.module, url)
        result = dict(changed=aruba_ansible_module.changed,
                      warnings=aruba_ansible_module.warnings)
        result["changed"] = True
        aruba_ansible_module.module.exit_json(**result)
def main():
    module_args = dict(
        partition_name=dict(type='str', default='primary',
                            choices=['primary', 'secondary']),
        firmware_file_path=dict(type='str', default=None),
        remote_firmware_file_path=dict(type='str', default=None),
        vrf=dict(type='str', default=None)
    )

    # Version management
    try:

        from ansible.module_utils.aoscx_pyaoscx import Session
        from pyaoscx.session import Session as Pyaoscx_Session
        from pyaoscx.device import Device

        USE_PYAOSCX_SDK = True

    except ImportError:
        USE_PYAOSCX_SDK = False

    # Use PYAOSCX SDK
    if USE_PYAOSCX_SDK:
        from ansible.module_utils.basic import AnsibleModule

        # ArubaModule
        ansible_module = AnsibleModule(
            argument_spec=module_args,
            supports_check_mode=True)

        # Session
        session = Session(ansible_module)

        # Set Variables
        http_path = ansible_module.params['remote_firmware_file_path']
        vrf = ansible_module.params['vrf']
        partition_name = ansible_module.params['partition_name']
        firmware_file_path = \
            ansible_module.params['firmware_file_path']

        result = dict(
            changed=False
        )

        if ansible_module.check_mode:
            ansible_module.exit_json(**result)

        # Get session serialized information
        session_info = session.get_session()

        # Create pyaoscx.session object
        # Use username and password from session_info
        s = Pyaoscx_Session.from_session(
            session_info['s'],
            session_info['url'],
            session_info['credentials'])

        # Create a Device Object
        device = Device(s)

        success = device.upload_firmware(
            partition_name=partition_name,
            firmware_file_path=firmware_file_path,
            remote_firmware_file_path=http_path,
            vrf=vrf)

        # Changed
        result['changed'] = success

        # Exit
        ansible_module.exit_json(**result)

    # Use Older version
    else:
        aruba_ansible_module = ArubaAnsibleModule(module_args=module_args)
        http_path = aruba_ansible_module.module.params['remote_firmware_file_path']
        vrf = aruba_ansible_module.module.params['vrf']
        partition_name = aruba_ansible_module.module.params['partition_name']
        firmware_file_path = \
            aruba_ansible_module.module.params['firmware_file_path']

        unsupported_versions = [
            "10.00",
            "10.01",
            "10.02",
            "10.03",
        ]

        if http_path is not None:

            switch_current_firmware = aruba_ansible_module.switch_current_firmware
            for version in unsupported_versions:
                if version in switch_current_firmware:
                    aruba_ansible_module.module.fail_json(
                        msg="Minimum supported firmware version is 10.04 for"
                            " remote firmware upload, your version is {firmware}"
                            "".format(firmware=switch_current_firmware))

            if vrf is None:
                aruba_ansible_module.module.fail_json(
                    msg="VRF needs to be provided in order"
                        " to upload firmware from HTTP server")
            http_path_replace = http_path.replace("/", "%2F")
            http_path_encoded = http_path_replace.replace(":", "%3A")
            url = '/rest/v1/firmware?image={part}&from={path}&vrf={vrf}'\
                .format(part=partition_name,
                        path=http_path_encoded,
                        vrf=vrf)
            put(aruba_ansible_module.module, url)
        else:
            url = '/rest/v1/firmware?image={part}'.format(part=partition_name)
            file_upload(aruba_ansible_module, url, firmware_file_path)
        result = dict(changed=aruba_ansible_module.changed,
                      warnings=aruba_ansible_module.warnings)
        result["changed"] = True
        aruba_ansible_module.module.exit_json(**result)
Ejemplo n.º 22
0
def main():
    '''
    Ansible module to configure DNS on AOS-CX switch
    '''
    module_args = dict(mgmt_nameservers=dict(type='dict', required=False),
                       dns_domain_list=dict(type='dict', required=False),
                       dns_domain_name=dict(type='str', required=False),
                       dns_name_servers=dict(type='dict', required=False),
                       vrf=dict(type='str', required=False),
                       dns_host_v4_address_mapping=dict(type='dict',
                                                        required=False),
                       state=dict(type='str',
                                  default='create',
                                  choices=['create', 'delete', 'update']))

    # Version management
    try:
        from ansible.module_utils.aoscx_pyaoscx import Session
        from pyaoscx.session import Session as Pyaoscx_Session
        from pyaoscx.device import Device

        USE_PYAOSCX_SDK = True

    except ImportError:
        USE_PYAOSCX_SDK = False

    # Use PYAOSCX SDK
    if USE_PYAOSCX_SDK:
        from ansible.module_utils.basic import AnsibleModule

        # ArubaModule
        ansible_module = AnsibleModule(argument_spec=module_args,
                                       supports_check_mode=True)

        # Session
        session = Session(ansible_module)
        # Set Variables
        mgmt_nameservers = ansible_module.params['mgmt_nameservers']
        dns_domain_name = ansible_module.params['dns_domain_name']
        dns_domain_list = ansible_module.params['dns_domain_list']
        vrf_name = ansible_module.params['vrf']
        dns_name_servers = ansible_module.params['dns_name_servers']
        dns_host_v4_address_mapping = ansible_module.params[
            'dns_host_v4_address_mapping']
        state = ansible_module.params['state']

        result = dict(changed=False)

        if ansible_module.check_mode:
            ansible_module.exit_json(**result)

        # Get session serialized information
        session_info = session.get_session()
        # Create pyaoscx.session object
        s = Pyaoscx_Session.from_session(session_info['s'],
                                         session_info['url'])

        # Create a Device Object
        device = Device(s)

        if state == 'delete':
            # Modifed Variables
            modified_op = False
            modified_op2 = False

            # Create DNS object
            dns = device.dns(vrf=vrf_name)

            # Delete MGMT nameservers
            if mgmt_nameservers is not None:
                # Delete it
                modified_op = dns.delete_mgmt_nameservers()

            # Delete DNS
            dns.delete_dns(
                dns_domain_name,
                dns_domain_list,
                dns_name_servers,
                dns_host_v4_address_mapping,
            )
            # Check if dns was modified
            modified_op2 = dns.was_modified()

            # Changed
            result['changed'] = modified_op or modified_op2

        if state == 'create' or state == 'update':
            # Modifed Variables
            modified_op = False
            modified_op2 = False

            # Create DNS object
            dns = device.dns(
                vrf=vrf_name,
                domain_name=dns_domain_name,
                domain_list=dns_domain_list,
                domain_servers=dns_name_servers,
                host_v4_address_mapping=dns_host_v4_address_mapping)

            # Check if dns was modified
            modified_op = dns.was_modified()

            # Set MGMT name servers
            if mgmt_nameservers is not None:
                primary = None
                secondary = None
                # Get Primary and Secondary
                for key, value in mgmt_nameservers.items():
                    if key.lower() == 'primary':
                        primary = value
                    elif key.lower() == 'secondary':
                        secondary = value
                # Set up
                modified_op2 = dns.setup_mgmt_nameservers(primary=primary,
                                                          secondary=secondary)

            # Changed
            result['changed'] = modified_op or modified_op2

        # Exit
        ansible_module.exit_json(**result)

    # Use Older version
    else:

        aruba_ansible_module = ArubaAnsibleModule(module_args)

        mgmt_nameservers = aruba_ansible_module.module.params[
            'mgmt_nameservers']
        dns_domain_name = aruba_ansible_module.module.params['dns_domain_name']
        dns_domain_list = aruba_ansible_module.module.params['dns_domain_list']
        vrf_name = aruba_ansible_module.module.params['vrf']
        dns_name_servers = aruba_ansible_module.module.params[
            'dns_name_servers']
        dns_host_v4_address_mapping = aruba_ansible_module.module.params[
            'dns_host_v4_address_mapping']
        state = aruba_ansible_module.module.params['state']

        vrf = VRF()

        if state == 'create' or state == 'update':
            if mgmt_nameservers is not None:
                if 'mode' in aruba_ansible_module.running_config['System'][
                        'mgmt_intf']:
                    mgmt_if_mode = aruba_ansible_module.running_config[
                        'System']['mgmt_intf']['mode']
                else:
                    mgmt_if_mode = 'dhcp'

                if mgmt_if_mode != 'static':
                    message_part1 = "The management interface must have static"
                    message_part2 = "IP to configure management interface name servers"
                    aruba_ansible_module.module.fail_json(msg=message_part1 +
                                                          message_part2)

                for key, value in mgmt_nameservers.items():
                    if key.lower() == 'primary':
                        aruba_ansible_module.running_config['System'][
                            'mgmt_intf']['dns_server_1'] = value
                    elif key.lower() == 'secondary':
                        aruba_ansible_module.running_config['System'][
                            'mgmt_intf']['dns_server_2'] = value

            if vrf_name is None:
                vrf_name = 'default'

            if not vrf.check_vrf_exists(aruba_ansible_module, vrf_name):
                aruba_ansible_module.module.fail_json(
                    msg="VRF {vrf} is not configured".format(vrf=vrf_name))
                return aruba_ansible_module

            if dns_domain_name is not None:
                aruba_ansible_module = vrf.update_vrf_fields(
                    aruba_ansible_module, vrf_name, "dns_domain_name",
                    dns_domain_name)

            if dns_domain_list is not None:
                aruba_ansible_module = vrf.update_vrf_fields(
                    aruba_ansible_module, vrf_name, "dns_domain_list",
                    dns_domain_list)

            if dns_name_servers is not None:
                aruba_ansible_module = vrf.update_vrf_fields(
                    aruba_ansible_module, vrf_name, "dns_name_servers",
                    dns_name_servers)

            if dns_host_v4_address_mapping is not None:
                aruba_ansible_module = vrf.update_vrf_fields(
                    aruba_ansible_module, vrf_name,
                    "dns_host_v4_address_mapping", dns_host_v4_address_mapping)

        if state == 'delete':

            if vrf_name is None:
                vrf_name = 'default'

            if not vrf.check_vrf_exists(aruba_ansible_module, vrf_name):
                aruba_ansible_module.warnings.append(
                    "VRF {vrf} is not configured"
                    "".format(vrf=vrf_name))
                return aruba_ansible_module

            if mgmt_nameservers is not None:

                for k in mgmt_nameservers.keys():
                    if k.lower() == 'primary':
                        aruba_ansible_module.running_config['System'][
                            'mgmt_intf'].pop('dns_server_1')
                    elif k.lower() == 'secondary':
                        aruba_ansible_module.running_config['System'][
                            'mgmt_intf'].pop('dns_server_2')

            if dns_domain_name is not None:
                aruba_ansible_module = vrf.delete_vrf_field(
                    aruba_ansible_module, vrf_name, "dns_domain_name",
                    dns_domain_name)

            if dns_domain_list is not None:
                aruba_ansible_module = vrf.delete_vrf_field(
                    aruba_ansible_module, vrf_name, "dns_domain_list",
                    dns_domain_list)

            if dns_name_servers is not None:
                aruba_ansible_module = vrf.delete_vrf_field(
                    aruba_ansible_module, vrf_name, "dns_name_servers",
                    dns_name_servers)

            if dns_host_v4_address_mapping is not None:
                aruba_ansible_module = vrf.delete_vrf_field(
                    aruba_ansible_module, vrf_name,
                    "dns_host_v4_address_mapping", dns_host_v4_address_mapping)

        aruba_ansible_module.update_switch_config()
Ejemplo n.º 23
0
def main():
    module_args = dict(config_name=dict(type='str', default='running-config'),
                       config_json=dict(type='str', default=None),
                       config_file=dict(type='str', default=None),
                       remote_config_file_tftp_path=dict(type='str',
                                                         default=None),
                       vrf=dict(type='str'))

    # Use PYAOSCX SDK
    if USE_PYAOSCX_SDK:
        from ansible.module_utils.basic import AnsibleModule

        # ArubaModule
        ansible_module = AnsibleModule(argument_spec=module_args,
                                       supports_check_mode=True)

        # Session
        session = Session(ansible_module)

        # Set Variables
        tftp_path = ansible_module.params['remote_config_file_tftp_path']
        vrf = ansible_module.params['vrf']
        config_name = ansible_module.params['config_name']
        config_json = ansible_module.params['config_json']
        config_file = ansible_module.params['config_file']

        result = dict(changed=False)

        if ansible_module.check_mode:
            ansible_module.exit_json(**result)

        # Get session's serialized information
        session_info = session.get_session()
        # Create pyaoscx session object
        s = Pyaoscx_Session.from_session(session_info['s'],
                                         session_info['url'])

        # Create a Device Object
        device = Device(s)

        # Create an instance of the Configuration class from Device
        config = device.configuration()  # Contains action methods

        # Upload configuration file/json to switch
        success = config.upload_switch_config(config_name=config_name,
                                              config_file=config_file,
                                              config_json=config_json,
                                              vrf=vrf,
                                              remote_file_tftp_path=tftp_path)

        # Changed
        result['changed'] = success

        # Exit
        ansible_module.exit_json(**result)

    # Use Older Version
    else:

        aruba_ansible_module = ArubaAnsibleModule(module_args=module_args,
                                                  store_config=False)

        tftp_path = aruba_ansible_module.module.params[
            "remote_config_file_tftp_path"]
        vrf = aruba_ansible_module.module.params['vrf']
        config_name = aruba_ansible_module.module.params['config_name']
        config_json = aruba_ansible_module.module.params['config_json']
        config_file = aruba_ansible_module.module.params['config_file']

        if tftp_path is not None:
            if vrf is None:
                aruba_ansible_module.module.fail_json(
                    msg=("VRF needs to be provided in order to TFTP"
                         " the configuration onto the switch"))
            tftp_path_replace = tftp_path.replace("/", "%2F")
            tftp_path_encoded = tftp_path_replace.replace(":", "%3A")
            if config_name != 'running-config' and config_name != 'startup-config':
                aruba_ansible_module.module.fail_json(
                    msg=("Only running-config or startup-config "
                         "can be uploaded using TFTP"))
            aruba_ansible_module.tftp_switch_config_from_remote_location(
                tftp_path_encoded, config_name, vrf)
        else:
            if config_json:
                with open(config_json) as json_file:
                    config_json = json.load(json_file)

            if config_file:
                with open(config_file) as json_file:
                    config_json = json.load(json_file)

            aruba_ansible_module.upload_switch_config(config_json, config_name)

        result = dict(changed=aruba_ansible_module.changed,
                      warnings=aruba_ansible_module.warnings)
        result["changed"] = True
        aruba_ansible_module.module.exit_json(**result)