Ejemplo n.º 1
0
def esg_clear_interface(client_session, esg_name, ifindex):
    """
    This function resets the vnic configuration of an ESG to its default state
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the ESG to configure interfaces on
    :param ifindex: The vnic index, e.g. vnic3 and the index 3
    :return: Returns True on successful configuration of the Interface
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return False
    vnic_config = client_session.read('vnic', uri_parameters={'index': ifindex, 'edgeId': esg_id})['body']

    vnic_config['vnic']['mtu'] = '1500'
    vnic_config['vnic']['type'] = 'internal'
    vnic_config['vnic']['name'] = 'vnic{}'.format(ifindex)
    vnic_config['vnic']['addressGroups'] = None
    vnic_config['vnic']['portgroupId'] = None
    vnic_config['vnic']['portgroupName'] = None
    vnic_config['vnic']['enableProxyArp'] = 'false'
    vnic_config['vnic']['enableSendRedirects'] = 'false'
    vnic_config['vnic']['isConnected'] = 'false'

    cfg_result = client_session.update('vnic', uri_parameters={'index': ifindex, 'edgeId': esg_id},
                                       request_body_dict=vnic_config)
    if cfg_result['status'] == 204:
        return True
    else:
        return False
Ejemplo n.º 2
0
def create_self_signed_cert(client_session, scope_id, cert, private_key):
    """
    This function adds an Load Balancer Application profile to an ESG

    :type client_session: nsxramlclient.client.NsxClient
    :param client_session: A nsxramlclient session Object
    :type scope_id: str
    :param scope_id: The display name of a Edge Service Gateway used for Load Balancing
    :type cert: file
    :param cert: Cert file with PEM Encoding
    :type private_key: file
    :param private_key: Private key file
    :return: Returns the Object Id of the newly created Cert, False on a failure, and None if the ESG was
             not found in NSX
    :rtype: str
    """
    esg_id, esg_params = get_edge(client_session, scope_id)
    if not esg_id:
        return None

    cert_dict = client_session.extract_resource_body_example('certificateSelfSigned', 'create')

    cert_dict['trustObject']['pemEncoding'] = cert.read()
    cert_dict['trustObject']['privateKey'] = private_key.read()

    result = client_session.create('certificateSelfSigned', uri_parameters={'scopeId': esg_id},
                                   request_body_dict=cert_dict)

    # print result['body']['certificates']['certificate']['subjectCn']

    if result['status'] != 200:
        return None
    else:
        return result['body']['certificates']['certificate']['objectId']
Ejemplo n.º 3
0
def esg_route_del(client_session, esg_name, network, next_hop):
    """
    This function deletes a static route to an ESG
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the ESG where the route should be deleted
    :param network: The routes network in the x.x.x.x/yy format, e.g. 192.168.1.0/24
    :param next_hop: The next hop ip
    :return: True on success, False on failure
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return False

    rtg_cfg = client_session.read('routingConfigStatic', uri_parameters={'edgeId': esg_id})['body']
    if rtg_cfg['staticRouting']['staticRoutes']:
        routes = client_session.normalize_list_return(rtg_cfg['staticRouting']['staticRoutes']['route'])
    else:
        return False

    routes_filtered = [route for route in routes if not (route['network'] == network and route['nextHop'] == next_hop)]
    if len(routes_filtered) == len(routes):
        return False
    rtg_cfg['staticRouting']['staticRoutes'] = {'route': routes_filtered}

    cfg_result = client_session.update('routingConfigStatic', uri_parameters={'edgeId': esg_id},
                                       request_body_dict=rtg_cfg)
    if cfg_result['status'] == 204:
        return True
    else:
        return False
Ejemplo n.º 4
0
def esg_route_list(client_session, esg_name):
    """
    This function return the configured static routes
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the ESG of which the routes should be listed
    :return: returns a tuple, the firt item of the tuple contains a list of 1 tuple with
             item 0 containing the routes network,
             item 1 containing the next hop IP as string,
             item 2 containing the vnic used by the route as string,
             item 3 containing the admin distance of the route as string,
             item 4 containing the mtu of the route as string
             The second item in the tuple contains a dict with all the static routing config details
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return False

    rtg_cfg = client_session.read('routingConfigStatic', uri_parameters={'edgeId': esg_id})['body']

    if not rtg_cfg['staticRouting']['staticRoutes']:
        return [()], {}

    routes = []
    routes_api = client_session.normalize_list_return(rtg_cfg['staticRouting']['staticRoutes']['route'])
    for route in routes_api:
        if 'vnic' in route.keys():
            vnic = route['vnic']
        else:
            vnic = ''
        add_route = (route['network'], route['nextHop'], vnic, route['adminDistance'], route['mtu'])
        routes.append(add_route)

    return routes, rtg_cfg['staticRouting']['staticRoutes']
Ejemplo n.º 5
0
def esg_route_del(client_session, esg_name, network, next_hop):
    """
    This function deletes a static route to an ESG
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the ESG where the route should be deleted
    :param network: The routes network in the x.x.x.x/yy format, e.g. 192.168.1.0/24
    :param next_hop: The next hop ip
    :return: True on success, False on failure
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return False

    rtg_cfg = client_session.read('routingConfigStatic', uri_parameters={'edgeId': esg_id})['body']
    if rtg_cfg['staticRouting']['staticRoutes']:
        routes = client_session.normalize_list_return(rtg_cfg['staticRouting']['staticRoutes']['route'])
    else:
        return False

    routes_filtered = [route for route in routes if not (route['network'] == network and route['nextHop'] == next_hop)]
    if len(routes_filtered) == len(routes):
        return False
    rtg_cfg['staticRouting']['staticRoutes'] = {'route': routes_filtered}

    cfg_result = client_session.update('routingConfigStatic', uri_parameters={'edgeId': esg_id},
                                       request_body_dict=rtg_cfg)
    if cfg_result['status'] == 204:
        return True
    else:
        return False
Ejemplo n.º 6
0
def get_nat_rules_with_ip(client_session, esg_name, original_ip, translated_ip):
    """
    This function returns all NAT rules on an esg with the specified original and translated IPs
    :type client_session: nsxramlclient.client.NsxClient
    :param client_session: A nsxramlclient session Object
    :type esg_name: str
    :param esg_name: The display name of a Edge Service Gateway used for Load Balancing
    :type original_ip: str
    :param esg_name: The original IP in the NAT rule
    :type translated_ip: str
    :param esg_name: The translated IP in the NAT rule
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return None

    result = client_session.read('edgeNat', uri_parameters={'edgeId': esg_id})

    if result['status'] != 200:
        return None
    else:
        rules = []
        nats = result['body']['nat']['natRules']['natRule']

        for i in nats:
            if original_ip in i['originalAddress'] and translated_ip in i['translatedAddress'] and i['ruleType'] == 'user':
                rules.append(i['ruleId'])

        # returns a list of ruleIDs
        return rules
Ejemplo n.º 7
0
def esg_fw_default_set(client_session, esg_name, def_action, logging_enabled=None):
    """
    This function sets the default firewall rule to accept or deny
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the ESG to which you want to apply the default firewall rule:
    :param def_action: Default firewall action, values are either accept or deny
    :param logging_enabled: (Optional) Is logging enabled by default (true/false)
    :return: True on success, False on failure
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return False

    if not logging_enabled:
        logging_enabled = 'false'

    def_policy_body = client_session.extract_resource_body_example('defaultFirewallPolicy', 'update')
    def_policy_body['firewallDefaultPolicy']['action'] = def_action
    def_policy_body['firewallDefaultPolicy']['loggingEnabled'] = logging_enabled

    cfg_result = client_session.update('defaultFirewallPolicy', uri_parameters={'edgeId': esg_id},
                                  request_body_dict=def_policy_body)

    if cfg_result['status'] == 204:
        return True
    else:
        return False
