vCloud Air Python SDK Package

A lightweight SDK for vCloud Air. Currently not meant to handle exhaustive operations against VMs, vDCs, edges, etc, but only some of the more common operations.

This is aimed more towards using newer APIs (ANS, metrics, etc) than classic (vCD) APIs, as those are far more heavy due to the use of XML.

vCloud Air Advanced Network Services

Advanced Networking Services (ANS) comes with a new/different set of API calls than the normal vCD networking. This module breaks down the different parts of the new API and its functionality. Now, firewall, NAT, routing, VPN, etc can all be called and updated separately. Each class represents of a different part of the ANS edge device.

class vcloudair.ans.ANSFirewall(edge_id, org_info=None, vcdurl=None, token=None)

Bases: vcloudair.ans.ANSSectionBase

This class handles interactions with the Firewall configuration.

add_rule(name, source, destination, action='accept', protocol='tcp', source_port='any', dest_port='any')

Add a new firewall rule into the current configuration. Must retrieve configuration from API first before adding new rules.

Parameters:
  • name (str) – The name of the rule
  • source (str) – The source IP or interface: ‘external’ or ‘internal’
  • destination (str) – The destination IP or interface (see source)
  • action (str) – Accept or Deny
  • protocol (str) – The protocol for the rule (TCP, UDP, ICMP, etc)
  • source_port (str) – Source port or range (33-44) or ‘any’
  • dest_port (str) – Destination port or range or ‘any’
Returns:

None

get_config()

Retrieve the firewall configuration from the ANS API.

Returns:None
save_config()

Save and submit the firewall configuration to the ANS API.

Returns:None
class vcloudair.ans.ANSIPSec(edge_id, org_info=None, vcdurl=None, token=None)

Bases: vcloudair.ans.ANSSectionBase

This class handles interactions with the IPSec configuration.

add_psk_tunnel(name, local_id, local_ip, peer_id, peer_ip, local_subnets, peer_subnets, psk, enc_algo='aes256', pfs=True, dhgroup=2, extension=None)

Add a new IPSec tunnel using Pre-Shared Key authentication.

For a full description of parameters, see vCA documentation: https://pubs.vmware.com/vca/topic/com.vmware.vca.ans.api.doc/GUID-DD69C65F-FD55-4934-A67B-2BF65491F272.html

Parameters:
  • name (str) – The friendly name of the IPSec tunnel
  • local_id (str) – The external IP of the local edge gateway
  • local_ip (str) – Endpoint network for the tunnel (usually external IP)
  • peer_id (str) – The public IP of the remote endpoint
  • peer_ip (str) – Public IP of the remote device (blank means wait for connection)
  • or list local_subnets (str) – The networks to share across the VPN
  • or list peer_subnets (str) – The remote networks shared across the VPN
  • psk (str) – Pre-Shared Key
  • enc_algo (str) – The encryption type/algorithm used
  • pfs (bool) – Enable Perfect-Forward Secrecy or not
  • dhgroup (int) – The Diffie-Hellman cryptography scheme
  • extension (str) – Optional extension configuration directive
Returns:

None

get_config()

Retrieve the IPSec configuration from the ANS API.

Returns:None
save_config()

Save and submit the IPSec configuration to the ANS API.

Returns:None
class vcloudair.ans.ANSNat(edge_id, org_info=None, vcdurl=None, token=None)

Bases: vcloudair.ans.ANSSectionBase

This class handles interactions with the NAT configuration.

add_rule(action, original_address, translated_address, original_port='any', translated_port='any', protocol='tcp', description='')

Creates a new NAT rule and appends it to the existing list of NAT rules within the retrieved configuration data.

Parameters:
  • action (str) – Type of rule, ‘dnat’ or ‘snat’
  • original_address (str) – IP address to translate
  • translated_address (str) – IP address to translate into
  • original_port (str) – Port, port range, or ‘any’ to translate from
  • translated_port (str) – Port, range, or ‘any’ to translate to
  • protocol (str) – TCP, UDP, ICMP, etc
  • description (str) – Rule description
