コード例 #1
0
def listLogicalRouters(module, stub_config):
    lr_list = []
    try:
        lr_svc = LogicalRouters(stub_config)
        lr_list = lr_svc.list()
    except Error as ex:
        api_error = ex.date.convert_to(ApiError)
        module.fail_json(msg='API Error listing Logical Routers: %s'%(api_error.error_message))
    return lr_list
コード例 #2
0
def main():
    connection = create_api_connection()

    # logicalswitches_svc = LogicalSwitches(connection)
    # result = logicalswitches_svc.list()

    logicalrouters_svc = LogicalRouters(connection)
    result = logicalrouters_svc.list()

    pp = PrettyPrinter()
    pp.pprint(result)
コード例 #3
0
def prepare_connectors():
    global CONNECTION
    CONNECTION = create_api_connection()

    global SVC_LOGICAL_SWITCHES
    SVC_LOGICAL_SWITCHES = LogicalSwitches(CONNECTION)
    global SVC_LOGICAL_ROUTERS
    SVC_LOGICAL_ROUTERS = LogicalRouters(CONNECTION)
    global SVC_LOGICAL_ROUTER_PORTS
    SVC_LOGICAL_ROUTER_PORTS = LogicalRouterPorts(CONNECTION)
    global SVC_LOGICAL_PORTS
    SVC_LOGICAL_PORTS = LogicalPorts(CONNECTION)
コード例 #4
0
def main():
    connection = create_api_connection()
    pp = PrettyPrinter()

    pp.pprint(
        LogicalRouters(connection).get(logical_router_id=LOGICAL_ROUTER_ID))
    pp.pprint(NatRules(connection).list(logical_router_id=LOGICAL_ROUTER_ID))
    # pp.pprint(BgpAdvertisementRules(connection).get(logical_router_id=LOGICAL_ROUTER_ID))
    pp.pprint(
        BgpRedistributionRules(connection).get(
            logical_router_id=LOGICAL_ROUTER_ID))
    pp.pprint(BfdPeers(connection).list(logical_router_id=LOGICAL_ROUTER_ID))
    pp.pprint(
        BgpNeighborsStatus(connection).list(
            logical_router_id=LOGICAL_ROUTER_ID, source='realtime'))
コード例 #5
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            vip_address=dict(required=True, type='str'),
            enabled=dict(required=False, type='bool', default=True),
            t0_router=dict(required=True, type='str'),
            redundant_uplink_port_ids=dict(required=True, type='list'),
            state=dict(required=False, type='str', default="present", choices=['present', 'absent']),
            nsx_manager=dict(required=True, type='str'),
            nsx_username=dict(required=True, type='str'),
            nsx_passwd=dict(required=True, type='str', no_log=True)
        ),
        supports_check_mode=True
    )

    if not HAS_PYNSXT:
        module.fail_json(msg='pynsxt is required for this module')
    session = requests.session()
    session.verify = False
    nsx_url = 'https://%s:%s' % (module.params['nsx_manager'], 443)
    connector = connect.get_requests_connector(
        session=session, msg_protocol='rest', url=nsx_url)
    stub_config = StubConfigurationFactory.new_std_configuration(connector)
    security_context = create_user_password_security_context(module.params["nsx_username"], module.params["nsx_passwd"])
    connector.set_security_context(security_context)
    requests.packages.urllib3.disable_warnings()

    lr_svc = LogicalRouters(stub_config)
    lr = getLogicalRouterByName(module, stub_config)
    subnet_list = []
    subnet = module.params['vip_address'].split('/')
    new_subnet = VIPSubnet(active_vip_addresses=[subnet[0]], prefix_length=int(subnet[1]))
    subnet_list.append(new_subnet)

    haVipConfig = [HaVipConfig(
			enabled=module.params['enabled'], 
			ha_vip_subnets=subnet_list, 
			redundant_uplink_port_ids=module.params['redundant_uplink_port_ids']
		)]


    if module.params['state'] == 'present':
        if lr.advanced_config.ha_vip_configs is None:
            lr.advanced_config.ha_vip_configs=haVipConfig
            if module.check_mode:
                module.exit_json(changed=True, debug_out=str(lr), id="1111")
            try:
                new_lr = lr_svc.update(lr.id, lr)
                module.exit_json(changed=True, object_name=module.params['vip_address'], id=lr.id, message="VIP for Logical Router with name %s was created!"%(lr.display_name))
            except Error as ex:
                api_error = ex.data.convert_to(ApiError)
                module.fail_json(msg='API Error creating VIP: %s'%(str(api_error.error_message)))
        elif lr.advanced_config.ha_vip_configs != haVipConfig:
                lr.advanced_config.ha_vip_configs=haVipConfig
                if module.check_mode:
                    module.exit_json(changed=True, debug_out=str(lr), id=lr.id)
                new_lr = lr_svc.update(lr.id, lr)
                module.exit_json(changed=True, object_name=module.params['vip_address'], id=lr.id, message="VIP for Logical Router with name %s has been changed!"%(lr.display_name))
        module.exit_json(changed=False, object_name=module.params['vip_address'], id=lr.id, message="VIP Logical Router with name %s already exists!"%(lr.display_name))

    elif module.params['state'] == "absent":

        if lr.advanced_config.ha_vip_configs:
            try:
                lr.advanced_config.ha_vip_configs=None
                if module.check_mode:
                    module.exit_json(changed=True, debug_out=str(lr), id=lr.id)
                new_lr = lr_svc.update(lr.id, lr)
                module.exit_json(changed=True, object_name=module.params['vip_address'], id=lr.id, message="VIP for Logical Router with name %s was deleted!"%(lr.display_name))

            except Error as ex:
                api_error = ex.date.convert_to(ApiError)
                module.fail_json(msg='API Error deleting Logical Router VIP: %s'%(api_error.error_message))

        module.exit_json(changed=False, object_name=module.params['vip_address'], message="Logical Router VIP  %s does not exist!"%(module.params['vip_address']))