Ejemplo n.º 8
0
def esg_dgw_read(client_session, esg_name):
    """
    This function return the default gateway configuration
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the ESG to return the default gateway configuration from
    :return: returns a tuple, the firt item of the tuple contains a list of 1 tuple with
             item 0 containing the vnic used by the default route as string,
             item 1 containing the gateway IP as string,
             item 2 containing the admin distance of the default route as string,
             item 3 containing the mtu of the gateway as string
             The second item in the tuple contains a dict with all the default gateway config details
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return False

    rtg_cfg = client_session.read('routingConfigStatic', uri_parameters={'edgeId': esg_id})['body']

    if 'defaultRoute' not in rtg_cfg['staticRouting'].keys():
        return [()], {}

    mtu = rtg_cfg['staticRouting']['defaultRoute']['mtu']

    try:
        admin_distance = rtg_cfg['staticRouting']['defaultRoute']['adminDistance']
    except KeyError:
        admin_distance = '1'
    try:
        vnic = rtg_cfg['staticRouting']['defaultRoute']['vnic']
    except KeyError:
        vnic = ''

    dgw_cfg_tpl = [(vnic, rtg_cfg['staticRouting']['defaultRoute']['gatewayAddress'], admin_distance, mtu)]

    return dgw_cfg_tpl, rtg_cfg['staticRouting']['defaultRoute']
Ejemplo n.º 9
0
def esg_dgw_read(client_session, esg_name):
    """
    This function return the default gateway configuration
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the ESG to return the default gateway configuration from
    :return: returns a tuple, the firt item of the tuple contains a list of 1 tuple with
             item 0 containing the vnic used by the default route as string,
             item 1 containing the gateway IP as string,
             item 2 containing the admin distance of the default route as string,
             item 3 containing the mtu of the gateway as string
             The second item in the tuple contains a dict with all the default gateway config details
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return False

    rtg_cfg = client_session.read('routingConfigStatic', uri_parameters={'edgeId': esg_id})['body']

    if 'defaultRoute' not in rtg_cfg['staticRouting'].keys():
        return [()], {}

    mtu = rtg_cfg['staticRouting']['defaultRoute']['mtu']

    try:
        admin_distance = rtg_cfg['staticRouting']['defaultRoute']['adminDistance']
    except KeyError:
        admin_distance = '1'
    try:
        vnic = rtg_cfg['staticRouting']['defaultRoute']['vnic']
    except KeyError:
        vnic = ''

    dgw_cfg_tpl = [(vnic, rtg_cfg['staticRouting']['defaultRoute']['gatewayAddress'], admin_distance, mtu)]

    return dgw_cfg_tpl, rtg_cfg['staticRouting']['defaultRoute']
Ejemplo n.º 10
0
def create_ipset(client_session, esg_name, ipset_name, ipset_value):
    """
    This function creates an IPset on the edge
    :param client_session: An instance of an NsxClient Session
    :param ipset_name: Name of the ipset to be created
    :param ipset_value: value of the IPset to be created
    :return: ???
    """

    ipset_dict = client_session.extract_resource_body_example('ipsetCreate', 'create')
    ipset_dict['ipset']['inheritanceAllowed'] = 'false'
    ipset_dict['ipset']['name'] = ipset_name
    ipset_dict['ipset']['objectTypeName'] = 'IPSet'
    ipset_dict['ipset']['type']['typeName'] = 'IPSet'
    ipset_dict['ipset']['value']= ipset_value

    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return False, None

    new_ipset = client_session.create('ipsetCreate', request_body_dict=ipset_dict, uri_parameters={'scopeMoref':esg_id})
    if new_ipset['status'] == 201:
            return True, esg_id
    else:
            return False, esg_id
Ejemplo n.º 11
0
def esg_dgw_set(client_session, esg_name, dgw_ip, vnic, mtu=None, admin_distance=None):
    """
    This function sets the default gateway on an ESG
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the ESG to list interfaces of
    :param dgw_ip: The default gateway ip (next hop)
    :param vnic: (Optional) The vnic index of were the default gateway is reachable on
    :param mtu: (Optional) The MTU of the defautl gateway (default=1500)
    :param admin_distance: (OIptional) Admin distance of the defautl route (default=1)
    :return: True on success, False on failure
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return False
    if not mtu:
        mtu = '1500'
    if not admin_distance:
        admin_distance = '1'

    rtg_cfg = client_session.read('routingConfigStatic', uri_parameters={'edgeId': esg_id})['body']
    rtg_cfg['staticRouting']['defaultRoute'] = {'vnic': vnic, 'gatewayAddress': dgw_ip,
                                                'adminDistance': admin_distance, 'mtu': mtu}

    cfg_result = client_session.update('routingConfigStatic', uri_parameters={'edgeId': esg_id},
                                       request_body_dict=rtg_cfg)
    if cfg_result['status'] == 204:
        return True
    else:
        return False
Ejemplo n.º 12
0
def delete_dhcp_binding(client_session, esg_name, binding_id):
    """
    This function deletes a DHCP binding from an edge DHCP Server

    :type client_session: nsxramlclient.client.NsxClient
    :param client_session: A nsxramlclient session Object
    :type esg_name: str
    :param esg_name: The display name of a Edge Service Gateway used for DHCP
    :type binding_id: str
    :param binding_id: The Id of the binding to be deleted (e.g. binding-3)
    :rtype: bool
    :return: Returns None if Edge was not found or the operation failed, returns true on success
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return None

    result = client_session.delete('dhcpStaticBindingID',
                                   uri_parameters={
                                       'edgeId': esg_id,
                                       'bindingID': binding_id
                                   })

    if result['status'] == 204:
        return True
    else:
        return None
Ejemplo n.º 13
0
def esg_route_list(client_session, esg_name):
    """
    This function return the configured static routes
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the ESG of which the routes should be listed
    :return: returns a tuple, the firt item of the tuple contains a list of 1 tuple with
             item 0 containing the routes network,
             item 1 containing the next hop IP as string,
             item 2 containing the vnic used by the route as string,
             item 3 containing the admin distance of the route as string,
             item 4 containing the mtu of the route as string
             The second item in the tuple contains a dict with all the static routing config details
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return False

    rtg_cfg = client_session.read('routingConfigStatic', uri_parameters={'edgeId': esg_id})['body']

    if not rtg_cfg['staticRouting']['staticRoutes']:
        return [()], {}

    routes = []
    routes_api = client_session.normalize_list_return(rtg_cfg['staticRouting']['staticRoutes']['route'])
    for route in routes_api:
        if 'vnic' in route.keys():
            vnic = route['vnic']
        else:
            vnic = ''
        add_route = (route['network'], route['nextHop'], vnic, route['adminDistance'], route['mtu'])
        routes.append(add_route)

    return routes, rtg_cfg['staticRouting']['staticRoutes']
Ejemplo n.º 14
0
def esg_dgw_set(client_session, esg_name, dgw_ip, vnic, mtu=None, admin_distance=None):
    """
    This function sets the default gateway on an ESG
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the ESG to list interfaces of
    :param dgw_ip: The default gateway ip (next hop)
    :param vnic: (Optional) The vnic index of were the default gateway is reachable on
    :param mtu: (Optional) The MTU of the defautl gateway (default=1500)
    :param admin_distance: (OIptional) Admin distance of the defautl route (default=1)
    :return: True on success, False on failure
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return False
    if not mtu:
        mtu = '1500'
    if not admin_distance:
        admin_distance = '1'

    rtg_cfg = client_session.read('routingConfigStatic', uri_parameters={'edgeId': esg_id})['body']
    rtg_cfg['staticRouting']['defaultRoute'] = {'vnic': vnic, 'gatewayAddress': dgw_ip,
                                                'adminDistance': admin_distance, 'mtu': mtu}

    cfg_result = client_session.update('routingConfigStatic', uri_parameters={'edgeId': esg_id},
                                       request_body_dict=rtg_cfg)
    if cfg_result['status'] == 204:
        return True
    else:
        return False