Returns:

None

get_config()

Retrieve the NAT configuration from the ANS API.

Returns:None
save_config()

Save and submit the NAT configuration to the ANS API.

Returns:None
class vcloudair.ans.ANSSectionBase(edge_id, org_info=None, vcdurl=None, token=None)

Bases: object

Note The org_info data structure can be supplied to the init method while omitting the other two keyword arguments.

This is an abstract base class for ANS subclasses to inherit. It contains the general mechanisms for manipulating and referencing the ANS data.

These classes support iteration as well as getting / deleting items based on index value. The values correspond to the rules or tunnels. The global configuration must be edited through the config_data member variable.

__init__(edge_id, org_info=None, vcdurl=None, token=None)

Base class for ANS sections. The org_info parameter will take precedence when passed. It is expected to be a dictionary with the keys returned from the VCA Session class after log in.

Parameters:
  • edge_id (str) – UUID of the edge
  • org_info (dict) – Dictionary containing Org login data
  • vcdurl (str) – If org_info is absent, the vCD URL
  • token (str) – If org_info is absent, the authorzation token

vCloud Air Disaster Recovery

The disaster recovery module provides a class for accessing DRaaS in vCloud Air and executing DR actions: Failover, Test Failover, and Test Cleanup.

This class is meant for DR 2.x and will not work properly with DR 1.x.

class vcloudair.dr.DisasterRecovery(org_info=None, vcdurl=None, token=None, org_uuid=None, version='5.7')

Bases: object

This class works with DRaaS version 2.x. Replication status or configuration cannot be viewed or modified by this class. It’s purpose is to take actions against replicated VMs: Fail, Test, Recover (after test).

Failing back cannot be done from this class, nor can recovery of a failed VM.

__init__(org_info=None, vcdurl=None, token=None, org_uuid=None, version='5.7')

Provides an interface to a DR environment with access to failover and cleanup actions.

Parameters:
  • org_info (dict) – Data structure from a VCAODSession containing all required fields
  • vcdurl (str) – The endpoint for the OD/DR instance
  • token (str) – Authorization token
  • org_uuid (str) – The org UUID for the DR instance
  • version (str) – The API version to use
do_failover(*uuids, power_on=True, total=False, test=False)

Initates a failover or test failover for a VM or all VMs

Parameters:
  • uuids – The uuids of the VMs to failover
  • power_on (bool) – Whether to power on the VM during the test fail
  • total (bool) – Fail over all VMs. This takes precedence if UUID is provided
  • test (bool) – Whether this is a test failover or actual failover
Returns:

None

do_test_cleanup(*uuids, total=False)

Clean up the test failover from a VM or all VMs

Parameters:
  • uuids – The UUIDs of the VMs that are being cleaned up
  • total (bool) – Clean up all the VMs. This takes precedence
Returns:

None

do_test_failover(*uuids, power_on=True, total=False)

Initates a test failover, specifically, against the supplied VMs or the entire DR environment.

Returns:None
dump_replication_details(filelocation='details.csv')

Write the replication names and UUIDs into a file

Parameters:filelocation (str) – The file path/name of where to write the data
Returns:None
retrieve_replications()

Connect to the DR API endpoint and retrieve the list of replications. After retrieval, replication information is stored in the replications member variable.

Returns:None

vCloud Air Metrics

Metrics are available via the hybridity API (as of 2016) for the two current subscription offerings: Dedicated Clouds and Virtual Private Clouds. This module allows querying of metrics and also filtering by only the metrics the programmer wants to see.

Metrics are retained for a 24-hour period server-side at the time of writing. For more information about the metrics API, please see the following documentation: https://pubs.vmware.com/vca/topic/com.vmware.vca.metrics.api.doc/GUID-95D137D6-04A7-4BB6-90A7-70B132343CBB.html

class vcloudair.metrics.Metrics(org_info=None, vcdurl=None, token=None, org_uuid=None, vm_uuids=None)

Bases: object

The metics class allows for metric retrieval against VMs or VDCs. Metrics do exist for NSX edges but this class doesn’t retrieve those. Also, when retrieving a VDC, the returned metrics are for all of the VMs within that VDC.