コード例 #6
0
def main():
    module = AnsibleModule(argument_spec=dict(
        network=dict(required=True, type='str'),
        description=dict(required=False, type='str', default=None),
        next_hops=dict(required=True, type='list', default=None),
        admin_distance=dict(required=False, type='int', default=1),
        router_name=dict(required=False, type='str', default=None),
        router_id=dict(required=False, type='str', default=None),
        tags=dict(required=False, type='dict', default=None),
        state=dict(required=False,
                   type='str',
                   default="present",
                   choices=['present', 'absent']),
        nsx_manager=dict(required=True, type='str'),
        nsx_username=dict(required=True, type='str'),
        nsx_passwd=dict(required=True, type='str', no_log=True)),
                           supports_check_mode=True)

    if not HAS_PYNSXT:
        module.fail_json(msg='pynsxt is required for this module')
    session = requests.session()
    session.verify = False
    nsx_url = 'https://%s:%s' % (module.params['nsx_manager'], 443)
    connector = connect.get_requests_connector(session=session,
                                               msg_protocol='rest',
                                               url=nsx_url)
    stub_config = StubConfigurationFactory.new_std_configuration(connector)
    security_context = create_user_password_security_context(
        module.params["nsx_username"], module.params["nsx_passwd"])
    connector.set_security_context(security_context)
    requests.packages.urllib3.disable_warnings()
    tags = None
    if module.params['tags'] is not None:
        tags = []
        for key, value in module.params['tags'].items():
            tag = Tag(scope=key, tag=value)
            tags.append(tag)
    lrid = ""
    if module.params['router_id']:
        lrid = module.params['router_id']
    elif module.params['router_name']:
        lr_svc = LogicalRouters(stub_config)
        lr = getLogicalRouterByName(module, stub_config)
        lrid = lr.id
    sroute = getStaticRouteByNetwork(module, stub_config, lrid)
    next_hop_list = []
    for next_hop in module.params['next_hops']:
        staticRouteNextHop = StaticRouteNextHop(
            administrative_distance=module.params['admin_distance'],
            ip_address=next_hop,
            logical_router_port_id=None)
        next_hop_list.append(staticRouteNextHop)
    sr_svc = StaticRoutes(stub_config)
    if module.params['state'] == 'present':
        if sroute is None:
            new_static_route = StaticRoute(
                display_name=None,
                network=module.params['network'],
                next_hops=next_hop_list,
                description=module.params['description'],
                tags=tags)
            if module.check_mode:
                module.exit_json(changed=True,
                                 debug_out=str(new_static_route),
                                 id="1111")
            try:
                new_static_route = sr_svc.create(lrid, new_static_route)
                module.exit_json(
                    changed=True,
                    object_name=module.params['network'],
                    id=new_static_route.id,
                    message=
                    "Static Route with for %s with id %s was created on router with id %s!"
                    % (module.params['network'], new_static_route.id, lrid))
            except Error as ex:
                module.fail_json(msg='API Error creating Static Route: %s' %
                                 (str(ex)))
        elif sroute:
            changed = False
            if tags != sroute.tags:
                sroute.tags = tags
                changed = True
            nhopList1 = simplifyNextHopList(sroute.next_hops)
            nhopList2 = simplifyNextHopList(next_hop_list)
            if nhopList1 != nhopList2:
                sroute.next_hops = next_hop_list
                changed = True
            if changed:
                if module.check_mode:
                    module.exit_json(changed=True,
                                     debug_out=str(sroute),
                                     id=lrid)
                new_static_route = sr_svc.update(lrid, sroute.id, sroute)
                module.exit_json(
                    changed=True,
                    object_name=module.params['network'],
                    id=new_static_route.id,
                    message="Static Route for %s has changed tags!" %
                    (module.params['network']))
            module.exit_json(changed=False,
                             object_name=module.params['network'],
                             id=sroute.id,
                             router_id=lrid,
                             message="Static Route for %s already exists!" %
                             (module.params['network']))

    elif module.params['state'] == "absent":
        if sroute:
            if module.check_mode:
                module.exit_json(changed=True, debug_out=str(sroute), id=lrid)
            try:
                sr_svc.delete(lrid, sroute.id)
                module.exit_json(changed=True,
                                 object_name=module.params['network'],
                                 message="Static Route for %s deleted!" %
                                 (module.params['network']))
            except Error as ex:
                api_error = ex.date.convert_to(ApiError)
                module.fail_json(msg='API Error deleting Logical Routers: %s' %
                                 (api_error.error_message))
        module.exit_json(changed=False,
                         object_name=module.params['network'],
                         message="Static Route for %s does not exist!" %
                         (module.params['network']))