Ejemplo n.º 15
0
def esg_fw_default_set(client_session, esg_name, def_action, logging_enabled=None):
    """
    This function sets the default firewall rule to accept or deny
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the ESG to which you want to apply the default firewall rule:
    :param def_action: Default firewall action, values are either accept or deny
    :param logging_enabled: (Optional) Is logging enabled by default (true/false)
    :return: True on success, False on failure
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return False

    #if not logging_enabled:
    #    logging_enabled = 'false'

    def_policy_body = client_session.extract_resource_body_example('defaultFirewallPolicy', 'update')
    def_policy_body['firewallDefaultPolicy']['action'] = def_action
    def_policy_body['firewallDefaultPolicy']['loggingEnabled'] = logging_enabled

    cfg_result = client_session.update('defaultFirewallPolicy', uri_parameters={'edgeId': esg_id},
                                  request_body_dict=def_policy_body)

    if cfg_result['status'] == 204:
        return True
    else:
        return False
Ejemplo n.º 16
0
def esg_clear_interface(client_session, esg_name, ifindex):
    """
    This function resets the vnic configuration of an ESG to its default state
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the ESG to configure interfaces on
    :param ifindex: The vnic index, e.g. vnic3 and the index 3
    :return: Returns True on successful configuration of the Interface
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return False
    vnic_config = client_session.read('vnic', uri_parameters={'index': ifindex, 'edgeId': esg_id})['body']

    vnic_config['vnic']['mtu'] = '1500'
    vnic_config['vnic']['type'] = 'internal'
    vnic_config['vnic']['name'] = 'vnic{}'.format(ifindex)
    vnic_config['vnic']['addressGroups'] = None
    vnic_config['vnic']['portgroupId'] = None
    vnic_config['vnic']['portgroupName'] = None
    vnic_config['vnic']['enableProxyArp'] = 'false'
    vnic_config['vnic']['enableSendRedirects'] = 'false'
    vnic_config['vnic']['isConnected'] = 'false'

    cfg_result = client_session.update('vnic', uri_parameters={'index': ifindex, 'edgeId': esg_id},
                                       request_body_dict=vnic_config)
    if cfg_result['status'] == 204:
        return True
    else:
        return False
Ejemplo n.º 17
0
def add_dhcp_pool(client_session,
                  esg_name,
                  ip_range,
                  default_gateway=None,
                  subnet_mask=None,
                  domain_name=None,
                  dns_server_1=None,
                  dns_server_2=None,
                  lease_time=None,
                  auto_dns=None):
    """
    This function adds a DHCP Pool to an edge DHCP Server

    :type client_session: nsxramlclient.client.NsxClient
    :param client_session: A nsxramlclient session Object
    :type esg_name: str
    :param esg_name: The display name of a Edge Service Gateway used for DHCP
    :type ip_range: str
    :param ip_range: An IP range, e.g. 192.168.178.10-192.168.178.100 for this IP Pool
    :type default_gateway: str
    :param default_gateway: The default gateway for the specified subnet
    :type subnet_mask: str
    :param subnet_mask: The subnet mask (e.g. 255.255.255.0) for the specified subnet
    :type domain_name: str
    :param domain_name: The DNS domain name (e.g. vmware.com) for the specified subnet
    :type dns_server_1: str
    :param dns_server_1: The primary DNS Server
    :type dns_server_2: str
    :param dns_server_2: The secondary DNS Server
    :type lease_time: str
    :param lease_time: The lease time in seconds, use 'infinite' to disable expiry of DHCP leases
    :type auto_dns: str
    :param auto_dns: ('true'/'false') If set to true, the DNS servers and domain name set for NSX-Manager will be used
    :rtype: str
    :return: Returns a string containing the pool id of the created DHCP Pool
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return None

    dhcp_pool_dict = {
        'ipRange': ip_range,
        'defaultGateway': default_gateway,
        'subnetMask': subnet_mask,
        'domainName': domain_name,
        'primaryNameServer': dns_server_1,
        'secondaryNameServer': dns_server_2,
        'leaseTime': lease_time,
        'autoConfigureDNS': auto_dns
    }

    result = client_session.create(
        'dhcpPool',
        uri_parameters={'edgeId': esg_id},
        request_body_dict={'ipPool': dhcp_pool_dict})
    if result['status'] != 204:
        return None
    else:
        return result['objectId']
Ejemplo n.º 18
0
def dhcp_server(client_session, esg_name, enabled=None, syslog_enabled=None, syslog_level=None):
    """
    This function enables/disables the DHCP server on an Edge Gateway and sets the logging status and Level

    :type client_session: nsxramlclient.client.NsxClient
    :param client_session: A nsxramlclient session Object
    :type esg_name: str
    :param esg_name: The display name of a Edge Service Gateway used for DHCP
    :type enabled: bool
    :param enabled: True/False The desired state of the DHCP Server
    :type syslog_enabled: str
    :param syslog_enabled: ('true'/'false') The desired logging state of the DHCP Server
    :type syslog_level: str
    :param syslog_level: The logging level for DHCP on this Edge (INFO/WARNING/etc.)
    :rtype: bool
    :return: Return True on success of the operation
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return None

    change_needed = False

    current_dhcp_config = client_session.read('dhcp', uri_parameters={'edgeId': esg_id})['body']
    new_dhcp_config = current_dhcp_config

    if enabled:
        if current_dhcp_config['dhcp']['enabled'] == 'false':
            new_dhcp_config['dhcp']['enabled'] = 'true'
            change_needed = True
    else:
        if current_dhcp_config['dhcp']['enabled'] == 'true':
            new_dhcp_config['dhcp']['enabled'] = 'false'
            change_needed = True

    if syslog_enabled == 'true':
        if current_dhcp_config['dhcp']['logging']['enable'] == 'false':
            new_dhcp_config['dhcp']['logging']['enable'] = 'true'
            change_needed = True
    elif syslog_enabled == 'false':
        if current_dhcp_config['dhcp']['logging']['enable'] == 'true':
            new_dhcp_config['dhcp']['logging']['enable'] = 'false'
            change_needed = True

    if syslog_level:
        if current_dhcp_config['dhcp']['logging']['logLevel'] != syslog_level:
            new_dhcp_config['dhcp']['logging']['logLevel'] = syslog_level
            change_needed = True

    if not change_needed:
        return True
    else:
        result = client_session.update('dhcp', uri_parameters={'edgeId': esg_id},
                                       request_body_dict=new_dhcp_config)
        if result['status'] == 204:
            return True
        else:
            return False
Ejemplo n.º 19
0
def dlr_read(client_session, dlr_name):
    """
    This funtions retrieves details of a dlr in NSX
    :param client_session: An instance of an NsxClient Session
    :param dlr_name: The name of the dlr to retrieve details from
    :return: returns a tuple, the first item is a string containing the dlr ID, the second is a dictionary
             containing the dlr details retrieved from the API
    """
    dlr_id, dlr_params = get_edge(client_session, dlr_name)
    return dlr_id, dlr_params
Ejemplo n.º 20
0
def dlr_read(client_session, dlr_name):
    """
    This funtions retrieves details of a dlr in NSX
    :param client_session: An instance of an NsxClient Session
    :param dlr_name: The name of the dlr to retrieve details from
    :return: returns a tuple, the first item is a string containing the dlr ID, the second is a dictionary
             containing the dlr details retrieved from the API
    """
    dlr_id, dlr_params = get_edge(client_session, dlr_name)
    return dlr_id, dlr_params
