Beispiel #1
0
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)
Beispiel #2
0
def main():

    api_client = auth.create_nsx_policy_api_client("admin",
                                                   "superSecretPassword",
                                                   "nsx1.yasen.local",
                                                   443,
                                                   auth_type=auth.SESSION_AUTH)

    # Create a pretty printer to make the output look nice.
    pp = PrettyPrinter()

    tag1 = Tag(scope="Event", tag="VMworld2019")
    tag2 = Tag(scope="Session", tag="CODE2544U")

    tagList = [tag1, tag2]

    t1id = 'my_t1_id'
    tier1 = Tier1(
        id=t1id,
        display_name='myVMworldT1',
        description='T1 GW created using python SDK for VMworld demo',
        route_advertisement_types=['TIER1_STATIC_ROUTES', 'TIER1_CONNECTED'],
        tier0_path='/infra/tier-0s/t0',
        tags=tagList)

    try:
        api_client.infra.Tier1s.patch(t1id, tier1)
        newTier1 = api_client.infra.Tier1s.get(t1id)
        pp.pprint(newTier1)
    except Error as ex:
        api_error = ex.data.convert_to(ApiError)
        print("An error occurred when creating Segment: %s" %
              api_error.error_message)

    subnet = SegmentSubnet(
        dhcp_ranges=None,
        gateway_address='10.114.209.121/30',
        network='10.114.209.120/30',
    )

    segmentId = 'testSegmentId'
    segment = Segment(
        id=segmentId,
        display_name='testSegmentName',
        tags=tagList,
        subnets=[subnet],
        connectivity_path='/infra/tier-1s/%s' % t1id,
        transport_zone_path=
        '/infra/sites/default/enforcement-points/default/transport-zones/4052b9da-2912-4c79-8709-3e25a34457ac'
    )

    try:
        api_client.infra.Segments.patch(segmentId, segment)
        newSegment = api_client.infra.Segments.get(segmentId)
        pp.pprint(newSegment)
    except Error as ex:
        api_error = ex.data.convert_to(ApiError)
        print("An error occurred when creating Segment: %s" %
              api_error.error_message)
Beispiel #3
0
def main():
    arg_parser = getargs.get_arg_parser()
    arg_parser.add_argument("port1",
                            metavar="PORT_ID_1",
                            type=str,
                            nargs="?",
                            help="Logical port 1")
    arg_parser.add_argument("port2",
                            metavar="PORT_ID_2",
                            type=str,
                            nargs="?",
                            help="Logical port 2")
    args = arg_parser.parse_args()

    # Verify exactly 0 or 2 ports were given
    ports = [x for x in [args.port1, args.port2] if x is not None]
    if len(ports) not in (0, 2):
        arg_parser.error("Give exactly two logical port IDs, or none to "
                         "get a list of logical ports.")

    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.
    lp_svc = LogicalPorts(stub_config)
    forwardingpath_svc = ForwardingPath(stub_config)

    # Find all logical ports
    all_lps = lp_svc.list().results
    lp_ids = [lp.id for lp in all_lps]
    fail = False
    for port in ports:
        if port not in lp_ids:
            print("Logical port %s not found" % port)
            fail = True
    if fail:
        sys.exit(1)
    print("Checking forwarding path between %s and %s" %
          (args.port1, args.port2))
    if len(ports) == 0:
        # Print all the ports
        for lp in all_lps:
            # Show the port's name and id, the logical switch it's on,
            # and what it's attached to, if anything.
            print("Logical port %s (id %s)" % (lp.display_name, lp.id))
            print(" On switch %s" % lp.logical_switch_id)
            attachment = ("None" if lp.attachment is None else "%s %s" %
                          (lp.attachment.attachment_type, lp.attachment.id))
            print(" Attached to: %s" % attachment)

    else:
        # Print forwarding path
        path = forwardingpath_svc.get(ports[0], ports[1])
        pp.pprint(path)
Beispiel #4
0
def main():
    connection = create_api_connection()

    bgp_svc = BGPStatus(connection)
    result = bgp_svc.list(
        logical_router_id='eb18c105-521a-4ca1-a7d7-ed51d93ed718',
        source='realtime')

    pp = PrettyPrinter()
    pp.pprint(result)