コード例 #7
0
def main():
    module = AnsibleModule(argument_spec=dict(
        display_name=dict(required=True, type='str'),
        description=dict(required=False, type='str', default=None),
        failover_mode=dict(required=False,
                           type='str',
                           default=None,
                           choices=['NON_PREEMPTIVE', 'PREEMPTIVE']),
        edge_cluster_id=dict(required=False, type='str', default=None),
        high_availability_mode=dict(
            required=False,
            type='str',
            default='ACTIVE_STANDBY',
            choices=['ACTIVE_STANDBY', 'ACTIVE_ACTIVE']),
        tags=dict(required=False, type='dict', default=None),
        state=dict(required=False,
                   type='str',
                   default="present",
                   choices=['present', 'absent']),
        nsx_manager=dict(required=True, type='str'),
        nsx_username=dict(required=True, type='str'),
        nsx_passwd=dict(required=True, type='str', no_log=True)),
                           supports_check_mode=True)

    if not HAS_PYNSXT:
        module.fail_json(msg='pynsxt is required for this module')
    session = requests.session()
    session.verify = False
    nsx_url = 'https://%s:%s' % (module.params['nsx_manager'], 443)
    connector = connect.get_requests_connector(session=session,
                                               msg_protocol='rest',
                                               url=nsx_url)
    stub_config = StubConfigurationFactory.new_std_configuration(connector)
    security_context = create_user_password_security_context(
        module.params["nsx_username"], module.params["nsx_passwd"])
    connector.set_security_context(security_context)
    requests.packages.urllib3.disable_warnings()
    #tags=None
    tags = []
    tags.append(
        Tag(scope='created-by', tag=os.getenv("NSX_T_INSTALLER", "nsx-t-gen")))

    if module.params['tags'] is not None:
        #tags = []
        for key, value in module.params['tags'].items():
            tag = Tag(scope=key, tag=value)
            tags.append(tag)
    lr_svc = LogicalRouters(stub_config)
    lr = getLogicalRouterByName(module, stub_config)
    if module.params['state'] == 'present':
        if lr is None:
            tags.append(
                Tag(scope='generated',
                    tag=time.strftime("%Y-%m-%d %H:%M:%S %z")))
            new_lr = LogicalRouter(
                display_name=module.params['display_name'],
                description=module.params['description'],
                failover_mode=module.params['failover_mode'],
                edge_cluster_id=module.params['edge_cluster_id'],
                router_type='TIER0',
                high_availability_mode=module.params['high_availability_mode'],
                tags=tags)
            if module.check_mode:
                module.exit_json(changed=True,
                                 debug_out=str(new_lr),
                                 id="1111")
            try:
                new_lr = lr_svc.create(new_lr)
                module.exit_json(
                    changed=True,
                    object_name=module.params['display_name'],
                    id=new_lr.id,
                    message="Logical Router with name %s created!" %
                    (module.params['display_name']))
            except Error as ex:
                module.fail_json(msg='API Error listing Logical Routers: %s' %
                                 (str(ex)))
        elif lr:
            #if tags != lr.tags:
            if not compareTags(lr.tags, tags):
                tags.append(findTag(lr.tags, 'generated'))
                tags.append(
                    Tag(scope='modified',
                        tag=time.strftime("%Y-%m-%d %H:%M:%S %z")))
                lr.tags = tags
                if module.check_mode:
                    module.exit_json(changed=True, debug_out=str(lr), id=lr.id)
                new_lr = lr_svc.update(lr.id, lr)
                module.exit_json(
                    changed=True,
                    object_name=module.params['display_name'],
                    id=new_lr.id,
                    message="Logical Router with name %s has changed tags!" %
                    (module.params['display_name']))
            module.exit_json(
                changed=False,
                object_name=module.params['display_name'],
                id=lr.id,
                message="Logical Router with name %s already exists!" %
                (module.params['display_name']))

    elif module.params['state'] == "absent":

        if lr:
            if module.check_mode:
                module.exit_json(changed=True, debug_out=str(lr), id=lr.id)
            try:
                deleteAllPortsOnRouter(lr, module, stub_config)
                lr_svc.delete(lr.id)
            except Error as ex:
                api_error = ex.date.convert_to(ApiError)
                module.fail_json(msg='API Error deleting Logical Routers: %s' %
                                 (api_error.error_message))

            module.exit_json(changed=True,
                             object_name=module.params['display_name'],
                             message="Logical Router with name %s deleted!" %
                             (module.params['display_name']))
        module.exit_json(
            changed=False,
            object_name=module.params['display_name'],
            message="Logical Router with name %s does not exist!" %
            (module.params['display_name']))