Ejemplo n.º 21
0
def add_nat_rule(client_session, esg_name, nat_type, nat_vnic, original_ip,
                 translated_ip, original_port, translated_port, protocol,
                 description):
    #def add_nat_rule(client_session, esg_name, nat_type, original_ip, translated_ip):
    """
    This function adds an NAT to an ESG

    :type client_session: nsxramlclient.client.NsxClient
    :param client_session: A nsxramlclient session Object
    :type esg_name: str
    :param esg_name: The display name of a Edge Service Gateway used for Load Balancing
    :type original_ip: str
    :param original_ip: Original IP Address
    :type translated_ip: str
    :param translated_ip: Translated IP Address
    :return: Returns the Object Id of the newly created NAT Rule and None if the ESG was
             not found in NSX
    :rtype: str
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return None

    # PEZ Changes
    nat_dict = client_session.extract_resource_body_example(
        'edgeNatRules', 'create')
    #{'natRules': {'natRule': {'vnic': None, 'protocol': None, 'description': None,
    #'loggingEnabled': None, 'translatedAddress': None, 'enabled': None, 'originalAddress': None,
    #'translatedPort': None, 'action': None, 'originalPort': None}}}

    nat_dict['natRules']['natRule']['vnic'] = nat_vnic
    nat_dict['natRules']['natRule']['protocol'] = protocol
    nat_dict['natRules']['natRule']['description'] = description
    nat_dict['natRules']['natRule']['loggingEnabled'] = 'true'
    # nat_dict['natRules']['natRule']['vnic'] = '0'
    # nat_dict['natRules']['natRule']['protocol'] = 'any'
    # nat_dict['natRules']['natRule']['description'] = ''
    # nat_dict['natRules']['natRule']['loggingEnabled'] = 'false'
    nat_dict['natRules']['natRule']['translatedAddress'] = translated_ip
    nat_dict['natRules']['natRule']['enabled'] = 'true'
    nat_dict['natRules']['natRule']['originalAddress'] = original_ip
    nat_dict['natRules']['natRule']['action'] = nat_type
    nat_dict['natRules']['natRule']['translatedPort'] = translated_port
    nat_dict['natRules']['natRule']['originalPort'] = original_port

    result = client_session.create('edgeNatRules',
                                   uri_parameters={'edgeId': esg_id},
                                   request_body_dict=nat_dict)
    if result['status'] != 201:
        return None
    else:
        return result['objectId']
Ejemplo n.º 22
0
def dlr_delete(client_session, dlr_name):
    """
    This function will delete a dlr in NSX
    :param client_session: An instance of an NsxClient Session
    :param dlr_name: The name of the dlr to delete
    :return: returns a tuple, the first item is a boolean indicating success or failure to delete the dlr,
             the second item is a string containing to dlr id of the deleted dlr
    """
    dlr_id, dlr_params = get_edge(client_session, dlr_name)
    if not dlr_id:
        return False, None
    client_session.delete('nsxEdge', uri_parameters={'edgeId': dlr_id})
    return True, dlr_id
Ejemplo n.º 23
0
def esg_delete(client_session, esg_name):
    """
    This function will delete a esg in NSX
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the ESG to delete
    :return: returns a tuple, the first item is a boolean indicating success or failure to delete the ESG,
             the second item is a string containing to ESG id of the deleted ESG
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return False, None
    client_session.delete('nsxEdge', uri_parameters={'edgeId': esg_id})
    return True, esg_id
Ejemplo n.º 24
0
def esg_delete(client_session, esg_name):
    """
    This function will delete a esg in NSX
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the ESG to delete
    :return: returns a tuple, the first item is a boolean indicating success or failure to delete the ESG,
             the second item is a string containing to ESG id of the deleted ESG
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return False, None
    client_session.delete('nsxEdge', uri_parameters={'edgeId': esg_id})
    return True, esg_id
Ejemplo n.º 25
0
def dlr_delete(client_session, dlr_name):
    """
    This function will delete a dlr in NSX
    :param client_session: An instance of an NsxClient Session
    :param dlr_name: The name of the dlr to delete
    :return: returns a tuple, the first item is a boolean indicating success or failure to delete the dlr,
             the second item is a string containing to dlr id of the deleted dlr
    """
    dlr_id, dlr_params = get_edge(client_session, dlr_name)
    if not dlr_id:
        return False, None
    client_session.delete('nsxEdge', uri_parameters={'edgeId': dlr_id})
    return True, dlr_id
Ejemplo n.º 26
0
def esg_read(client_session, esg_name):
    """
    This funtions retrieves details of a ESG in NSX
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the esg to retrieve details from
    :return: returns a tuple, the first item is a string containing the ESG ID, the second is a dictionary
             containing the ESG details retrieved from the API
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return None, None
    read_result = client_session.read('nsxEdge', uri_parameters={'edgeId': esg_id})
    esg_params = read_result['body']
    return esg_id, esg_params
Ejemplo n.º 27
0
def list_dhcp_bindings(client_session, esg_name):
    """
    This function lists all static bindings on an edge DHCP Server

    :type client_session: nsxramlclient.client.NsxClient
    :param client_session: A nsxramlclient session Object
    :type esg_name: str
    :param esg_name: The display name of a Edge Service Gateway used for DHCP
    :rtype: tuple
    :return: Returns a tuple with the first item being a list of tuples containing:

             [0] Binding Id
             [1] MAC Address if MAC based entry is used
             [2] VM Moid if VM based entry is used
             [3] vnic index of the attached VM if VM based entry is used
             [4] Hostname
             [5] IP Address
             [6] Default Gateway
             [7] Subnet Mask
             [8] Domain Name
             [9] Primary DNS Server
             [10] Secondary DNS Server
             [11] Lease Time
             [12] Autoconfigure DNS (true/false),

             The second item contains a list of dicts with all the pool details as returned by the NSX API
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return None, None

    result = client_session.read('dhcp', uri_parameters={'edgeId': esg_id})
    if not result['body']['dhcp']['staticBindings']:
        return [], []

    bindings = client_session.normalize_list_return(
        result['body']['dhcp']['staticBindings']['staticBinding'])
    bindings_list = [
        (binding.get('bindingId'), binding.get('macAddress'),
         binding.get('vmId'), binding.get('vnicId'), binding.get('hostname'),
         binding.get('ipAddress'), binding.get('defaultGateway'),
         binding.get('subnetMask'), binding.get('domainName'),
         binding.get('primaryNameServer'), binding.get('secondaryNameServer'),
         binding.get('leaseTime'), binding.get('autoConfigureDNS'))
        for binding in bindings
    ]

    bindings_list_verbose = [binding for binding in bindings]

    return bindings_list, bindings_list_verbose
Ejemplo n.º 28
0
def esg_read(client_session, esg_name):
    """
    This funtions retrieves details of a ESG in NSX
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the esg to retrieve details from
    :return: returns a tuple, the first item is a string containing the ESG ID, the second is a dictionary
             containing the ESG details retrieved from the API
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return None, None
    read_result = client_session.read('nsxEdge', uri_parameters={'edgeId': esg_id})
    esg_params = read_result['body']
    return esg_id, esg_params
Ejemplo n.º 29
0
def routing_ospf(client_session, esg_name, vnic_ip, area_id, auth_type, auth_value):
    """
    This function configures the edge for OSPF routing
    :param client_session: An instance of an NsxClient Session
    :param area_id: The id of the vCenter vLAN to use for uplink
    :param auth_type: The type of auth to do (MD5 or password)
    :param auth_value: The MD5 value or password based on auth_type
    :return: ???
    """
    routing_dict = client_session.extract_resource_body_example('routingConfig', 'update')

    del routing_dict['routing']['bgp']
    del routing_dict['routing']['staticRouting']['staticRoutes']
    del routing_dict['routing']['routingGlobalConfig']['ipPrefixes']

    routing_dict['routing']['staticRouting']['defaultRoute']['gatewayAddress'] = '10.193.252.1'
    routing_dict['routing']['staticRouting']['defaultRoute']['vnic'] = '0'

    routing_dict['routing']['routingGlobalConfig']['routerId'] = vnic_ip

    routing_dict['routing']['ospf']['enabled'] = 'true'
    routing_dict['routing']['ospf']['gracefulRestart'] = 'true'
    routing_dict['routing']['ospf']['defaultOriginate'] = 'false'
    routing_dict['routing']['ospf']['ospfAreas']['ospfArea']['areaId'] = area_id
    routing_dict['routing']['ospf']['ospfAreas']['ospfArea']['type'] = 'Normal'
    routing_dict['routing']['ospf']['ospfAreas']['ospfArea']['authentication']['type'] = auth_type
    routing_dict['routing']['ospf']['ospfAreas']['ospfArea']['authentication']['value'] = auth_value

    routing_dict['routing']['ospf']['ospfInterfaces']['ospfInterface']['vnic'] = '0'
    routing_dict['routing']['ospf']['ospfInterfaces']['ospfInterface']['areaId'] = area_id
    routing_dict['routing']['ospf']['ospfInterfaces']['ospfInterface']['helloInterval'] = '10'
    routing_dict['routing']['ospf']['ospfInterfaces']['ospfInterface']['deadInterval'] = '40'
    routing_dict['routing']['ospf']['ospfInterfaces']['ospfInterface']['priority'] = '128'
    routing_dict['routing']['ospf']['ospfInterfaces']['ospfInterface']['cost'] = '1'

    routing_dict['routing']['ospf']['redistribution']['enabled'] = 'true'
    routing_dict['routing']['ospf']['redistribution']['rules']['rule']['from']['connected'] = 'true'
    routing_dict['routing']['ospf']['redistribution']['rules']['rule']['from']['static'] = 'true'
    routing_dict['routing']['ospf']['redistribution']['rules']['rule']['action'] = 'permit'

    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return False, None

    new_esg = client_session.update('routingConfig', uri_parameters={'edgeId': esg_id}, request_body_dict=routing_dict)
    if new_esg['status'] == 204:
        return True, esg_id
    else:
        return False, esg_id