Beispiel #5
0
def main():
    arg_parser = getargs.get_arg_parser()
    arg_parser.add_argument("-s",
                            "--remote_ssh_server",
                            type=str,
                            required=True,
                            help="remote ssh server")
    arg_parser.add_argument("-r",
                            "--remote_ssh_user",
                            type=str,
                            required=True,
                            help="remote ssh username")
    arg_parser.add_argument("-c",
                            "--remote_ssh_password",
                            type=str,
                            required=True,
                            help="remote ssh password")
    arg_parser.add_argument("-f",
                            "--remote_ssh_fingerprint",
                            type=str,
                            required=True,
                            help="remote ssh SHA256 fingerprint")
    args = arg_parser.parse_args()
    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.
    sb_svc = SupportBundles(stub_config)
    cl_node_svc = Nodes(stub_config)

    # Get the UUID of the manager node we're talking to. We'll
    # request a support bundle from it.
    mgr_node = cl_node_svc.get("self")
    mgr_uuid = mgr_node.id
    print(mgr_uuid)

    protocol = SupportBundleFileTransferProtocol(
        name="SCP",
        authentication_scheme=SupportBundleFileTransferAuthenticationScheme(
            scheme_name="PASSWORD",
            username=args.remote_ssh_user,
            password=args.remote_ssh_password),
        ssh_fingerprint=args.remote_ssh_fingerprint)
    rfs = SupportBundleRemoteFileServer(directory_path="/tmp",
                                        server=args.remote_ssh_server,
                                        protocol=protocol)

    sb_request = SupportBundleRequest(log_age_limit=1,
                                      nodes=[mgr_uuid],
                                      remote_file_server=rfs)
    resp = sb_svc.collect(sb_request)
    pp.pprint(resp)
Beispiel #6
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)
Beispiel #7
0
def main():
    args = getargs.getargs()

    api_client = auth.create_nsx_api_client(args.user,
                                            args.password,
                                            args.nsx_host,
                                            args.tcp_port,
                                            auth_type=auth.SESSION_AUTH)

    # Create a pretty printer to make the output look nice.
    pp = PrettyPrinter()

    t = api_client.telemetry.Config.get()
    pp.pprint(t)
Beispiel #8
0
def main():
    arg_parser = getargs.get_arg_parser()
    arg_parser.add_argument("-s", "--remote_ssh_server", type=str,
                            required=True, help="remote ssh server")
    arg_parser.add_argument("-w", "--remote_ssh_user", type=str,
                            required=True, help="remote ssh username")
    arg_parser.add_argument("-c", "--remote_ssh_password", type=str,
                            required=True, help="remote ssh password")
    arg_parser.add_argument("-f", "--remote_ssh_fingerprint", type=str,
                            required=True,
                            help="remote ssh SHA256 fingerprint")
    args = arg_parser.parse_args()
    api_client = auth.create_nsx_api_client(args.user, args.password,
                                            args.nsx_host, args.tcp_port,
                                            auth_type=auth.SESSION_AUTH)
    pp = PrettyPrinter()

    # Get the UUID of the manager node we're talking to. We'll
    # request a support bundle from it.
    mgr_node = api_client.cluster.Nodes.get("self")
    mgr_uuid = mgr_node.id
    print(mgr_uuid)

    protocol = SupportBundleFileTransferProtocol(
        name="SCP",
        authentication_scheme=SupportBundleFileTransferAuthenticationScheme(
            scheme_name="PASSWORD",
            username=args.remote_ssh_user,
            password=args.remote_ssh_password
        ),
        ssh_fingerprint=args.remote_ssh_fingerprint
    )
    rfs = SupportBundleRemoteFileServer(
        directory_path="/tmp",
        server=args.remote_ssh_server,
        protocol=protocol
    )

    sb_request = SupportBundleRequest(
        log_age_limit=1,
        nodes=[mgr_uuid],
        remote_file_server=rfs
    )
    try:
        resp = api_client.administration.SupportBundles.collect(sb_request)
        pp.pprint(resp)
    except Error as ex:
        api_error = ex.data.convert_to(ApiError)
        print("An error occurred: %s" % api_error.error_message)
Beispiel #9
0
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 and client
    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)
    stub_factory = nsx_client.StubFactory(stub_config)
    api_client = ApiClient(stub_factory)

    # Now any API calls we make should authenticate to NSX using
    # the client certificate. Let's get a list of all Transport Zones.
    tzs = api_client.TransportZones.list()
    # Create a pretty printer to make the output look nice.
    pp = PrettyPrinter()
    pp.pprint(tzs)