コード例 #8
0
def main():
    module = AnsibleModule(argument_spec=dict(
        display_name=dict(required=True, type='str'),
        description=dict(required=False, type='str', default=None),
        edge_cluster_member=dict(required=True, type='str'),
        ip_address=dict(required=True, type='str'),
        t0_router=dict(required=True, type='str'),
        logical_switch_port_id=dict(required=True, type='str'),
        urpf=dict(required=False,
                  type='str',
                  default='NONE',
                  choices=['NONE', 'STRICT']),
        tags=dict(required=False, type='dict', default=None),
        state=dict(required=False,
                   type='str',
                   default="present",
                   choices=['present', 'absent']),
        nsx_manager=dict(required=True, type='str'),
        nsx_username=dict(required=True, type='str'),
        nsx_passwd=dict(required=True, type='str', no_log=True)),
                           supports_check_mode=True)

    if not HAS_PYNSXT:
        module.fail_json(msg='pynsxt is required for this module')
    session = requests.session()
    session.verify = False
    nsx_url = 'https://%s:%s' % (module.params['nsx_manager'], 443)
    connector = connect.get_requests_connector(session=session,
                                               msg_protocol='rest',
                                               url=nsx_url)
    stub_config = StubConfigurationFactory.new_std_configuration(connector)
    security_context = create_user_password_security_context(
        module.params["nsx_username"], module.params["nsx_passwd"])
    connector.set_security_context(security_context)
    requests.packages.urllib3.disable_warnings()
    tags = None
    if module.params['tags'] is not None:
        tags = []
        for key, value in module.params['tags'].items():
            tag = Tag(scope=key, tag=value)
            tags.append(tag)
    lr_svc = LogicalRouters(stub_config)
    lr = getLogicalRouterByName(module, stub_config)
    ec_svc = EdgeClusters(stub_config)
    edgeCluster = ec_svc.get(lr.edge_cluster_id)

    tn = getTransportNodeByName(module, stub_config)
    member_index = []
    for member in edgeCluster.members:
        if member.transport_node_id == tn.id:
            member_index.append(int(member.member_index))

    subnet_list = []
    subnet = module.params['ip_address'].split('/')
    new_subnet = IPSubnet(ip_addresses=[subnet[0]],
                          prefix_length=int(subnet[1]))
    subnet_list.append(new_subnet)
    lrp_svc = LogicalRouterPorts(stub_config)
    lrp = getLogicalRouterPortByName(module, stub_config, lr.id)
    if module.params['state'] == 'present':
        if lrp is None:
            new_lrp = LogicalRouterUpLinkPort(
                display_name=module.params['display_name'],
                description=module.params['description'],
                edge_cluster_member_index=member_index,
                linked_logical_switch_port_id=ResourceReference(
                    target_id=module.params['logical_switch_port_id']),
                subnets=subnet_list,
                urpf_mode=module.params['urpf'],
                logical_router_id=lr.id,
                tags=tags)
            if module.check_mode:
                module.exit_json(changed=True,
                                 debug_out=str(new_lrp),
                                 id="1111")
            try:
                lrp_temp = lrp_svc.create(new_lrp)
                new_lrp = lrp_temp.convert_to(LogicalRouterUpLinkPort)
                module.exit_json(
                    changed=True,
                    object_name=module.params['display_name'],
                    id=new_lrp.id,
                    message="Logical Router Port with name %s created!" %
                    (module.params['display_name']))
            except Error as ex:
                api_error = ex.data.convert_to(ApiError)
                module.fail_json(
                    msg='API Error creating Logical Router Uplink: %s' %
                    (str(api_error.error_message)))
        elif lrp:
            changed = False
            if lrp.linked_logical_switch_port_id.target_id != module.params[
                    'logical_switch_port_id']:
                changed = True
                lrp.linked_logical_switch_port_id = ResourceReference(
                    target_id=module.params['logical_switch_port_id'])
            if tags != lrp.tags:
                changed = True
                lrp.tags = tags
            if subnet_list != lrp.subnets:
                changed = True
                lrp.subnets = subnet_list
            if member_index != lrp.edge_cluster_member_index:
                changed = True
                lrp.edge_cluster_member_index = member_index
            if changed:
                if module.check_mode:
                    module.exit_json(changed=True,
                                     debug_out=str(lrp),
                                     id=lrp.id)
                new_lr = lrp_svc.update(lrp.id, lrp)
                module.exit_json(
                    changed=True,
                    object_name=module.params['display_name'],
                    id=lrp.id,
                    message=
                    "Logical Router Uplink with name %s has been changed!" %
                    (module.params['display_name']))
            module.exit_json(
                changed=False,
                object_name=module.params['display_name'],
                id=lrp.id,
                message="Logical Router Uplink with name %s already exists!" %
                (module.params['display_name']))

    elif module.params['state'] == "absent":

        if lrp:
            if module.check_mode:
                module.exit_json(changed=True, debug_out=str(lrp), id=lrp.id)
            try:
                lrp_svc.delete(lrp.id, force=True)
            except Error as ex:
                api_error = ex.date.convert_to(ApiError)
                module.fail_json(
                    msg='API Error deleting Logical Router Ports: %s' %
                    (api_error.error_message))

            module.exit_json(
                changed=True,
                object_name=module.params['display_name'],
                message="Logical Router Port with name %s deleted!" %
                (module.params['display_name']))
        module.exit_json(
            changed=False,
            object_name=module.params['display_name'],
            message="Logical Router Port with name %s does not exist!" %
            (module.params['display_name']))