__init__(org_info=None, vcdurl=None, token=None, org_uuid=None, vm_uuids=None)

Create a metrics instance to query the vCA Metrics API. Either a VDC or list of VMs can be queried by one instance. NOT BOTH!

Parameters:
  • org_info (dict) – Dictionary containing org login data
  • vcdurl (str) – Base URL for vCD instance
  • token (str) – vCD authentication token
  • org_uuid (str) – UUID for the VDC to query
  • vm_uuids (list) – List of VM UUIDs to query
add_metric_filters(*filters)

Adds additional filters to the existing list of filters.

Parameters:filters (str) – The names of the specific filters to add
Returns:None
collect()

Initiate the data collection from the metrics API

Returns:None
set_absolute_interval(start, end)

Not implemented at this time.

Parameters:
  • start
  • end
Returns:

set_metric_filters(*filters)

Sets the list of specific metrics to pull out of the returned JSON results.

Parameters:filters (str) – The names of the specific filters
Returns:None
set_relative_interval(units, start, end=None)

Sets the interval for which to collect metrics. This is a relative (aka, N minutes/hours AGO) rather than time window specific date.

Parameters:
  • units (str) – Duration units (MINUTE, HOUR, SECOND)
  • start (int) – Number of <unit> ago to begin collecting at
  • end (int) – Number of <unit> ago to end collecting at
Returns:

None

vCloud Air vCloud Director Queries

The query classes inherit from the base class which is used to return data from vCloud Director’s query API. The subclasses are for convenience when querying common vCD types.

An instance of the base class can be instantiated and manipulated manually in order to query more specific objects. A manual call to add the ‘type’ key to the instance variable “params” as well as changing the instance variable “record_name” to a matching query type will facilitate querying anything from the query API.

See the vCD API schema or documentation for additional query and type information.

class vcloudair.query.EdgeGatewayQuery(org_info=None, version=None, vcdurl=None, token=None)

Bases: vcloudair.query.QueryBase

The query results will be Edge records when using this class.

class vcloudair.query.OrgVdcQuery(org_info=None, version=None, vcdurl=None, token=None)

Bases: vcloudair.query.QueryBase

The query results will be OrgVDC records when using this class.

class vcloudair.query.QueryBase(org_info=None, version=None, vcdurl=None, token=None)

Bases: object

This is the base class for vCD queries. It can be instantiated on its own but some additional configuration will need to happen to get it to actually return query results.

Manipulating the params dictionary will dictate how the results are returned and for what type of record. The inheriting query classes are simply shortcuts for those changes.

__init__(org_info=None, version=None, vcdurl=None, token=None)

Base query class for using the query API within vCloud Director. There are child classes which are helper classes to make querying specific objects easier.

Parameters:
  • org_info (dict) – Dictionary containing org login data
  • version (str) – API version string, e.g: ‘5.6’
  • vcdurl (str) – vCD base URL
  • token (str) – vCD authorization token
execute()

Executes the query by sending a web request to the vCD API

Returns:Query results in dict format instead of XML
Return type:dict
find_by_name(name)

Search the query results by friendly name and return a list of UUIDs that contain the matching name attribute. Since name is not unique, there may be multiple results.

Parameters:name (str) – The friendly name of the object
Returns:Resulting UUIDs
Return type:list
set_fields(*fields)

The fields to be returned in each query record. Refer to vCD documentation for the list of fields available to each query type.

Parameters:fields – Field names to be concatenated into the fields parameter
Returns:None
set_query_type(qtype)

Sets the type of the query, e.g: vm, edge, vapp, etc. Check vCD documentation for available types.

Parameters:qtype (str) – Query type to be appended to query
Returns:None
class vcloudair.query.VAppQuery(org_info=None, version=None, vcdurl=None, token=None)

Bases: vcloudair.query.QueryBase

The query results will be vApp records when using this class.

class vcloudair.query.VAppTemplateQuery(org_info=None, version=None, vcdurl=None, token=None)