Ejemplo n.º 30
0
def add_vm_binding(client_session, esg_name, vm_id, vnic_id, hostname, ip, default_gateway=None, subnet_mask=None,
                   domain_name=None, dns_server_1=None, dns_server_2=None, lease_time=None, auto_dns=None):
    """
    This function add a VM based static binding entry to an edge DHCP Server

    :type client_session: nsxramlclient.client.NsxClient
    :param client_session: A nsxramlclient session Object
    :type esg_name: str
    :param esg_name: The display name of a Edge Service Gateway used for DHCP
    :type vm_id: str
    :param vm_id: The VM managed object Id in vCenter for the VM to be attached to this binding entry
    :type vnic_id: str
    :param vnic_id: The vnic index for the VM interface attached to this binding entry (e.g. vnic0 has index 0)
    :type hostname: str
    :param hostname: The hostname for this static binding
    :type ip: str
    :param ip: The IP Address for this static binding
    :type default_gateway: str
    :param default_gateway: The default gateway for the specified binding
    :type subnet_mask: str
    :param subnet_mask: The subnet mask (e.g. 255.255.255.0) for the specified binding
    :type domain_name: str
    :param domain_name: The DNS domain name (e.g. vmware.com) for the specified binding
    :type dns_server_1: str
    :param dns_server_1: The primary DNS Server
    :type dns_server_2: str
    :param dns_server_2: The secondary DNS Server
    :type lease_time: str
    :param lease_time: The lease time in seconds, use 'infinite' to disable expiry of DHCP leases
    :type auto_dns: str
    :param auto_dns: ('true'/'false') If set to true, the DNS servers and domain name set for NSX-Manager will be used
    :rtype: str
    :return: Returns a string containing the binding id of the created DHCP binding
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return None

    binding_dict = {'vmId': vm_id, 'vnicId': vnic_id, 'hostname': hostname, 'ipAddress': ip,
                    'defaultGateway': default_gateway, 'subnetMask': subnet_mask, 'domainName': domain_name,
                    'primaryNameServer': dns_server_1, 'secondaryNameServer': dns_server_2, 'leaseTime': lease_time,
                    'autoConfigureDNS': auto_dns}

    result = client_session.create('dhcpStaticBinding', uri_parameters={'edgeId': esg_id},
                                   request_body_dict={'staticBinding': binding_dict})
    if result['status'] != 204:
        return None
    else:
        return result['objectId']
Ejemplo n.º 31
0
def add_dhcp_pool(client_session, esg_name, ip_range, default_gateway=None, subnet_mask=None, domain_name=None,
                  dns_server_1=None, dns_server_2=None, lease_time=None, auto_dns=None):
    """
    This function adds a DHCP Pool to an edge DHCP Server

    :type client_session: nsxramlclient.client.NsxClient
    :param client_session: A nsxramlclient session Object
    :type esg_name: str
    :param esg_name: The display name of a Edge Service Gateway used for DHCP
    :type ip_range: str
    :param ip_range: An IP range, e.g. 192.168.178.10-192.168.178.100 for this IP Pool
    :type default_gateway: str
    :param default_gateway: The default gateway for the specified subnet
    :type subnet_mask: str
    :param subnet_mask: The subnet mask (e.g. 255.255.255.0) for the specified subnet
    :type domain_name: str
    :param domain_name: The DNS domain name (e.g. vmware.com) for the specified subnet
    :type dns_server_1: str
    :param dns_server_1: The primary DNS Server
    :type dns_server_2: str
    :param dns_server_2: The secondary DNS Server
    :type lease_time: str
    :param lease_time: The lease time in seconds, use 'infinite' to disable expiry of DHCP leases
    :type auto_dns: str
    :param auto_dns: ('true'/'false') If set to true, the DNS servers and domain name set for NSX-Manager will be used
    :rtype: str
    :return: Returns a string containing the pool id of the created DHCP Pool
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return None

    dhcp_pool_dict = {'ipRange': ip_range,
                      'defaultGateway': default_gateway,
                      'subnetMask': subnet_mask,
                      'domainName': domain_name,
                      'primaryNameServer': dns_server_1,
                      'secondaryNameServer': dns_server_2,
                      'leaseTime': lease_time,
                      'autoConfigureDNS': auto_dns}

    result = client_session.create('dhcpPool', uri_parameters={'edgeId': esg_id},
                                   request_body_dict={'ipPool': dhcp_pool_dict})
    if result['status'] != 204:
        return None
    else:
        return result['objectId']
Ejemplo n.º 32
0
def read(client_session, esg_name):
    """
    This function returns the configuration of the DHCP server on an Edge Gateway

    :type client_session: nsxramlclient.client.NsxClient
    :param client_session: A nsxramlclient session Object
    :type esg_name: str
    :param esg_name: The display name of a Edge Service Gateway used for DHCP
    :rtype: dict
    :return: A dict containing the configuration information of DHCP on the specified Edge Gateway
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return None

    dhcp_status = client_session.read('dhcp', uri_parameters={'edgeId': esg_id})['body']
    return dhcp_status
Ejemplo n.º 33
0
def list_dhcp_bindings(client_session, esg_name):
    """
    This function lists all static bindings on an edge DHCP Server

    :type client_session: nsxramlclient.client.NsxClient
    :param client_session: A nsxramlclient session Object
    :type esg_name: str
    :param esg_name: The display name of a Edge Service Gateway used for DHCP
    :rtype: tuple
    :return: Returns a tuple with the first item being a list of tuples containing:

             [0] Binding Id
             [1] MAC Address if MAC based entry is used
             [2] VM Moid if VM based entry is used
             [3] vnic index of the attached VM if VM based entry is used
             [4] Hostname
             [5] IP Address
             [6] Default Gateway
             [7] Subnet Mask
             [8] Domain Name
             [9] Primary DNS Server
             [10] Secondary DNS Server
             [11] Lease Time
             [12] Autoconfigure DNS (true/false),

             The second item contains a list of dicts with all the pool details as returned by the NSX API
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return None, None

    result = client_session.read('dhcp', uri_parameters={'edgeId': esg_id})
    if not result['body']['dhcp']['staticBindings']:
        return [], []

    bindings = client_session.normalize_list_return(result['body']['dhcp']['staticBindings']['staticBinding'])
    bindings_list = [(binding.get('bindingId'), binding.get('macAddress'), binding.get('vmId'),
                      binding.get('vnicId'), binding.get('hostname'), binding.get('ipAddress'),
                      binding.get('defaultGateway'), binding.get('subnetMask'), binding.get('domainName'),
                      binding.get('primaryNameServer'), binding.get('secondaryNameServer'),
                      binding.get('leaseTime'), binding.get('autoConfigureDNS')) for binding in bindings]

    bindings_list_verbose = [binding for binding in bindings]

    return bindings_list, bindings_list_verbose
Ejemplo n.º 34
0
def read(client_session, esg_name):
    """
    This function returns the configuration of the DHCP server on an Edge Gateway

    :type client_session: nsxramlclient.client.NsxClient
    :param client_session: A nsxramlclient session Object
    :type esg_name: str
    :param esg_name: The display name of a Edge Service Gateway used for DHCP
    :rtype: dict
    :return: A dict containing the configuration information of DHCP on the specified Edge Gateway
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return None

    dhcp_status = client_session.read('dhcp',
                                      uri_parameters={'edgeId':
                                                      esg_id})['body']
    return dhcp_status
Ejemplo n.º 35
0
def delete_nat_rule(client_session, esg_name, rule_id):
    """
    This function deletes the NAT rule with ID rule_id

    :type client_session: nsxramlclient.client.NsxClient
    :param client_session: A nsxramlclient session Object
    :type esg_name: str
    :param esg_name: The display name of a Edge Service Gateway
    :param rule_id: The ID of the NAT rules
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return None

    result = client_session.delete('edgeNatRule', uri_parameters={'edgeId': esg_id, 'ruleID':rule_id})
    if result['status'] != 204:
        return None
    else:
        return result