Beispiel #10
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'))
Beispiel #11
0
def main():
    args = getargs.getargs()

    # Create a pretty printer to make the output look nice.
    pp = PrettyPrinter()

    api_client = auth.create_nsx_api_client(args.user,
                                            args.password,
                                            args.nsx_host,
                                            args.tcp_port,
                                            auth_type=auth.SESSION_AUTH)

    # First, list all switching profiles.
    swps = api_client.SwitchingProfiles.list()
    print("Initial list of switching profiles - %d profiles" %
          swps.result_count)
    # Since switching profiles are polymorphic, we need to convert
    # each profile to its concrete class
    for raw_profile in swps.results:
        concrete_type_name = raw_profile.to_dict()["resource_type"]
        concrete_type = getattr(model_client, concrete_type_name)
        profile = raw_profile.convert_to(concrete_type)
        pp.pprint(profile)

    # Create a new QOS switching profile
    new_profile = QosSwitchingProfile(class_of_service=None,
                                      dscp=None,
                                      shaper_configuration=None,
                                      description="",
                                      display_name="My QoS Policy",
                                      tags=[])
    result_profile = api_client.SwitchingProfiles.create(
        new_profile).convert_to(QosSwitchingProfile)
    print("Switching profile created. id is %s" % result_profile.id)

    # Save the id, which uniquely identifies the resource we created.
    profile_id = result_profile.id

    # Read that switching profile.
    read_profile = api_client.SwitchingProfiles.get(profile_id).convert_to(
        QosSwitchingProfile)
    print("Re-read the QOS switching profile")
    pp.pprint(read_profile)

    # Delete the switching profile
    api_client.SwitchingProfiles.delete(profile_id)
    print("After deleting QOS switching profile")
Beispiel #12
0
def main():
    # Read the command-line arguments. The args object will contain
    # 3 properties, args.nsx_host, args.tcp_port, and args.refresh_token.
    args = getargs.getargs()
    if args.refresh_token is None:
        sys.stderr.write(
            "Error: you must provide a refresh token for this example\n")
        sys.exit(1)

    # Obtain a token to use for authenticating to the NSX Manager. We
    # just use the python requests library directly.
    params = {"refresh_token", args.refresh_token}
    resp = requests.post("%s?refresh_token=%s" %
                         (VMC_AUTH_URL, args.refresh_token))
    resp.raise_for_status()  # Will raise exception if error
    resp_json = resp.json()
    # This is the access token you will pass with all NSX Manager API requests
    access_token = resp_json["access_token"]

    # Create a session using the requests library. For more information on
    # requests, see http://docs.python-requests.org/en/master/
    session = requests.session()
    # Arrange for the requests library to send the bearer token header
    # with each request.
    session.headers["Authorization"] = "Bearer %s" % access_token

    # 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
    nsx_url = 'https://%s:%s' % (args.nsx_host, args.tcp_port)
    resp = session.get("%s/api/v1/cluster" % nsx_url)
    connector = connect.get_requests_connector(session=session,
                                               msg_protocol='rest',
                                               url=nsx_url)
    stub_config = StubConfigurationFactory.new_std_configuration(connector)

    # Let's get a list of all Domains
    domains_svc = Domains(stub_config)
    domains = domains_svc.list()
    # Create a pretty printer to make the output look nice.
    pp = PrettyPrinter()
    pp.pprint(domains)
Beispiel #13
0
def main():
    # Read the command-line arguments.
    arg_parser = argparse.ArgumentParser()
    arg_parser.add_argument('-o', '--org_id', type=str, required=True,
                            help='VMC Organization ID')
    arg_parser.add_argument('-s', '--sddc_id', type=str, required=True,
                            help='VMC Software Defined Datacenter ID')
    arg_parser.add_argument('-r', '--refresh_token', type=str, required=True,
                            help='Refresh token')
    args = arg_parser.parse_args()

    vmc_client = create_nsx_policy_client_for_vmc(
        args.refresh_token, args.org_id, args.sddc_id)

    # Let's get a list of all Domains
    domains = vmc_client.infra.Domains.list()
    # Create a pretty printer to make the output look nice.
    pp = PrettyPrinter()
    pp.pprint(domains)
