NSX-T: OpenAPI and SDKs

NSX-T: OpenAPI and SDKs

This post was originally published on this site ---

Nowadays everything is about automation. Organizations are moving away from the traditional static infrastructure to full automation and here the need of NSX is significant. There are many use-cases for NSX, but the common in all of them is that they all need to be automated.

VMware is investing heavenly for different tools to ease the automation aspect of NSX but in order to take full advantage of it one need to understand what happens under the hood. It is also important if someone wants to build their own custom automation tool or CMP (Cloud Management Platform). Many existing solutions like Openstack, Kubernetes, vRO and so on automate NSX-T using different plugins. In fact, those plugins are sending REST API calls to NSX Manager in order to automate logical topology CRUD(Create, Read, Update, Delete) operations.

Based on our experience we decided that NSX-T APIs will be based on JSON format following OpenAPI standard. The use of Open APIs is to enable third party developers to build applications and services around NSX-T by standardising on how REST APIs are described. This means one can use standard tools like Swagger to read and use those APIs. Below is a quick example from my Mac on how to generate from CLI a language bindings on any of the program languages swagger supports.

# Install swagger-codegen
brew install swagger-codegen
#  Get NSX swagger specification and store it in a file
curl -k -u admin:{password} -X GET https://{nsx_manager}/api/v1/spec/openapi/nsx_api.json > nsx_api.json
# Generate python language bindings
swagger-codegen generate -i nsx_api.json -l python

The above allows you to generate python bindings and documentation with 100% API coverage. You can create those bindings easily by replacing the keyword python with other (like go, ruby, php, etc) on the last swagger-codegen command. In Addtional Info section below you can find a link how to install swagger on Linux or Windows. This is just for information and I won’t spend more time on it as VMware makes your life as a developer even easier by taking care for this process and we produce official VMware supported language bindings. The goal of the sections below is to help you getting started with Python SDK for NSX-T.

Download and Install Python SDK

As of today, we support Python and Java SDKs that can be downloaded from downloads.vmware.com or https://code.vmware.com/sdks

Let me quickly give some example on how to install and use the Python SDK. Download vAPI runtime and dependencies as well as NSX-T SDK. They should be like following:

nsx_python_sdk-2.1.0.0.0.7319425-py2.py3-none-any.whl
vapi_common-2.7.0-py2.py3-none-any.whl
vapi_common_client-2.7.0-py2.py3-none-any.whl
vapi_runtime-2.7.0-py2.py3-none-any.whl

You will need python pip installed. Run the following from the folder you have the files above downloaded.

sudo pip install *.whl

In order to validate that it was installed successfully enter python interactive mode and try to import one of the packages.

python
from com.vmware.nsx_client import TransportZones

The output should be like this:

 

If it doesn’t complain that there is no module named TransportZones you are fine, enter quit() and lets start with our first sample script.

Write simple test script

The workflow should look like following:

  1. Create a Stub Context with NSX Manager IP Address and credentials
  2. Instantiate a service for the API endpoint
  3. Create a payload object
  4. Call the service’s CRUD method

The first example reads and lists all Transport Zones.

#!/usr/bin/env python

import pprint
import requests

from com.vmware.nsx_client import TransportZones
from vmware.vapi.bindings.struct import PrettyPrinter
from vmware.vapi.lib import connect
from vmware.vapi.security.user_password import 
    create_user_password_security_context
from vmware.vapi.stdlib.client.factories import StubConfigurationFactory


def main():
    # 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
    # Don't forget to put your own NSX Manager IP Address
    nsx_url = 'https://%s:%s' % ("10.29.12.211", 443)
    connector = connect.get_requests_connector(
        session=session, msg_protocol='rest', url=nsx_url)
    stub_config = StubConfigurationFactory.new_std_configuration(connector)

    # Don't forget to put your own username and password for NSX
    security_context = create_user_password_security_context(
        "admin", "VMware1!")
    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)


if __name__ == "__main__":
    main()

Copy the code above and paste it in a file called list_tz.py. Don’t forget to change the  NSX Manager IP Address and password. Run python list_tz.py from the CLI and if you get a list of all Transport Zones together with their properties we have our first script ran successful.

Explore more CRUD operations

Lets extend the script using the same workflow. Now we will create a Transport Zone and a Logical Switch based on the newly created Transport Zone. After that we will update the name of the Transport Zone. At the end we will delete both recourses.

#!/usr/bin/env python

import pprint
import requests

from com.vmware.nsx_client import TransportZones
from com.vmware.nsx_client import LogicalSwitches
from com.vmware.nsx.model_client import TransportZone
from com.vmware.nsx.model_client import LogicalSwitch
from vmware.vapi.bindings.struct import PrettyPrinter
from vmware.vapi.lib import connect
from vmware.vapi.security.user_password import 
    create_user_password_security_context
from vmware.vapi.stdlib.client.factories import StubConfigurationFactory


def main():
    session = requests.session()
    session.verify = False
    nsx_url = 'https://%s:%s' % ("10.29.12.211", 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("admin", "VMware1!")
    connector.set_security_context(security_context)

    # Create the services we'll need.
    transportzones_svc = TransportZones(stub_config)
    logicalswitches_svc = LogicalSwitches(stub_config)

    # Create a transport zone.
    new_tz = TransportZone(
	transport_type=TransportZone.TRANSPORT_TYPE_OVERLAY,
	display_name="My New Transport Zone",
	description="Transport zone created by Python",
	host_switch_name="nsxtvds1"
    )
    tz = transportzones_svc.create(new_tz)
    print("Transport zone created. id is %s" % tz.id)

    # Create a Logical Switch based on this TZ
    ls = LogicalSwitch(
	transport_zone_id=tz.id,
	admin_state=LogicalSwitch.ADMIN_STATE_UP,
	replication_mode=LogicalSwitch.REPLICATION_MODE_MTEP,
	display_name="ls-demo",
    )
    ls = logicalswitches_svc.create(ls)
    print("Logical switch created. id is %s" % ls.id)
    print("Review the newly created Transport Zone and Logical Switch in NSX GUI")
    print("When you hit Enter the name of Transport Zone will be changed!!!")
    raw_input("Press Enter to continue...")
    # Read that transport zone.
    read_tz = transportzones_svc.get(tz.id)
    read_tz.display_name = "Updated TZ"
    updated_tz = transportzones_svc.update(tz.id, read_tz)

    print("Review the updated Transport Zone name in NSX GUI")
    print("When you hit Enter both the Logical Switch and the transport Zone will be deleted")
    raw_input("Press Enter to continue...")
    logicalswitches_svc.delete(ls.id)
    transportzones_svc.delete(tz.id)
    print("TZ and LS are deleted !!!")

if __name__ == "__main__":
    main()

Copy the code above in a file and run it. After every operation there is a pause to give you the opportunity to review what happened. Don’t Forget to change NSX ip address and password!

We covered all CRUD operations with the above two scripts. Similarly one can create, read, update, or delete all the resources in NSX.

 

Happy coding!!!

 

Additional info:

VMware NSX-T Documentation: https://docs.vmware.com/en/VMware-NSX-T/index.html

All VMware Documentation: https://docs.vmware.com

VMware NSX YouTube Channel: https://www.youtube.com/VMwareNSX

VMware Official Site: https://www.vmware.com/

OpenAPI Initiative: https://www.openapis.org/

Install Swagger: https://github.com/swagger-api/swagger-codegen#prerequisites

 

 

The post NSX-T: OpenAPI and SDKs appeared first on Network Virtualization.

Leave a Reply

Your email address will not be published. Required fields are marked *