Ejemplo n.º 36
0
def list_dhcp_pools(client_session, esg_name):
    """
    This function lists all DHCP Pools on an edge DHCP Server

    :type client_session: nsxramlclient.client.NsxClient
    :param client_session: A nsxramlclient session Object
    :type esg_name: str
    :param esg_name: The display name of a Edge Service Gateway used for DHCP
    :rtype: tuple
    :return: Returns a tuple with the first item being a list of tuples containing:

             [0] Pool Id
             [1] IP Range
             [2] Default Gateway
             [3] Subnet Mask
             [4] Domain Name
             [5] Primary DNS Server
             [6] Secondary DNS Server
             [7] Lease Time
             [8] Autoconfigure DNS (true/false),

             The second item contains a list of dicts with all the pool details as returned by the NSX API
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return None, None

    result = client_session.read('dhcp', uri_parameters={'edgeId': esg_id})
    if not result['body']['dhcp']['ipPools']:
        return [], []

    ip_pools = client_session.normalize_list_return(
        result['body']['dhcp']['ipPools']['ipPool'])

    pool_list = [(pool.get('poolId'), pool.get('ipRange'),
                  pool.get('defaultGateway'), pool.get('subnetMask'),
                  pool.get('domainName'), pool.get('primaryNameServer'),
                  pool.get('secondaryNameServer'), pool.get('leaseTime'),
                  pool.get('autoConfigureDNS')) for pool in ip_pools]

    pool_list_verbose = [pool for pool in ip_pools]

    return pool_list, pool_list_verbose
Ejemplo n.º 37
0
def esg_dgw_clear(client_session, esg_name):
    """
    This function clears the default gateway config on an ESG
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the ESG to list interfaces of
    :return: True on success, False on failure
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return False

    rtg_cfg = client_session.read('routingConfigStatic', uri_parameters={'edgeId': esg_id})['body']
    rtg_cfg['staticRouting']['defaultRoute'] = None

    cfg_result = client_session.update('routingConfigStatic', uri_parameters={'edgeId': esg_id},
                                       request_body_dict=rtg_cfg)
    if cfg_result['status'] == 204:
        return True
    else:
        return False
Ejemplo n.º 38
0
def esg_dgw_clear(client_session, esg_name):
    """
    This function clears the default gateway config on an ESG
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the ESG to list interfaces of
    :return: True on success, False on failure
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return False

    rtg_cfg = client_session.read('routingConfigStatic', uri_parameters={'edgeId': esg_id})['body']
    rtg_cfg['staticRouting']['defaultRoute'] = None

    cfg_result = client_session.update('routingConfigStatic', uri_parameters={'edgeId': esg_id},
                                       request_body_dict=rtg_cfg)
    if cfg_result['status'] == 204:
        return True
    else:
        return False
Ejemplo n.º 39
0
def list_dhcp_pools(client_session, esg_name):
    """
    This function lists all DHCP Pools on an edge DHCP Server

    :type client_session: nsxramlclient.client.NsxClient
    :param client_session: A nsxramlclient session Object
    :type esg_name: str
    :param esg_name: The display name of a Edge Service Gateway used for DHCP
    :rtype: tuple
    :return: Returns a tuple with the first item being a list of tuples containing:

             [0] Pool Id
             [1] IP Range
             [2] Default Gateway
             [3] Subnet Mask
             [4] Domain Name
             [5] Primary DNS Server
             [6] Secondary DNS Server
             [7] Lease Time
             [8] Autoconfigure DNS (true/false),

             The second item contains a list of dicts with all the pool details as returned by the NSX API
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return None, None

    result = client_session.read('dhcp', uri_parameters={'edgeId': esg_id})
    if not result['body']['dhcp']['ipPools']:
        return [], []

    ip_pools = client_session.normalize_list_return(result['body']['dhcp']['ipPools']['ipPool'])

    pool_list = [(pool.get('poolId'), pool.get('ipRange'), pool.get('defaultGateway'), pool.get('subnetMask'),
                  pool.get('domainName'), pool.get('primaryNameServer'), pool.get('secondaryNameServer'),
                  pool.get('leaseTime'), pool.get('autoConfigureDNS')) for pool in ip_pools]

    pool_list_verbose = [pool for pool in ip_pools]

    return pool_list, pool_list_verbose
Ejemplo n.º 40
0
def esg_list_interfaces(client_session, esg_name):
    """
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the ESG to list interfaces of
    :return: returns two tuples, the first is a list of tuples with
             item 0 containing the vnic Name as string,
             item 1 containing the vnic index as string,
             item 2 containing the ip as string,
             item 3 containing the secondary ip as list of strings
             item 4 containing the netmask as string,
             item 5 containing the 'connected-to' portgroup as string,
             The second item contains a list of dictionaries containing all ESG vnic details
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return None, None
    all_int_response = client_session.read('vnics', uri_parameters={'edgeId': esg_id})
    all_int = client_session.normalize_list_return(all_int_response['body']['vnics']['vnic'])
    esg_int_list = []
    esg_int_list_verbose = []
    for interface in all_int:
        try:
            ip = interface['addressGroups']['addressGroup']['primaryAddress']
            snmask = interface['addressGroups']['addressGroup']['subnetMask']
        except TypeError:
            ip = ''
            snmask = ''
        try:
            pgname = interface['portgroupName']
        except KeyError:
            pgname = ''
        try:
            secondary_ips = interface['addressGroups']['addressGroup']['secondaryAddresses']['ipAddress']
        except:
            secondary_ips = None

        esg_int_list.append((interface['name'], interface['index'], ip, snmask, pgname, secondary_ips))
        esg_int_list_verbose.append(interface)
    return esg_int_list, esg_int_list_verbose
Ejemplo n.º 41
0
def esg_list_interfaces(client_session, esg_name):
    """
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the ESG to list interfaces of
    :return: returns two tuples, the first is a list of tuples with
             item 0 containing the vnic Name as string,
             item 1 containing the vnic index as string,
             item 2 containing the ip as string,
             item 3 containing the secondary ip as list of strings
             item 4 containing the netmask as string,
             item 5 containing the 'connected-to' portgroup as string,
             The second item contains a list of dictionaries containing all ESG vnic details
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return None, None
    all_int_response = client_session.read('vnics', uri_parameters={'edgeId': esg_id})
    all_int = client_session.normalize_list_return(all_int_response['body']['vnics']['vnic'])
    esg_int_list = []
    esg_int_list_verbose = []
    for interface in all_int:
        try:
            ip = interface['addressGroups']['addressGroup']['primaryAddress']
            snmask = interface['addressGroups']['addressGroup']['subnetMask']
        except TypeError:
            ip = ''
            snmask = ''
        try:
            pgname = interface['portgroupName']
        except KeyError:
            pgname = ''
        try:
            secondary_ips = interface['addressGroups']['addressGroup']['secondaryAddresses']['ipAddress']
        except:
            secondary_ips = None

        esg_int_list.append((interface['name'], interface['index'], ip, snmask, pgname, secondary_ips))
        esg_int_list_verbose.append(interface)
    return esg_int_list, esg_int_list_verbose