Beispiel #14
0
def main():
    args = getargs.getargs()

    # Create a pretty printer to make the output look nice.
    pp = PrettyPrinter()

    api_client = auth.create_nsx_api_client(args.user,
                                            args.password,
                                            args.nsx_host,
                                            args.tcp_port,
                                            auth_type=auth.SESSION_AUTH)

    # Create an IP Pool
    new_pool = IpPool(display_name="My IP Pool",
                      description="IP Pool for IP Pool demo",
                      subnets=[
                          IpPoolSubnet(cidr="192.168.1.0/24",
                                       allocation_ranges=[
                                           IpPoolRange(start="192.168.1.10",
                                                       end="192.168.1.20")
                                       ])
                      ])
    result_pool = api_client.pools.IpPools.create(new_pool)
    print("IP Pool created. id is %s" % result_pool.id)

    # Allocate an IP address
    alloc = AllocationIpAddress(allocation_id="192.168.1.11")
    api_client.pools.IpPools.allocateorrelease(
        pool_id=result_pool.id,
        allocation_ip_address=alloc,
        action=api_client.pools.IpPools.ALLOCATEORRELEASE_ACTION_ALLOCATE)

    # Show the allocations
    allocs = api_client.pools.ip_pools.Allocations.list(result_pool.id)
    pp.pprint(allocs)

    # Deallocate the IP address
    api_client.pools.IpPools.allocateorrelease(
        pool_id=result_pool.id,
        allocation_ip_address=alloc,
        action=api_client.pools.IpPools.ALLOCATEORRELEASE_ACTION_RELEASE)
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)
    # Arrange for the Authorization header to be sent with every request.
    # We do this because the vapi libraries do not currently directly
    # support authentication with this header payload.
    auth_str = base64.b64encode("%s:%s" % (args.user, args.password))
    session.headers["Authorization"] = "Remote %s" % auth_str
    stub_factory = nsx_client.StubFactory(stub_config)
    api_client = ApiClient(stub_factory)

    # Now any API calls we make should authenticate to NSX by
    # providing an Authorization header with the correct value.
    # Let's get a list of all Transport Zones.
    tzs = api_client.TransportZones.list()
    # Create a pretty printer to make the output look nice.
    pp = PrettyPrinter()
    pp.pprint(tzs)
def main():
    arg_parser = getargs.get_arg_parser()
    arg_parser.add_argument("-s",
                            "--remote_enforcement_point",
                            type=str,
                            required=True,
                            help="remote enforcement point (nsx-t manager "
                            "ip address or hostname)")
    arg_parser.add_argument("-l",
                            "--remote_login_user",
                            type=str,
                            required=True,
                            help="remote login username")
    arg_parser.add_argument("-c",
                            "--remote_login_password",
                            type=str,
                            required=True,
                            help="remote login password")
    arg_parser.add_argument("-f",
                            "--remote_ssl_thumbprint",
                            type=str,
                            required=True,
                            help="remote ssl SHA256 thumbprint")
    args = arg_parser.parse_args()

    api_client = auth.create_nsx_policy_api_client(args.user,
                                                   args.password,
                                                   args.nsx_host,
                                                   args.tcp_port,
                                                   auth_type=auth.SESSION_AUTH)

    # Create a pretty printer to make the output look nice.
    pp = PrettyPrinter()

    DEFAULT_DZ_ID = "default"
    # Read the default deployment zone
    default_dz = api_client.infra.DeploymentZones.get(DEFAULT_DZ_ID)

    # Print the current enforcement points
    print("Initial enforcement points: ")
    pp.pprint(default_dz.enforcement_points)

    # Register an enforcement point
    conn_info = NSXTConnectionInfo(
        enforcement_point_address=args.remote_enforcement_point,
        thumbprint=args.remote_ssl_thumbprint,
        username=args.remote_login_user,
        password=args.remote_login_password,
    )
    ep = EnforcementPoint(
        description="Example Enforcement Point",
        connection_info=conn_info,
    )

    try:
        api_client.infra.EnforcementPoints.patch(DEFAULT_DZ_ID, "example", ep)
    except Error as ex:
        api_error = ex.data.convert_to(ApiError)
        print("An error occurred: %s" % api_error.error_message)

    eps = api_client.infra.EnforcementPoints.list(DEFAULT_DZ_ID)
    pp.pprint(eps)

    print("You can now examine the enforcement points in the")
    print("NSX policy service if you wish. Press enter to continue.")
    sys.stdin.readline()

    # Delete the enforcement point
    api_client.infra.EnforcementPoints.delete(DEFAULT_DZ_ID, "example")
    print("After deleting enforcement point")
