def main(): session = requests.session() session.verify = False nsx_url = 'https://%s:%s' % ("<NSX MANAGER IP>", 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("<USERNAME>", "<PASSWORD>") connector.set_security_context(security_context) urllib3.disable_warnings() tz_list = [] tz_svc = TransportZones(stub_config) tz_list = tz_svc.list() r = tz_list.results start_row = 1 for i in r: tz = i.convert_to(TransportZone) sheet1.write(start_row, 0, tz.display_name) sheet1.write(start_row, 1, tz.description) sheet1.write(start_row, 2, tz.id) sheet1.write(start_row, 3, tz.resource_type) sheet1.write(start_row, 4, tz.host_switch_id) sheet1.write(start_row, 5, tz.host_switch_mode) sheet1.write(start_row, 6, tz.host_switch_name) sheet1.write(start_row, 7, tz.is_default) sheet1.write(start_row, 8, tz.nested_nsx) sheet1.write(start_row, 9, tz.transport_type) sheet1.write(start_row, 10,tz.uplink_teaming_policy_names) start_row += 1 ls_wkbk.save('Transport Zones.xls')
def main(): args = getargs.getargs() stub_config = auth.get_session_auth_stub_config(args.user, args.password, args.nsx_host, args.tcp_port) # Create a pretty printer to make the output look nice. pp = PrettyPrinter() # Create the service we'll need. transportzones_svc = TransportZones(stub_config) # Create a transport zone, but intentionally pass an incorrect # overlay type, so we cause an error. new_tz = TransportZone( transport_type="zappa", # invalid overlay type display_name="My transport zone", description="Transport zone for error handling demo", host_switch_name="hostswitch1" ) try: result_tz = transportzones_svc.create(new_tz) except Error as ex: api_error = ex.data.convert_to(ApiError) print("An error occurred: %s" % api_error.error_message)
def main(): # Read the command-line arguments. The args object will contain # 4 properties, args.nsx_host, args.tcp_port, args.user, and # args.password. args = getargs.getargs() # Create a session using the requests library. For more information on # requests, see http://docs.python-requests.org/en/master/ session = requests.session() # If your NSX API server is using its default self-signed certificate, # you will need the following line, otherwise the python ssl layer # will reject the server certificate. THIS IS UNSAFE and you should # normally verify the server certificate. session.verify = False # Set up the API connector and security context nsx_url = 'https://%s:%s' % (args.nsx_host, args.tcp_port) 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( args.user, args.password) connector.set_security_context(security_context) # Now any API calls we make should authenticate to NSX using # HTTP Basic Authentication. Let's get a list of all Transport Zones. transportzones_svc = TransportZones(stub_config) tzs = transportzones_svc.list() # Create a pretty printer to make the output look nice. pp = PrettyPrinter() pp.pprint(tzs)
def SheetSegments(auth_list,WORKBOOK,TN_WS,NSX_Config = {}): NSX_Config['Segments'] = [] Dict_LS = {} # NSX Connection SessionNSX = ConnectNSX(auth_list) stub_config = StubConfigurationFactory.new_std_configuration(SessionNSX[1]) ls_svc = LogicalSwitches(stub_config) ls_list = ls_svc.list() nb = len(ls_list.results) tz_svc = TransportZones(stub_config) tz_list = tz_svc.list() XLS_Lines = [] TN_HEADER_ROW = ('Segments', 'VNI', 'VLAN', 'Transport Zone Name', 'Transport Zone Type', 'Replication Mode', 'Admin State') if ls_list.result_count > 0: while True: for segment in ls_list.results: TZ_NAME = "" TZ_Type = "" for tz in tz_list.results: if segment.transport_zone_id == tz.id: TZ_NAME = tz.display_name TZ_Type = tz.transport_type Dict_LS['segment_name'] = segment.display_name Dict_LS['vni'] = segment.vni Dict_LS['vlan'] = segment.vlan Dict_LS['tz_name'] = TZ_NAME Dict_LS['tz_type'] = TZ_Type Dict_LS['replication_mode'] = segment.replication_mode Dict_LS['status'] = segment.admin_state NSX_Config['Segments'].append(Dict_LS) XLS_Lines.append([segment.display_name, segment.vni, segment.vlan, TZ_NAME, TZ_Type, segment.replication_mode,segment.admin_state]) if ls_list.cursor is None: break else: print(" --> more than " + str(nb) + " results for " + style.RED + "Segments" + style.NORMAL + " - please wait") ls_list = LogicalSwitches(stub_config).list(cursor =ls_list.cursor ) nb = len(ls_list.results) + nb else: XLS_Lines.append(["no Segments", "", "", "", "", "",""]) if GetOutputFormat() == 'CSV': CSV = WORKBOOK FillSheetCSV(CSV,TN_HEADER_ROW,XLS_Lines) elif GetOutputFormat() == 'JSON': JSON = WORKBOOK FillSheetJSON(JSON, NSX_Config) elif GetOutputFormat() == 'YAML': YAML = WORKBOOK FillSheetYAML(YAML, NSX_Config) else: FillSheet(WORKBOOK,TN_WS.title,TN_HEADER_ROW,XLS_Lines,"0072BA") ConditionnalFormat(TN_WS, 'G2:G' + str(len(XLS_Lines) + 1), 'UP')
def listTransportZones(module, stub_config): tz_list = [] try: tz_svc = TransportZones(stub_config) tz_list = tz_svc.list() except Error as ex: api_error = ex.date.convert_to(ApiError) module.fail_json(msg='API Error listing Transport Zones: %s'%(api_error.error_message)) return tz_list
def getTransportZoneEndPoint(module, stub_config): tz_endpoints = [] transportzones_svc = TransportZones(stub_config) try: tzs = transportzones_svc.list() except Error as ex: api_error = ex.data.convert_to(ApiError) module.exit_json(changed=False, message="Error listing Transport Zones: "%(api_error)) for tz_name in module.params['transport_zone_endpoints']: for vs in tzs.results: fn = vs.convert_to(TransportZone) if fn.display_name == tz_name: ep=TransportZoneEndPoint(transport_zone_id=fn.id) tz_endpoints.append(ep) return tz_endpoints
def SheetTZ(auth_list,WORKBOOK,TN_WS, NSX_Config ={} ): NSX_Config['TZ'] = [] Dict_TZ = {} # Connect NSX SessionNSX = ConnectNSX(auth_list) stub_config = StubConfigurationFactory.new_std_configuration(SessionNSX[1]) XLS_Lines = [] TN_HEADER_ROW = ('Name', 'Description', 'ID', 'Ressource Type', 'Host Switch ID', 'Hos Switch Mode', 'Host Switch Name', 'Host Switch is Default', 'is Nested NSX', 'Transport Type', 'Uplink Teaming Policy Name') tz_list = TransportZones(stub_config).list() for TZ in tz_list.results: tz = TZ.convert_to(TransportZone) if tz.uplink_teaming_policy_names is not None: TZ_Teaming = "\n".join(tz.uplink_teaming_policy_names) else: TZ_Teaming = "" Dict_TZ['name'] = tz.display_name Dict_TZ['description'] = tz.description Dict_TZ['id'] = tz.id Dict_TZ['resource_type'] = tz.resource_type Dict_TZ['host_swithc_id'] = tz.host_switch_id Dict_TZ['host_switch_mode'] = tz.host_switch_mode Dict_TZ['host_switch_name'] = tz.host_switch_name Dict_TZ['is_default'] = tz.is_default Dict_TZ['nested'] = tz.nested_nsx Dict_TZ['type'] = tz.transport_type Dict_TZ['teaming'] = tz.uplink_teaming_policy_names NSX_Config['TZ'].append(Dict_TZ) # Create line XLS_Lines.append([tz.display_name, tz.description, tz.id, tz.resource_type, tz.host_switch_id, tz.host_switch_mode, tz.host_switch_name, tz.is_default, tz.nested_nsx, tz.transport_type, TZ_Teaming]) FillSheet(WORKBOOK,TN_WS.title,TN_HEADER_ROW,XLS_Lines,"0072BA")
def main(): session = requests.session() session.verify = False nsx_url = 'https://%s:%s' % ("<NSX-T MANAGER FQDN>", 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( "<USERNAME>", "<PASSWORD>") connector.set_security_context(security_context) urllib3.disable_warnings() ls_list = [] ls_svc = LogicalSwitches(stub_config) ls_list = ls_svc.list() # print(ls_list) tz_list = [] tz_svc = TransportZones(stub_config) tz_list = tz_svc.list() start_row = 1 for vs in ls_list.results: ls = vs.convert_to(LogicalSwitch) sheet1.write(start_row, 0, ls.display_name) sheet1.write(start_row, 1, ls.vni, style_alignleft) sheet1.write(start_row, 2, ls.vlan, style_alignleft) sheet1.write(start_row, 4, ls.transport_zone_id) sheet1.write(start_row, 6, ls.replication_mode) sheet1.write(start_row, 7, ls.admin_state) # print(ls.resource_type) newlist = [] for i in range(len(ls.tags)): newlist.append(ls.tags[i].tag) sheet1.write(start_row, 8, (str(newlist[0]))) if len(newlist) > 1: sheet1.write(start_row, 9, (str(newlist.pop()))) x = len(tz_list.results) for i in range(0, x): if ls.transport_zone_id == tz_list.results[i].id: sheet1.write(start_row, 3, tz_list.results[i].display_name) sheet1.write(start_row, 5, tz_list.results[i].transport_type) start_row += 1 ls_wkbk.save('Logical Switches.xls')
def main(): # Read the command-line arguments. arg_parser = argparse.ArgumentParser() arg_parser.add_argument('-n', '--nsx_host', type=str, required=True, help='NSX host to connect to') arg_parser.add_argument('-t', '--tcp_port', type=int, default=443, help='TCP port for NSX server') arg_parser.add_argument('-c', '--client_certificate', type=str, required=True, help='Name of PEM file containing client ' 'certificate and private key') args = arg_parser.parse_args() # Create a session using the requests library. For more information on # requests, see http://docs.python-requests.org/en/master/ session = requests.session() # If your NSX API server is using its default self-signed certificate, # you will need the following line, otherwise the python ssl layer # will reject the server certificate. THIS IS UNSAFE and you should # normally verify the server certificate. session.verify = False # Configure the requests library to supply a client certificate session.cert = args.client_certificate # Set up the API connector nsx_url = 'https://%s:%s' % (args.nsx_host, args.tcp_port) connector = connect.get_requests_connector( session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) # Now any API calls we make should authenticate to NSX using # the client certificate. Let's get a list of all Transport Zones. transportzones_svc = TransportZones(stub_config) tzs = transportzones_svc.list() # Create a pretty printer to make the output look nice. pp = PrettyPrinter() pp.pprint(tzs)
def main(): module = AnsibleModule(argument_spec=dict( display_name=dict(required=True, type='str'), description=dict(required=False, type='str', default=None), host_switch_mode=dict(required=False, type='str', default='STANDARD', choices=['STANDARD', 'ENS']), host_switch_name=dict(required=True, type='str'), nested_nsx=dict(required=False, type='bool', default=False), transport_type=dict(required=False, type='str', default='OVERLAY', choices=['OVERLAY', 'VLAN']), 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) transportzones_svc = TransportZones(stub_config) tz = getTransportZoneByName(module, stub_config) if module.params['state'] == 'present': if tz is None: tags.append( Tag(scope='generated', tag=time.strftime("%Y-%m-%d %H:%M:%S %z"))) new_tz = TransportZone( transport_type=module.params['transport_type'], display_name=module.params['display_name'], description=module.params['description'], host_switch_name=module.params['host_switch_name'], host_switch_mode=module.params['host_switch_mode'], nested_nsx=module.params['nested_nsx'], tags=tags) if module.check_mode: module.exit_json(changed=True, debug_out=str(new_tz), id="1111") new_tz = transportzones_svc.create(new_tz) module.exit_json(changed=True, object_name=module.params['display_name'], id=new_tz.id, message="Transport Zone with name %s created!" % (module.params['display_name'])) elif tz: #if tags != tz.tags: if not compareTags(tz.tags, tags): tags.append(findTag(tz.tags, 'generated')) tags.append( Tag(scope='modified', tag=time.strftime("%Y-%m-%d %H:%M:%S %z"))) tz.tags = tags if module.check_mode: module.exit_json(changed=True, debug_out=str(tz), id=tz.id) new_tz = transportzones_svc.update(tz.id, tz) module.exit_json( changed=True, object_name=module.params['display_name'], id=new_tz.id, message="Transport Zone with name %s has changed tags!" % (module.params['display_name'])) module.exit_json( changed=False, object_name=module.params['display_name'], id=tz.id, message="Transport Zone with name %s already exists!" % (module.params['display_name'])) elif module.params['state'] == "absent": if tz: if module.check_mode: module.exit_json(changed=True, debug_out=str(tz), id=tz.id) transportzones_svc.delete(tz.id) module.exit_json(changed=True, object_name=module.params['display_name'], message="Transport Zone with name %s deleted!" % (module.params['display_name'])) module.exit_json(changed=False, object_name=module.params['display_name'], message="Transport Zone with name %s doe not exist!" % (module.params['display_name']))
def main(): args = getargs.getargs() stub_config = auth.get_session_auth_stub_config(args.user, args.password, args.nsx_host, args.tcp_port) # Create a pretty printer to make the output look nice. pp = PrettyPrinter() # Create the services we'll need. transportzones_svc = TransportZones(stub_config) logicalswitches_svc = LogicalSwitches(stub_config) logicalports_svc = LogicalPorts(stub_config) nsgroups_svc = NsGroups(stub_config) efflports_svc = EffectiveLogicalPortMembers(stub_config) # Create a transport zone and logical switch. We only # need these so we can create logical ports. They aren't # part of the demo. tz = TransportZone(transport_type=TransportZone.TRANSPORT_TYPE_OVERLAY, display_name="Tagging Demo Transport Zone", description="Transport zone for tagging demo", host_switch_name="hostswitch") tz = transportzones_svc.create(tz) ls = LogicalSwitch( transport_zone_id=tz.id, admin_state=LogicalSwitch.ADMIN_STATE_UP, replication_mode=LogicalSwitch.REPLICATION_MODE_MTEP, display_name="ls-tag-demo", ) ls = logicalswitches_svc.create(ls) # First, create a new group whose members are any logical # ports with a tag scope of "color" and tag value of "green" group = NSGroup( display_name="Green Logical Ports", description="All logical ports with scope=color and tag=green", membership_criteria=[ NSGroupTagExpression(resource_type="NSGroupTagExpression", target_type="LogicalPort", scope_op="EQUALS", scope="color", tag_op="EQUALS", tag="green") ]) green_group = nsgroups_svc.create(group) # Now create another group for color:yellow logical ports. group = NSGroup( display_name="Yellow Logical Ports", description="All logical ports with scope=color and tag=yellow", membership_criteria=[ NSGroupTagExpression(resource_type="NSGroupTagExpression", target_type="LogicalPort", scope_op="EQUALS", scope="color", tag_op="EQUALS", tag="yellow") ]) yellow_group = nsgroups_svc.create(group) # Now get the list of effective members (that is, logical ports # with color:green). There should be no effective members yet. print("Before creating any lports:") print_group_effective_members("green group", efflports_svc.list(green_group.id)) print_group_effective_members("yellow group", efflports_svc.list(yellow_group.id)) print("") # Create a logical port with color:green lport = LogicalPort(display_name="tagging-demo-lp1", admin_state=LogicalPort.ADMIN_STATE_UP, logical_switch_id=ls.id, tags=[Tag(scope="color", tag="green")]) lport = logicalports_svc.create(lport) print("Logical port for this test has id %s" % lport.id) print("") # Group membership is computed asynchronously in the NSX # manager. Wait a bit. time.sleep(2.0) # Find the effective members of the green and yellow groups. # Notice that the logical port is in the green group. print("After creating green lport:") print_group_effective_members("green group", efflports_svc.list(green_group.id)) print_group_effective_members("yellow group", efflports_svc.list(yellow_group.id)) print("") # Now modify the logical port's color to yellow. lport = logicalports_svc.get(lport.id) lport.tags = [Tag(scope="color", tag="yellow")] logicalports_svc.update(lport.id, lport) # Wait for group recalculation time.sleep(2.0) # Find the effective members of the green and yellow groups. # Notice that the logical port is now in the yellow group # and no longer in the green group. print("After changing lport color to yellow:") print_group_effective_members("green group", efflports_svc.list(green_group.id)) print_group_effective_members("yellow group", efflports_svc.list(yellow_group.id)) print("") # Now clear the tag lport = logicalports_svc.get(lport.id) lport.tags = [] logicalports_svc.update(lport.id, lport) # Wait for group recalculation time.sleep(2.0) # The port should be in neither group print("After removing lport color tag:") print_group_effective_members("green group", efflports_svc.list(green_group.id)) print_group_effective_members("yellow group", efflports_svc.list(yellow_group.id)) print("") print("Press enter to delete all resources created for this example.") sys.stdin.readline() # Delete all resources we created. logicalports_svc.delete(lport.id) nsgroups_svc.delete(green_group.id) nsgroups_svc.delete(yellow_group.id) logicalswitches_svc.delete(ls.id) transportzones_svc.delete(tz.id)
def main(): args = getargs.getargs() print("----debug-----1") nsx_host="192.168.55.37" user = "******" password = "******" tcp_port = 443 # stub_config = auth.get_session_auth_stub_config(args.user, args.password, # args.nsx_host, # args.tcp_port) stub_config = auth.get_session_auth_stub_config(user, password, nsx_host, tcp_port) # Create a pretty printer to make the output look nice. pp = PrettyPrinter() # Create the service we'll need. transportzones_svc = TransportZones(stub_config) # First, list all transport zones. If your NSX installation has # just been installed, this should return an empty list. tzs = transportzones_svc.list() print("Initial list of transport zones - %d zones" % tzs.result_count) pp.pprint(tzs) # Create a transport zone. new_tz = TransportZone( transport_type=TransportZone.TRANSPORT_TYPE_OVERLAY, display_name="My transport zone", description="Transport zone for basic create/read/update/delete demo", host_switch_name="hostswitch1" ) result_tz = transportzones_svc.create(new_tz) print("Transport zone created. id is %s" % result_tz.id) # Save the id, which uniquely identifies the resource we created. tz_id = result_tz.id # Read that transport zone. read_tz = transportzones_svc.get(tz_id) print("Re-read the transport zone") pp.pprint(read_tz) # List all transport zones again. The newly created transport # zone will be in the list. tzs = transportzones_svc.list() print("Updated list of transport zones - %d zones" % tzs.result_count) pp.pprint(tzs) print("You can now examine the list of transport zones in the") print("NSX manager if you wish. Press enter to continue.") sys.stdin.readline() # Update the transport zone. read_tz.description = "Updated description for transport zone" updated_tz = transportzones_svc.update(tz_id, read_tz) print("After updating description. Note that the revision property is " "automatically updated.") pp.pprint(updated_tz) # Update the transport zone again. # # Note that NSX insists that clients always operate on up-to-date # data. To enforce this, every resource in NSX has a "revision" # property that is automatically maintained by NSX and is # incremented each time the resource is updated. If a client # submits an update operation, and the revision property in the # payload provided by the client does not match the revision # stored on the server, another update must have happened since # the client last read the resource, and the client's copy is # therefore stale. In this case, the server will return a 412 # Precondition Failed error. This is intended to prevent clients # from clobbering each other's updates. To recover from this # error, the client must re-read the resource, apply any desired # updates, and perform another update operation. updated_tz.description = "Updated description again for transport zone" updated_tz = transportzones_svc.update(tz_id, updated_tz) print("After updating description again.") pp.pprint(updated_tz) # Delete the transport zone. transportzones_svc.delete(tz_id) print("After deleting transport zone") # Now if we try to read the transport zone, we should get a # 404 Not Found error. This example also shows how you can # check for and handle specific errors from the NSX API. try: read_tz = transportzones_svc.get(tz_id) except NotFound: print("Transport zone is gone, as expected")
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)