Ejemplo n.º 42
0
def esg_route_add(client_session, esg_name, network, next_hop, vnic=None, mtu=None,
                  admin_distance=None, description=None):
    """
    This function adds a static route to an ESG
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the ESG where the route should be added
    :param network: The routes network in the x.x.x.x/yy format, e.g. 192.168.1.0/24
    :param next_hop: The next hop ip
    :param vnic: (Optional) The vnic index of were this route is reachable on
    :param mtu: (Optional) The MTU of the route (default=1500)
    :param admin_distance: (Optional) Admin distance of the defautl route (default=1)
    :param description: (Optional) A description for this route
    :return: True on success, False on failure
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return False
    if not mtu:
        mtu = '1500'
    if not admin_distance:
        admin_distance = '1'

    rtg_cfg = client_session.read('routingConfigStatic', uri_parameters={'edgeId': esg_id})['body']
    if rtg_cfg['staticRouting']['staticRoutes']:
        routes = client_session.normalize_list_return(rtg_cfg['staticRouting']['staticRoutes']['route'])
    else:
        routes = []
    new_route = {'vnic': vnic, 'network': network, 'nextHop': next_hop, 'adminDistance': admin_distance,
                 'mtu': mtu, 'description': description}
    routes.append(new_route)
    rtg_cfg['staticRouting']['staticRoutes'] = {'route': routes}

    cfg_result = client_session.update('routingConfigStatic', uri_parameters={'edgeId': esg_id},
                                       request_body_dict=rtg_cfg)
    if cfg_result['status'] == 204:
        return True
    else:
        return False
Ejemplo n.º 43
0
def esg_route_add(client_session, esg_name, network, next_hop, vnic=None, mtu=None,
                  admin_distance=None, description=None):
    """
    This function adds a static route to an ESG
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the ESG where the route should be added
    :param network: The routes network in the x.x.x.x/yy format, e.g. 192.168.1.0/24
    :param next_hop: The next hop ip
    :param vnic: (Optional) The vnic index of were this route is reachable on
    :param mtu: (Optional) The MTU of the route (default=1500)
    :param admin_distance: (Optional) Admin distance of the defautl route (default=1)
    :param description: (Optional) A description for this route
    :return: True on success, False on failure
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return False
    if not mtu:
        mtu = '1500'
    if not admin_distance:
        admin_distance = '1'

    rtg_cfg = client_session.read('routingConfigStatic', uri_parameters={'edgeId': esg_id})['body']
    if rtg_cfg['staticRouting']['staticRoutes']:
        routes = client_session.normalize_list_return(rtg_cfg['staticRouting']['staticRoutes']['route'])
    else:
        routes = []
    new_route = {'vnic': vnic, 'network': network, 'nextHop': next_hop, 'adminDistance': admin_distance,
                 'mtu': mtu, 'description': description}
    routes.append(new_route)
    rtg_cfg['staticRouting']['staticRoutes'] = {'route': routes}

    cfg_result = client_session.update('routingConfigStatic', uri_parameters={'edgeId': esg_id},
                                       request_body_dict=rtg_cfg)
    if cfg_result['status'] == 204:
        return True
    else:
        return False
Ejemplo n.º 44
0
def delete_dhcp_binding(client_session, esg_name, binding_id):
    """
    This function deletes a DHCP binding from an edge DHCP Server

    :type client_session: nsxramlclient.client.NsxClient
    :param client_session: A nsxramlclient session Object
    :type esg_name: str
    :param esg_name: The display name of a Edge Service Gateway used for DHCP
    :type binding_id: str
    :param binding_id: The Id of the binding to be deleted (e.g. binding-3)
    :rtype: bool
    :return: Returns None if Edge was not found or the operation failed, returns true on success
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return None

    result = client_session.delete('dhcpStaticBindingID', uri_parameters={'edgeId': esg_id, 'bindingID': binding_id})

    if result['status'] == 204:
        return True
    else:
        return None
Ejemplo n.º 45
0
def add_vm_binding(client_session,
                   esg_name,
                   vm_id,
                   vnic_id,
                   hostname,
                   ip,
                   default_gateway=None,
                   subnet_mask=None,
                   domain_name=None,
                   dns_server_1=None,
                   dns_server_2=None,
                   lease_time=None,
                   auto_dns=None):
    """
    This function add a VM based static binding entry to an edge DHCP Server

    :type client_session: nsxramlclient.client.NsxClient
    :param client_session: A nsxramlclient session Object
    :type esg_name: str
    :param esg_name: The display name of a Edge Service Gateway used for DHCP
    :type vm_id: str
    :param vm_id: The VM managed object Id in vCenter for the VM to be attached to this binding entry
    :type vnic_id: str
    :param vnic_id: The vnic index for the VM interface attached to this binding entry (e.g. vnic0 has index 0)
    :type hostname: str
    :param hostname: The hostname for this static binding
    :type ip: str
    :param ip: The IP Address for this static binding
    :type default_gateway: str
    :param default_gateway: The default gateway for the specified binding
    :type subnet_mask: str
    :param subnet_mask: The subnet mask (e.g. 255.255.255.0) for the specified binding
    :type domain_name: str
    :param domain_name: The DNS domain name (e.g. vmware.com) for the specified binding
    :type dns_server_1: str
    :param dns_server_1: The primary DNS Server
    :type dns_server_2: str
    :param dns_server_2: The secondary DNS Server
    :type lease_time: str
    :param lease_time: The lease time in seconds, use 'infinite' to disable expiry of DHCP leases
    :type auto_dns: str
    :param auto_dns: ('true'/'false') If set to true, the DNS servers and domain name set for NSX-Manager will be used
    :rtype: str
    :return: Returns a string containing the binding id of the created DHCP binding
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return None

    binding_dict = {
        'vmId': vm_id,
        'vnicId': vnic_id,
        'hostname': hostname,
        'ipAddress': ip,
        'defaultGateway': default_gateway,
        'subnetMask': subnet_mask,
        'domainName': domain_name,
        'primaryNameServer': dns_server_1,
        'secondaryNameServer': dns_server_2,
        'leaseTime': lease_time,
        'autoConfigureDNS': auto_dns
    }

    result = client_session.create(
        'dhcpStaticBinding',
        uri_parameters={'edgeId': esg_id},
        request_body_dict={'staticBinding': binding_dict})
    if result['status'] != 204:
        return None
    else:
        return result['objectId']
Ejemplo n.º 46
0
def dhcp_server(client_session,
                esg_name,
                enabled=None,
                syslog_enabled=None,
                syslog_level=None):
    """
    This function enables/disables the DHCP server on an Edge Gateway and sets the logging status and Level

    :type client_session: nsxramlclient.client.NsxClient
    :param client_session: A nsxramlclient session Object
    :type esg_name: str
    :param esg_name: The display name of a Edge Service Gateway used for DHCP
    :type enabled: bool
    :param enabled: True/False The desired state of the DHCP Server
    :type syslog_enabled: str
    :param syslog_enabled: ('true'/'false') The desired logging state of the DHCP Server
    :type syslog_level: str
    :param syslog_level: The logging level for DHCP on this Edge (INFO/WARNING/etc.)
    :rtype: bool
    :return: Return True on success of the operation
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return None

    change_needed = False

    current_dhcp_config = client_session.read(
        'dhcp', uri_parameters={'edgeId': esg_id})['body']
    new_dhcp_config = current_dhcp_config

    if enabled:
        if current_dhcp_config['dhcp']['enabled'] == 'false':
            new_dhcp_config['dhcp']['enabled'] = 'true'
            change_needed = True
    else:
        if current_dhcp_config['dhcp']['enabled'] == 'true':
            new_dhcp_config['dhcp']['enabled'] = 'false'
            change_needed = True

    if syslog_enabled == 'true':
        if current_dhcp_config['dhcp']['logging']['enable'] == 'false':
            new_dhcp_config['dhcp']['logging']['enable'] = 'true'
            change_needed = True
    elif syslog_enabled == 'false':
        if current_dhcp_config['dhcp']['logging']['enable'] == 'true':
            new_dhcp_config['dhcp']['logging']['enable'] = 'false'
            change_needed = True

    if syslog_level:
        if current_dhcp_config['dhcp']['logging']['logLevel'] != syslog_level:
            new_dhcp_config['dhcp']['logging']['logLevel'] = syslog_level
            change_needed = True

    if not change_needed:
        return True
    else:
        result = client_session.update('dhcp',
                                       uri_parameters={'edgeId': esg_id},
                                       request_body_dict=new_dhcp_config)
        if result['status'] == 204:
            return True
        else:
            return False
Ejemplo n.º 47
0
def esg_cfg_interface(client_session, esg_name, ifindex, ipaddr=None, netmask=None, prefixlen=None, name=None, mtu=None,
                      is_connected=None, portgroup_id=None, vnic_type=None, enable_send_redirects=None,
                      enable_proxy_arp=None, secondary_ips=None):
    """
    This function configures vnic interfaces on ESGs
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the ESG to configure interfaces on
    :param ifindex: The vnic index, e.g. vnic3 and the index 3
    :param ipaddr: (Optional) The primary IP Address to be configured for this interface
    :param netmask: (Optional) The netmask in the x.x.x.x format
    :param prefixlen: (Optional) The prefix length, this takes precedence over the netmask
    :param name: (Optional) The name assigned to the vnic
    :param mtu: (Optional) The vnic MTU
    :param is_connected: (Optional) The vnic connection state (true/false)
    :param portgroup_id: (Optional) The portgroup id of logical switch id to connenct this vnic to
    :param vnic_type: (Optional) The vnic type (uplink/internal)
    :param enable_send_redirects: (Optional) Whether the interface will send icmp redirects (true/false)
    :param enable_proxy_arp: (Optional) Whether the interface will do proxy arp (true/false)
    :param secondary_ips: (Optional) A list of additional secondary IP addresses in the primary IP's Subnet
    :return: Returns True on successful configuration of the Interface
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return False
    vnic_config = client_session.read('vnic', uri_parameters={'index': ifindex, 'edgeId': esg_id})['body']

    if not mtu:
        mtu = 1500
    if not vnic_type:
        vnic_type = 'internal'

    vnic_config['vnic']['mtu'] = mtu
    vnic_config['vnic']['type'] = vnic_type
    if name:
        vnic_config['vnic']['name'] = name
    if portgroup_id:
        vnic_config['vnic']['portgroupId'] = portgroup_id
    if enable_send_redirects:
        vnic_config['vnic']['enableSendRedirects'] = enable_send_redirects
    if enable_proxy_arp:
        vnic_config['vnic']['enableProxyArp'] = enable_proxy_arp
    if is_connected:
        vnic_config['vnic']['isConnected'] = is_connected
    if ipaddr and (netmask or prefixlen):
        address_group = {}
        sec_ips = []
        if netmask:
            address_group['subnetMask'] = netmask
        if prefixlen:
            address_group['subnetPrefixLength'] = str(prefixlen)
        if secondary_ips:
            sec_ips = secondary_ips
        address_group['primaryAddress'] = ipaddr
        address_group['secondaryAddresses'] = {'ipAddress': sec_ips}
        vnic_config['vnic']['addressGroups'] = {'addressGroup': address_group}

    cfg_result = client_session.update('vnic', uri_parameters={'index': ifindex, 'edgeId': esg_id},
                                       request_body_dict=vnic_config)
    if cfg_result['status'] == 204:
        return True
    else:
        return False