Bases: vcloudair.query.QueryBase

The query results will be vApp Template records when using this class.

class vcloudair.query.VMQuery(org_info=None, version=None, vcdurl=None, token=None)

Bases: vcloudair.query.QueryBase

The query results will be VM records when using this class.

vCloud Air Sessions

The VCA session module handles logging into vCloud Air and subsequent virtual datacenters within the service offering.

For Virtual Private Clouds (VPC) and Dedicated Clouds (DC) multiple virtual datacenters (vDCs) can be logged into at once. The Session class will store the tokens for the vDCs and allow them to be looked up by vDC name in the key format: session[vdc].

For On-Demand environments, an instance can be logged into via its index number. The index numbers can be found through the method call show_instance_list() on the On-Demand session class instance.

class vcloudair.session.VCAODSession(version='5.7', username=None, password=None)

Bases: object

This session class handles the newer on-demand architecture. Like the main session class, this can also handle multiple vCD login tokens.

__init__(version='5.7', username=None, password=None)

Used to create login sessions and On-Demand instance sessions within vCloud Air

Parameters:
  • version (str) – Version of the API to interact with
  • username (str) – vCA Username
  • password (str) – vCA Password
login(username=None, password=None)

Log into the On-Demand top-level system and generate a list of available instances.

Parameters:
  • username (str) – vCA Username
  • password (str) – vCA Password
Returns:

None

login_to_instance(idx)

Log into a specific instance within the On-Demand infrastructure and issue an auth token that can be used for further operations

Parameters:idx (int) – Index of the instance in self.instances to log into
Returns:Login information for the session that was created
Return type:dict
show_instance_list()

Prints out the current list of OD instances and their indexes in a human-readable format

Returns:None
class vcloudair.session.VCASession(version='5.6', username=None, password=None)

Bases: object

This is the session class to handle VPC / Dedicated instances. This uses the older vchs platform instead of the on-demand platform.

Each session class can handle and track multiple vCD login tokens.

__init__(version='5.6', username=None, password=None)

Create login sessions to vCA (root) and vCD (child) orgs.

Parameters:
  • version (str) – API version number, e.g: ‘5.6’
  • username (str) – vCloud Air username
  • password (str) – vCloud Air password
login(username=None, password=None, orgname='', vcd_url=None)

Log into either the vCA main portal or directly into a vCloud Director instance.

Parameters:
  • username (str) – vCloud Air Username
  • password (str) – vCloud Air Password
  • orgname (str) – vCloud Director Org Name
  • vcd_url (str) – URL to a vCD Instance
Returns:

None or Org login details

login_to_vdc(orgname)

Create a login session to a specific VDC based on the org name specified

Note: The org name refers to the actual Org name and not the VDC name. Usually they are the same, but the VDC name may be different. While not the case in vCloud Air today (2016), a single Org may contain multiple VDCs.

Parameters:orgname (str) – The orgname for which to create the session
Returns:Dict of org data from the login: UUID, Token, APIURL
Return type:dict

Utility Module

This is a small utility module where utility classes and functions can be stored and exported.

class vcloudair.util.ThreadPool(num_workers)

Bases: object

Parameters:num_workers (int) – The number of threads that exist in the pool

A basic thread pooling class to allow a set number of threads to pick up work items submitted to a queue. Threads are started as soon as the class is instantiated. They run in daemon mode and so will end if the main thread ends.

add(target, *args, **kwargs)

Adds a call to the thread pool along with the associated arguments and/or keyword arguments.

Parameters:
  • target (func) – The target callable object for the thread, usually a function.
  • args – The arguments to pass into the callable
  • kwargs – The keyword arguments to pass into the callable
Returns:

None

join()

Join against the internal queue datastructure until it’s empty. This is a blocking call which will force the program to wait until the queue is empty to continue with execution.

Returns:None
vcloudair.util.check_http_response_error(response)

Verify that the HTTP request did not return an error. If error is returned, raise a runtime exception with the status and reason.

Parameters:response – Requests response object
Returns:None
Raises:RuntimeError