Beispiel #17
0
def main():
    # args = getargs.getargs()

    nsx_host = "192.168.55.37"
    user = "******"
    password = "******"
    tcp_port = 443

    # stub_config = auth.get_basic_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 services we'll need.
    infra_svc = Infra(stub_config)
    domains_svc = Domains(stub_config)

    # First, retrieve /infra and the domains in /infra. If your NSX
    # policy service has just been installed, there will be no domains.
    infra = infra_svc.get()
    print("Initial state of /infra")
    pp.pprint(infra)
    domains = domains_svc.list()
    print("All domains: total of %d domains" % domains.result_count)

    # Create a domain with a random id
    domain_id = "Domain_%d" % random.choice(range(10000))
    domain = Domain(
        id=domain_id,
        display_name=domain_id,
        # Note: the revision should not be required, but for
        # now it must be provided on initial object creation.
        revision=0)
    try:
        domains_svc.update(domain_id, domain)
        print("Domain %s created." % domain_id)
    except Error as ex:
        api_error = ex.data.convert_to(ApiError)
        print("An error occurred: %s" % api_error.error_message)

    # Read that domain
    read_domain = domains_svc.get(domain_id)
    print("Re-read the domain")
    pp.pprint(read_domain)

    # List all domains again. The newly created domain
    # will be in the list.
    domains = domains_svc.list()
    print("All domains: total of %d domains" % domains.result_count)

    print("You can now examine the infra and domains in the")
    print("NSX policy service if you wish. Press enter to continue.")
    sys.stdin.readline()

    # Update the domain. The NSX policy API only supports a create API,
    # so to update an existing resource, just call the create method
    # again, passing the properties you wish to update.
    read_domain.description = "Updated description for transport zone"
    domains_svc.update(domain_id, read_domain)

    # Re-read the domain
    read_domain = domains_svc.get(domain_id)
    print("Domain after updating")
    pp.pprint(read_domain)

    # Delete the domain
    domains_svc.delete(domain_id)
    print("After deleting domain")

    # Now if we try to read the domain, we should get a
    # 404 Not Found error. This example also shows how you can
    # check for and handle specific errors from the NSX Policy API.
    try:
        read_domain = domains_svc.get(domain_id)
    except NotFound:
        print("Domain is gone, as expected")
Beispiel #18
0
def main():
    args = getargs.getargs()

    # Create a pretty printer to make the output look nice.
    pp = PrettyPrinter()

    api_client = auth.create_nsx_api_client(args.user,
                                            args.password,
                                            args.nsx_host,
                                            args.tcp_port,
                                            auth_type=auth.SESSION_AUTH)

    # First, list all transport zones. If your NSX installation has
    # just been installed, this should return an empty list.
    tzs = api_client.TransportZones.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 = api_client.TransportZones.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 = api_client.TransportZones.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 = api_client.TransportZones.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 = api_client.TransportZones.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 = api_client.TransportZones.update(tz_id, updated_tz)
    print("After updating description again.")
    pp.pprint(updated_tz)

    # Delete the transport zone.
    api_client.TransportZones.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 = api_client.TransportZones.get(tz_id)
    except NotFound:
        print("Transport zone is gone, as expected")
Beispiel #19
0
def main():
    args = getargs.getargs()

    api_client = auth.create_nsx_policy_api_client(
        args.user, args.password, args.nsx_host, args.tcp_port,
        auth_type=auth.SESSION_AUTH)

    # Create a pretty printer to make the output look nice.
    pp = PrettyPrinter()

    # First, retrieve /infra and the domains in /infra. If your NSX
    # policy service has just been installed, there will be no domains.
    infra = api_client.Infra.get()
    print("Initial state of /infra")
    pp.pprint(infra)
    domains = api_client.infra.Domains.list()
    print("All domains: total of %d domains" % domains.result_count)

    # Create a domain with a random id
    domain_id = "Domain_%d" % random.choice(range(10000))
    domain = Domain(
        id=domain_id,
        display_name=domain_id,
    )
    try:
        api_client.infra.Domains.update(domain_id, domain)
        print("Domain %s created." % domain_id)
    except Error as ex:
        api_error = ex.data.convert_to(ApiError)
        print("An error occurred: %s" % api_error.error_message)

    # Read that domain
    read_domain = api_client.infra.Domains.get(domain_id)
    print("Re-read the domain")
    pp.pprint(read_domain)

    # List all domains again. The newly created domain
    # will be in the list.
    domains = api_client.infra.Domains.list()
    print("All domains: total of %d domains" % domains.result_count)

    print("You can now examine the infra and domains in the")
    print("NSX policy service if you wish. Press enter to continue.")
    sys.stdin.readline()

    # Update the domain. The NSX policy API only supports a create API,
    # so to update an existing resource, just call the create method
    # again, passing the properties you wish to update.
    read_domain.description = "Updated description for transport zone"
    api_client.infra.Domains.update(domain_id, read_domain)

    # Re-read the domain
    read_domain = api_client.infra.Domains.get(domain_id)
    print("Domain after updating")
    pp.pprint(read_domain)

    # Delete the domain
    api_client.infra.Domains.delete(domain_id)
    print("After deleting domain")

    # Now if we try to read the domain, we should get a
    # 404 Not Found error. This example also shows how you can
    # check for and handle specific errors from the NSX Policy API.
    try:
        read_domain = api_client.infra.Domains.get(domain_id)
    except NotFound:
        print("Domain is gone, as expected")