コード例 #9
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            display_name=dict(required=True, type='str'),
            description=dict(required=False, type='str', default=None),
            failover_mode=dict(required=False, type='str', default=None, choices=['NON_PREEMPTIVE', 'PREEMPTIVE']),
            edge_cluster_id=dict(required=False, type='str', default=None),
            connected_t0_id=dict(required=False, type='str', default=None),
            high_availability_mode=dict(required=False, type='str', default='ACTIVE_STANDBY', choices=['ACTIVE_STANDBY', 'ACTIVE_ACTIVE']),
            advertise=dict(required=False, type='dict', default=None),
            tags=dict(required=False, type='dict', default=None),
            state=dict(required=False, type='str', default="present", choices=['present', 'absent']),
            nsx_manager=dict(required=True, type='str'),
            nsx_username=dict(required=True, type='str'),
            nsx_passwd=dict(required=True, type='str', no_log=True)
        ),
        supports_check_mode=True
    )

    if not HAS_PYNSXT:
        module.fail_json(msg='pynsxt is required for this module')
    session = requests.session()
    session.verify = False
    nsx_url = 'https://%s:%s' % (module.params['nsx_manager'], 443)
    connector = connect.get_requests_connector(
        session=session, msg_protocol='rest', url=nsx_url)
    stub_config = StubConfigurationFactory.new_std_configuration(connector)
    security_context = create_user_password_security_context(module.params["nsx_username"], module.params["nsx_passwd"])
    connector.set_security_context(security_context)
    requests.packages.urllib3.disable_warnings()
    desired_adv_config = AdvertisementConfig()
    if module.params['advertise']:
        if 'enabled' in module.params['advertise']:
            desired_adv_config.enabled = module.params['advertise']['enabled']
        else:
            desired_adv_config.enabled = True
        if 'advertise_lb_snat_ip' in module.params['advertise'] and module.params['advertise']['advertise_lb_snat_ip']:
            desired_adv_config.advertise_lb_snat_ip = module.params['advertise']['advertise_lb_snat_ip']
        if 'advertise_lb_vip' in module.params['advertise'] and module.params['advertise']['advertise_lb_vip']:
            desired_adv_config.advertise_lb_vip = module.params['advertise']['advertise_lb_vip']
        if 'advertise_nat_routes' in module.params['advertise'] and module.params['advertise']['advertise_nat_routes']:
            desired_adv_config.advertise_nat_routes = module.params['advertise']['advertise_nat_routes']
        if 'advertise_nsx_connected_routes' in module.params['advertise'] and module.params['advertise']['advertise_nsx_connected_routes']:
            desired_adv_config.advertise_nsx_connected_routes = module.params['advertise']['advertise_nsx_connected_routes']
        if 'advertise_static_routes' in module.params['advertise'] and module.params['advertise']['advertise_static_routes']:
            desired_adv_config.advertise_static_routes = module.params['advertise']['advertise_static_routes']

    tags=None
    if module.params['tags'] is not None:
        tags = []
        for key, value in module.params['tags'].items():
            tag=Tag(scope=key, tag=value)
            tags.append(tag)
    lr_svc = LogicalRouters(stub_config)
    lr = getLogicalRouterByName(module, stub_config)
    if module.params['state'] == 'present':
        if lr is None:
            new_lr = LogicalRouter(
                display_name=module.params['display_name'],
                description=module.params['description'],
                failover_mode=module.params['failover_mode'],
                edge_cluster_id=module.params['edge_cluster_id'],
                router_type='TIER1',
                high_availability_mode=module.params['high_availability_mode'],
                tags=tags
            )
            if module.check_mode:
                module.exit_json(changed=True, debug_out=str(new_lr), id="1111")
            try:
                new_lr = lr_svc.create(new_lr)
                mylr = getLogicalRouterByName(module, stub_config)
                if module.params['connected_t0_id']:
                    connectT0(mylr, module, stub_config)
                if module.params['advertise']:
                    adv_svc = Advertisement(stub_config)
                    adv_config = adv_svc.get(mylr.id)
                    adv_config.enabled = desired_adv_config.enabled
                    adv_config.advertise_lb_snat_ip = desired_adv_config.advertise_lb_snat_ip
                    adv_config.advertise_lb_vip = desired_adv_config.advertise_lb_vip
                    adv_config.advertise_nat_routes = desired_adv_config.advertise_nat_routes
                    adv_config.advertise_nsx_connected_routes = desired_adv_config.advertise_nsx_connected_routes
                    adv_config.advertise_static_routes = desired_adv_config.advertise_static_routes
                    adv_svc.update(mylr.id, adv_config)
                module.exit_json(changed=True, object_name=module.params['display_name'], id=mylr.id, message="Logical Router with name %s created!"%(module.params['display_name']))
            except Error as ex:
                module.fail_json(msg='API Error listing Logical Routers: %s'%(str(ex)))
        elif lr:
            adv_svc = Advertisement(stub_config)
            adv_config = adv_svc.get(lr.id)
            changed = False
            if tags != lr.tags:
                changed = True
                lr.tags=tags
            if module.params['edge_cluster_id'] != lr.edge_cluster_id:
                lr.edge_cluster_id=module.params['edge_cluster_id']
                changed = True
            if changed:
                if module.check_mode:
                    module.exit_json(changed=True, debug_out=str(lr), id=lr.id)
                new_lr = lr_svc.update(lr.id, lr)
                module.exit_json(changed=True, object_name=module.params['display_name'], id=new_lr.id, message="Logical Router with name %s has been modified!"%(module.params['display_name']))
            if compareLrpT0T1(lr, module, stub_config):
                module.exit_json(changed=True, object_name=module.params['display_name'], id=lr.id, message="Logical Router uplink on T1 with name %s has been modified!"%(module.params['display_name']))
            if module.params['advertise']:
                changed = False
                if ('enabled' not in module.params['advertise']):
                    changed = False
                elif module.params['advertise']['enabled'] != adv_config.enabled:
                    adv_config.enabled = desired_adv_config.enabled
                    changed = True
                if ('advertise_lb_snat_ip' not in module.params['advertise']):
                    if adv_config.advertise_lb_snat_ip:
                        adv_config.advertise_lb_snat_ip = None
                        changed = True
                elif module.params['advertise']['advertise_lb_snat_ip'] != adv_config.advertise_lb_snat_ip:
                    adv_config.advertise_lb_snat_ip = desired_adv_config.advertise_lb_snat_ip
                    changed = True

                if ('advertise_lb_vip' not in module.params['advertise']):
                    if adv_config.advertise_lb_vip:
                        adv_config.advertise_lb_vip = None
                        changed = True
                elif module.params['advertise']['advertise_lb_vip'] != adv_config.advertise_lb_vip:
                    adv_config.advertise_lb_vip = desired_adv_config.advertise_lb_vip
                    changed = True
 
                if ('advertise_nat_routes' not in module.params['advertise']):
                    if adv_config.advertise_nat_routes:
                        adv_config.advertise_nat_routes = None
                        changed = True
                elif module.params['advertise']['advertise_nat_routes'] != adv_config.advertise_nat_routes:
                    adv_config.advertise_nat_routes = desired_adv_config.advertise_nat_routes
                    changed = True

                if ('advertise_nsx_connected_routes' not in module.params['advertise']):
                    if adv_config.advertise_nsx_connected_routes:
                        adv_config.advertise_nsx_connected_routes = None
                        changed = True
                elif module.params['advertise']['advertise_nsx_connected_routes'] != adv_config.advertise_nsx_connected_routes:
                    adv_config.advertise_nsx_connected_routes = desired_adv_config.advertise_nsx_connected_routes
                    changed = True

                if ('advertise_static_routes' not in module.params['advertise']):
                    if adv_config.advertise_static_routes:
                        adv_config.advertise_static_routes = None
                        changed = True
                elif module.params['advertise']['advertise_static_routes'] != adv_config.advertise_static_routes:
                    adv_config.advertise_static_routes = desired_adv_config.advertise_static_routes
                    changed = True

                if changed:
                    if module.check_mode:
                        module.exit_json(changed=True, debug_out=str(adv_config), id=lr.id)
                    adv_svc.update(lr.id, adv_config)
                    module.exit_json(changed=True, object_name=module.params['display_name'], id=lr.id, message="Logical Router advertisement config on T1 with name %s has been modified!"%(module.params['display_name']))

            module.exit_json(changed=False, object_name=module.params['display_name'], id=lr.id, message="Logical Router with name %s already exists!"%(module.params['display_name']))

    elif module.params['state'] == "absent":
        if lr:
            if module.check_mode:
                module.exit_json(changed=True, debug_out=str(lr), id=lr.id)
            try:
                deleteAllPortsOnRouter(lr, module, stub_config)
                lr_svc.delete(lr.id)
            except Error as ex:
                api_error = ex.date.convert_to(ApiError)
                module.fail_json(msg='API Error deleting Logical Routers: %s'%(api_error.error_message))


            module.exit_json(changed=True, object_name=module.params['display_name'], message="Logical Router with name %s deleted!"%(module.params['display_name']))
        module.exit_json(changed=False, object_name=module.params['display_name'], message="Logical Router with name %s does not exist!"%(module.params['display_name']))