Ejemplo n.º 48
0
def create_fw_rule(client_session, vccontent, esg_name, rule_src, rule_dst, rule_app, rule_action, rule_description):
    """
    This function creates a firewall on the edge
    :param client_session: An instance of an NsxClient Session
    :param rule_src: source object of the firwall rule
    :param rule_dst: destination object of the firwall rule
    :param rule_app: application object of the firwall rule
    :param rule_action: accept or deny
    :param rule_description: description of the rule

    :return: ???
    """
    firewallRules_dict = dict()
    firewallRules_dict['firewallRules'] = dict()
    firewallRules_dict['firewallRules']['firewallRule'] = list()

    firewallRule_dict =  dict()

    firewallRule_dict['enabled'] = 'true'
    firewallRule_dict['loggingEnabled'] = 'true'

    firewallRule_dict['name'] = rule_description
    firewallRule_dict['action'] = rule_action

    # if the source/dst/application is any, the dict is not needed.
    # if the src/dest/app object doesn't exist, fail gracefully. Otherwise an any-any-any rule will be created
    if rule_src != 'any':
        src = nametovalue (vccontent, client_session, rule_src, 'ipset')
        if src == '':
            return False, None
        else:
            firewallRule_dict['source'] = {'groupingObjectId':src}

    if rule_dst != 'any':
        dst = nametovalue (vccontent, client_session, rule_dst, 'ipset')
        if dst == '':
            return False, None
        else:
            firewallRule_dict['destination'] = {'groupingObjectId':dst}

    if rule_app != 'any':

        # find the ID for the rule_app object
        serviceGroups = client_session.read('serviceGroups', uri_parameters={'scopeId': 'globalroot-0' })
        serviceGroups_list = serviceGroups.items()[1][1]['list']['applicationGroup']
        app = ''
        for i, val in enumerate(serviceGroups_list):
            if str(val['name']) == rule_app:
                app = val['objectId']

        if app == '':
            return False, None
        else:
            firewallRule_dict['application'] = {'applicationId':app}


    ## source is any
#    firewallRules_dict['destination'] = {'groupingObjectId':slot_networks}
#    firewallRules_dict['application'] = {'applicationId':PCF_Ports}


    firewallRules_dict['firewallRules']['firewallRule'].append(firewallRule_dict)

    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return False, None

    new_firewallRules = client_session.create('firewallRules', request_body_dict=firewallRules_dict, uri_parameters={'edgeId':esg_id})
#    client_session.view_response(new_firewallRules)
#    client_session.view_body_dict(new_firewallRules)

    if new_firewallRules['status'] == 201:
        return True, new_firewallRules['objectId']
    else:
        return False, None
Ejemplo n.º 49
0
def esg_cfg_interface(client_session, esg_name, ifindex, ipaddr=None, netmask=None, prefixlen=None, name=None, mtu=None,
                      is_connected=None, portgroup_id=None, vnic_type=None, enable_send_redirects=None,
                      enable_proxy_arp=None, secondary_ips=None):
    """
    This function configures vnic interfaces on ESGs
    :param client_session: An instance of an NsxClient Session
    :param esg_name: The name of the ESG to configure interfaces on
    :param ifindex: The vnic index, e.g. vnic3 and the index 3
    :param ipaddr: (Optional) The primary IP Address to be configured for this interface
    :param netmask: (Optional) The netmask in the x.x.x.x format
    :param prefixlen: (Optional) The prefix length, this takes precedence over the netmask
    :param name: (Optional) The name assigned to the vnic
    :param mtu: (Optional) The vnic MTU
    :param is_connected: (Optional) The vnic connection state (true/false)
    :param portgroup_id: (Optional) The portgroup id of logical switch id to connenct this vnic to
    :param vnic_type: (Optional) The vnic type (uplink/internal)
    :param enable_send_redirects: (Optional) Whether the interface will send icmp redirects (true/false)
    :param enable_proxy_arp: (Optional) Whether the interface will do proxy arp (true/false)
    :param secondary_ips: (Optional) A list of additional secondary IP addresses in the primary IP's Subnet
    :return: Returns True on successful configuration of the Interface
    """
    esg_id, esg_params = get_edge(client_session, esg_name)
    if not esg_id:
        return False
    vnic_config = client_session.read('vnic', uri_parameters={'index': ifindex, 'edgeId': esg_id})['body']

    if not mtu:
        mtu = 1500
    if not vnic_type:
        vnic_type = 'internal'

    vnic_config['vnic']['mtu'] = mtu
    vnic_config['vnic']['type'] = vnic_type
    if name:
        vnic_config['vnic']['name'] = name
    if portgroup_id:
        vnic_config['vnic']['portgroupId'] = portgroup_id
    if enable_send_redirects:
        vnic_config['vnic']['enableSendRedirects'] = enable_send_redirects
    if enable_proxy_arp:
        vnic_config['vnic']['enableProxyArp'] = enable_proxy_arp
    if is_connected:
        vnic_config['vnic']['isConnected'] = is_connected
    if ipaddr and (netmask or prefixlen):
        address_group = {}
        sec_ips = []
        if netmask:
            address_group['subnetMask'] = netmask
        if prefixlen:
            address_group['subnetPrefixLength'] = str(prefixlen)
        if secondary_ips:
            sec_ips = secondary_ips
        address_group['primaryAddress'] = ipaddr
        address_group['secondaryAddresses'] = {'ipAddress': sec_ips}
        vnic_config['vnic']['addressGroups'] = {'addressGroup': address_group}

    cfg_result = client_session.update('vnic', uri_parameters={'index': ifindex, 'edgeId': esg_id},
                                       request_body_dict=vnic_config)
    if cfg_result['status'] == 204:
        return True
    else:
        return False