コード例 #10
0
def main():
    args = getargs.getargs()
    stub_config = auth.get_session_auth_stub_config(args.user, args.password,
                                                    args.nsx_host,
                                                    args.tcp_port)

    pp = PrettyPrinter()

    # Instantiate all the services we'll need.
    transportzones_svc = TransportZones(stub_config)
    logicalswitches_svc = LogicalSwitches(stub_config)
    logicalrouters_svc = LogicalRouters(stub_config)
    logicalrouterports_svc = LogicalRouterPorts(stub_config)
    logicalports_svc = LogicalPorts(stub_config)
    fwsections_svc = Sections(stub_config)

    # Create a transport zone
    new_tz = TransportZone(
        transport_type=TransportZone.TRANSPORT_TYPE_OVERLAY,
        display_name="Two Tier App Demo Transport Zone",
        description="Transport zone for two-tier app demo",
        host_switch_name="hostswitch"
    )
    demo_tz = transportzones_svc.create(new_tz)

    # Create a logical switch for the db tier
    new_ls = LogicalSwitch(
        transport_zone_id=demo_tz.id,
        admin_state=LogicalSwitch.ADMIN_STATE_UP,
        replication_mode=LogicalSwitch.REPLICATION_MODE_MTEP,
        display_name="ls-db",
    )
    db_ls = logicalswitches_svc.create(new_ls)

    # Create a logical switch for the web tier
    new_ls = LogicalSwitch(
        transport_zone_id=demo_tz.id,
        admin_state=LogicalSwitch.ADMIN_STATE_UP,
        replication_mode=LogicalSwitch.REPLICATION_MODE_MTEP,
        display_name="ls-web",
    )
    web_ls = logicalswitches_svc.create(new_ls)

    # Create a logical router that will route traffic between
    # the web and db tiers
    new_lr = LogicalRouter(
        router_type=LogicalRouter.ROUTER_TYPE_TIER1,
        display_name="lr-demo",
        failover_mode=LogicalRouter.FAILOVER_MODE_PREEMPTIVE
    )
    lr = logicalrouters_svc.create(new_lr)

    # Create a logical port on the db and web logical switches. We
    # will attach the logical router to those ports so that it can
    # route between the logical switches.
    # Logical port on the db logical switch
    new_lp = LogicalPort(
        admin_state=LogicalPort.ADMIN_STATE_UP,
        logical_switch_id=db_ls.id,
        display_name="dbTierUplinkToRouter"
    )
    db_port_on_ls = logicalports_svc.create(new_lp)

    # Logical port on the web logical switch
    new_lp = LogicalPort(
        admin_state=LogicalPort.ADMIN_STATE_UP,
        logical_switch_id=web_ls.id,
        display_name="webTierUplinkToRouter"
    )
    web_port_on_ls = logicalports_svc.create(new_lp)

    # Populate a logical router downlink port payload and configure
    # the port with the CIDR 192.168.1.1/24. We will attach this
    # port to the db tier's logical switch.
    new_lr_port = LogicalRouterDownLinkPort(
        subnets=[IPSubnet(ip_addresses=["192.168.1.1"], prefix_length=24)],
        linked_logical_switch_port_id=ResourceReference(
            target_id=db_port_on_ls.id),
        resource_type="LogicalRouterDownLinkPort",
        logical_router_id=lr.id
    )
    # Create the downlink port
    lr_port_for_db_tier = logicalrouterports_svc.create(new_lr_port)
    # Convert to concrete type
    lr_port_for_db_tier = lr_port_for_db_tier.convert_to(
        LogicalRouterDownLinkPort)

    # Populate a logical router downlink port payload and configure
    # the port with the CIDR 192.168.2.1/24. We will attach this
    # port to the web tier's logical switch.
    new_lr_port = LogicalRouterDownLinkPort(
        subnets=[IPSubnet(ip_addresses=["192.168.2.1"], prefix_length=24)],
        linked_logical_switch_port_id=ResourceReference(
            target_id=web_port_on_ls.id),
        resource_type="LogicalRouterDownLinkPort",
        logical_router_id=lr.id
    )
    # Create the downlink port
    lr_port_for_web_tier = logicalrouterports_svc.create(new_lr_port)
    lr_port_for_web_tier = lr_port_for_web_tier.convert_to(
        LogicalRouterDownLinkPort)

    # Now establish a firewall policy that only allows MSSQL
    # server traffic and ICMP traffic in and out of the db tier's
    # logical switch.

    # Create 3 firewall rules. The first will allow traffic used
    # by MS SQL Server to pass. This rule references a built-in
    # ns service group that includes all the common ports used by
    # the MSSQL Server. The ID is common to all NSX installations.
    MSSQL_SERVER_NS_GROUP_ID = "5a6d380a-6d28-4e3f-b705-489f463ae6ad"
    ms_sql_rule = FirewallRule(
        action=FirewallRule.ACTION_ALLOW,
        display_name="Allow MSSQL Server",
        ip_protocol=FirewallRule.IP_PROTOCOL_IPV4_IPV6,
        services=[
            FirewallService(
                target_type="NSServiceGroup",
                target_id=MSSQL_SERVER_NS_GROUP_ID
            )
        ]
    )

    # The second rule will allow ICMP echo requests and responses.
    ICMP_ECHO_REQUEST_NS_SVC_ID = "5531a880-61aa-42cc-ba4b-13b9ea611e2f"
    ICMP_ECHO_REPLY_NS_SVC_ID = "c54b2d86-6327-41ff-a3fc-c67171b6ba63"
    icmp_rule = FirewallRule(
        action=FirewallRule.ACTION_ALLOW,
        display_name="Allow ICMP Echo",
        ip_protocol=FirewallRule.IP_PROTOCOL_IPV4_IPV6,
        services=[
            FirewallService(
                target_type="NSService",
                target_id=ICMP_ECHO_REQUEST_NS_SVC_ID
            ),
            FirewallService(
                target_type="NSService",
                target_id=ICMP_ECHO_REPLY_NS_SVC_ID
            )
        ]
    )

    # The third rule will drop all traffic not passed by the previous
    # rules.
    block_all_rule = FirewallRule(
        action=FirewallRule.ACTION_DROP,
        display_name="Drop all",
        ip_protocol=FirewallRule.IP_PROTOCOL_IPV4_IPV6
    )

    # Add all rules to a new firewall section and create the section.
    rule_list = FirewallSectionRuleList(
        rules=[ms_sql_rule, icmp_rule, block_all_rule],
        section_type=FirewallSection.SECTION_TYPE_LAYER3,
        stateful=True,
        display_name="MSSQL Server",
        description="Only allow MSSQL server traffic"
    )
    demo_section = fwsections_svc.createwithrules(
        rule_list, None, operation="insert_top")

    # Re-read the firewall section so that we are operating on up-to-date
    # data.
    section = fwsections_svc.get(demo_section.id)

    # Make the firewall section apply to the db tier logical
    # switch. This enables the firewall policy on all logical
    # ports attached to the db tier logical switch.
    section.applied_tos = [
        ResourceReference(target_id=db_ls.id,
                          target_type="LogicalSwitch")
    ]
    fwsections_svc.update(section.id, section)

    print("At this point you may attach VMs for the db tier to the db")
    print("logical switch and VMs for the web tier to the web logical")
    print("switch. The network interfaces should be configured as")
    print("follows:")
    print("db tier:")
    print("    IP address: in the range 192.168.1.2-254")
    print("    Netmask: 255.255.255.0")
    print("    Default route: 192.168.1.1")
    print("web tier:")
    print("    IP address: in the range 192.168.2.2-254")
    print("    Netmask: 255.255.255.0")
    print("    Default route: 192.168.2.1")
    print("Logical switch IDs:")
    print("    %s: %s" % (db_ls.display_name, db_ls.id))
    print("    %s: %s" % (web_ls.display_name, web_ls.id))
    print("Transport zone: %s: %s" % (demo_tz.display_name, demo_tz.id))

    print("Press enter to delete all resources created for this example.")
    sys.stdin.readline()

    fwsections_svc.delete(section.id, cascade=True)
    logicalrouterports_svc.delete(lr_port_for_web_tier.id)
    logicalrouterports_svc.delete(lr_port_for_db_tier.id)
    logicalports_svc.delete(web_port_on_ls.id)
    logicalports_svc.delete(db_port_on_ls.id)
    logicalrouters_svc.delete(lr.id)
    logicalswitches_svc.delete(web_ls.id)
    logicalswitches_svc.delete(db_ls.id)
    transportzones_svc.delete(demo_tz.id)