vrandom yet another random IT blog

vROps python api - nagini

Overview

In this post we’re going to briefly cover the steps required to begin exploring and consuming your vROps API with the Python binding. This environment will form the base for a series of other posts showing some ways in which the API can be utilized.

What you’ll need

A deployed vROps instance
A CentOS install

Preparation

To begin with you first need to have a working vROps install, if you haven’t then your first port of call should be the documentation homepage here and the full documentation here.

At this point you should have vROps configured and objects in your inventory. To check select Environment -> vSphere Hosts and Clusters -> vSphere World. Then expand your VC inventory: install completed

If you don’t have an environment to add to your vROps install then you should check out the vCenter Server Simulator. Using this you can feed your vROps environment with large simulated environment.

Now check your CentOS server can connect to your vROps instance by executing the below command, substituting the IP address or DNS name of your vROps instance:

[root@web01 ~]# curl -k https://vro01.lab.vrandom.com/
<html>
  <head>
    <META HTTP-EQUIV="content-type" CONTENT="text/html; charset=UTF-8">
    <!-- redirect immediately -->
    <meta http-equiv="refresh" content="0; url=vcops-web-ent/">
    <!-- and do not cache this file in the browser! -->
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="cache-control" content="no-store">
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="expires" content="-1">
  </head>
  <body>Redirecting to vRealize Operations Manager Web UI...</body>
</html>

Now lets install the python binding, in a web browser head to https://your server ip/suite-api/ you should be greeted by the below page: api page

Scroll to the bottom of the page to find the Python Client: python download

Copy the url to your clipboard: install completed In my lab the url was:
https://vro01.lab.vrandom.com/suite-api/docs/bindings/python/vcops-python.zip

Now return to your CentOS server and execute the below commands, substituting the url you copied earlier:

[root@web01 ~]# yum install -y unzip
<snip>
Installed:
  unzip.x86_64 0:6.0-15.el7                                                                                                                                                                                        

Complete!
[root@web01 ~]# curl -k https://vro01.lab.vrandom.com/suite-api/docs/bindings/python/vcops-python.zip -O
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 1422k  100 1422k    0     0  4335k      0 --:--:-- --:--:-- --:--:-- 4351k
[root@web01 ~]# cd vcops-python
[root@web01 vcops-python]# unzip ../vcops-python.zip 
Archive:  ../vcops-python.zip
   creating: deps/
   creating: nagini/
   creating: scripts/
  inflating: deps/requests-2.2.1-py2.6.egg  
  inflating: deps/requests-2.2.1-py2.7.egg  
  inflating: nagini/__init__.py      
  inflating: nagini/methods.json     
  inflating: nagini/nagini.py        
  inflating: scripts/README          
  inflating: setup.py                
[root@web01 vcops-python]# python setup.py install
<snip>
Installed /usr/lib/python2.7/site-packages/nagini-1.0-py2.7.egg
Processing dependencies for nagini==1.0
Finished processing dependencies for nagini==1.0
[root@web01 vcops-python]#

Now hopefully you’ve not had any problems with any dependancies (I had no problems with a fresh install of CentOS - If you do please comment below and I’ll add the dependencies in to the instructions) Lets test the nagini library is available with the below command:

[root@web01 vcops-python]# python
Python 2.7.5 (default, Jun 17 2014, 18:11:42) 
[GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import nagini
>>>

If you get an error such as “ImportError: No module named” then review your previous commands, as something’s gone wrong.

Lets get started

Using your favorite editor, create the below text file on your CentOS host

#!/usr/bin/python
print "Connecting to vROps"
import nagini
vcops = nagini.Nagini(host="vro01.lab.vrandom.com", user_pass=("admin", "yourpassword") )
print "Completed"

You should see no errors when running your script: connection test

Now here are some of the single most useful sets of python commands I know. Firstly when you execute python with a “-i” argument it causes an interactive shell to be spawned after the script has completed. Couple this with the two below lines of code enables you to autocomplete python commands:

import rlcompleter, readline
readline.parse_and_bind('tab:complete')

Lets explore!

[root@web01 ~]# python -i test.py 
Connecting to vROps
Completed
>>> import rlcompleter, readline
>>> readline.parse_and_bind('tab:complete')
>>>

Python is now waiting for your command. Type “vcops.” and hit ‘tab tab’, you should see the below:

>>> vcops.
Display all 216 possibilities? (y or n)
vcops.__class__(                                       vcops.delete_symptom_definition(                       vcops.get_stats_of_resources_csv(
vcops.__delattr__(                                     vcops.delete_user(                                     vcops.get_super_metric(
vcops.__dict__                                         vcops.delete_user_group(                               vcops.get_super_metrics(
vcops.__doc__                                          vcops.delete_user_groups(                              vcops.get_supported_application_versions(
vcops.__format__(                                      vcops.delete_user_role(                                vcops.get_supported_application_versions_0(
vcops.__getattribute__(                                vcops.delete_users(                                    vcops.get_symptom_definition_by_key(
vcops.__hash__(                                        vcops.do_request(                                      vcops.get_symptom_definitions(
vcops.__init__(                                        vcops.enumerate_adapter_instances(                     vcops.get_symptoms(
vcops.__module__                                       vcops.exclude_more_resources_from_custom_group(        vcops.get_task_status(
vcops.__new__(                                         vcops.fetch_links(                                     vcops.get_tasks_status(
vcops.__reduce__(                                      vcops.find_create_resource_push_data(                  vcops.get_top_n_stats_of_resource(
vcops.__reduce_ex__(                                   vcops.find_create_resource_with_adapter_key(           vcops.get_top_n_stats_of_resources(
vcops.__repr__(                                        vcops.find_create_resource_with_adapter_uuid(          vcops.get_traversal_specs(
vcops.__rest_methods_initialized                       vcops.get_adapter_instance(                            vcops.get_user(
vcops.__setattr__(                                     vcops.get_adapter_instances_using_credential(          vcops.get_user_group(
vcops.__sizeof__(                                      vcops.get_adapter_type(                                vcops.get_user_groups(
vcops.__str__(                                         vcops.get_adapter_types(                               vcops.get_users(
vcops.__subclasshook__(                                vcops.get_alert(                                       vcops.included_more_resources_into_custom_group(
vcops.__weakref__                                      vcops.get_alert_definition_by_id(                      vcops.mark_adapter_instance_as_being_maintained(
vcops._add_methods(                                    vcops.get_alert_definitions(                           vcops.mark_resource_as_being_maintained(
vcops._api_version                                     vcops.get_alert_plugin_instance(                       vcops.mark_resources_as_being_maintained(
vcops._base_url                                        vcops.get_alert_plugin_type_with_id(                   vcops.merge_resources(
vcops._certs                                           vcops.get_alert_plugin_types(                          vcops.modify_alert_plugin_state(
vcops._gen_links                                       vcops.get_alert_plugins_of_type(                       vcops.modify_alerts(
vcops._path_regex                                      vcops.get_alert_types(                                 vcops.modify_custom_group(
vcops._rest_request(                                   vcops.get_alerts(                                      vcops.modify_user(
vcops._verify                                          vcops.get_all_notification_rules(                      vcops.modify_user_group(
vcops.acquire_token(                                   vcops.get_auth_source(                                 vcops.patch_adapter_instance(
vcops.add_properties(                                  vcops.get_auth_source_type(                            vcops.patch_alert_plugin(
vcops.add_properties_using_push_adapter_kind(          vcops.get_auth_source_types(                           vcops.push_event(
vcops.add_relationship(                                vcops.get_auth_sources(                                vcops.push_event_by_adapter_kind_key(
vcops.add_role_privileges(                             vcops.get_available_privilege_groups(                  vcops.push_events(
vcops.add_stats(                                       vcops.get_available_privileges(                        vcops.push_events_by_adapter_kind_key(
vcops.add_stats_using_push_adapter_kind(               vcops.get_collectors(                                  vcops.query_alert(
vcops.assign_maintenance_schedule_to_resources(        vcops.get_credential(                                  vcops.query_email_templates(
vcops.assign_traversal_spec_to_user(                   vcops.get_credential_kinds(                            vcops.query_symptoms(
vcops.assign_traversal_spec_to_user_group(             vcops.get_credentials(                                 vcops.release_token(
vcops.build_resource_key(                              vcops.get_current_version_of_server(                   vcops.remove_role_privileges(
vcops.change_password(                                 vcops.get_custom_group(                                vcops.replaced_excluded_resources_of_custom_group(
vcops.client                                           vcops.get_custom_groups(                               vcops.replaced_included_resources_of_custom_group(
vcops.close(                                           vcops.get_email_template(                              vcops.resource_push_data(
vcops.create_adapter_instance(                         vcops.get_latest_stats(                                vcops.set_auth_token(
vcops.create_alert_definition(                         vcops.get_latest_stats_of_resources(                   vcops.set_email_condition(
vcops.create_alert_plugin(                             vcops.get_latest_stats_of_resources_csv(               vcops.set_relationship(
vcops.create_credential(                               vcops.get_maintenance_schedules(                       vcops.set_role_privileges(
vcops.create_custom_group(                             vcops.get_members_of_group(                            vcops.start_monitoring_resource(
vcops.create_email_template(                           vcops.get_notification_rule(                           vcops.start_monitoring_resources(
vcops.create_maintenance_schedules(                    vcops.get_recommendation_by_id(                        vcops.start_monitoring_resources_of_adapter_instance(
vcops.create_notification_plugin_rule(                 vcops.get_recommendations(                             vcops.stop_monitoring_resource(
vcops.create_recommendation(                           vcops.get_relationship(                                vcops.stop_monitoring_resources(
vcops.create_resource_kind(                            vcops.get_relationships(                               vcops.stop_monitoring_resources_of_adapter_instance(
vcops.create_resource_using_adapter_instance(          vcops.get_resource(                                    vcops.unassign_maintenance_schedule_to_resources(
vcops.create_resource_using_adapter_kind(              vcops.get_resource_properties(                         vcops.unmark_adapter_instance_as_being_maintained(
vcops.create_static_custom_group(                      vcops.get_resource_properties_list(                    vcops.unmark_resource_as_being_maintained(
vcops.create_super_metric(                             vcops.get_resource_type_attributes_for_adapter_type(   vcops.unmark_resources_as_being_maintained(
vcops.create_symptom_definition(                       vcops.get_resource_type_for_adapter_type(              vcops.unset_email_condition(
vcops.create_user(                                     vcops.get_resource_type_properties_for_adapter_type(   vcops.update_adapter_instance(
vcops.create_user_group(                               vcops.get_resource_types_for_adapter_type(             vcops.update_alert_definition(
vcops.create_user_role(                                vcops.get_resources(                                   vcops.update_alert_plugin(
vcops.delete_adapter_instance(                         vcops.get_resources_of_adapter_instance(               vcops.update_credential(
vcops.delete_alert_definition(                         vcops.get_resources_using_credential(                  vcops.update_describe_xml(
vcops.delete_alert_plugin(                             vcops.get_resources_with_adapter_and_resource_kind(    vcops.update_email_template(
vcops.delete_credential(                               vcops.get_resources_with_adapter_kind(                 vcops.update_geo_location_of_resource(
vcops.delete_custom_group(                             vcops.get_rest_end_points_of_server(                   vcops.update_maintenance_schedules(
vcops.delete_email_template(                           vcops.get_role_by_name(                                vcops.update_notification_plugin_rule(
vcops.delete_maintenance_schedules(                    vcops.get_role_privileges(                             vcops.update_recommendation(
vcops.delete_notification_plugin_rules(                vcops.get_roles(                                       vcops.update_resource(
vcops.delete_recommendation(                           vcops.get_rules_of_plugin(                             vcops.update_super_metric(
vcops.delete_relationship(                             vcops.get_stat_keys(                                   vcops.update_symptom_definition(
vcops.delete_resource(                                 vcops.get_stat_keys_of_resources(                      vcops.update_user_role(
vcops.delete_resources(                                vcops.get_stats_of_resource(                           vcops.upload_adapter_zip(
vcops.delete_super_metric(                             vcops.get_stats_of_resources(                          vcops.upload_describe_document(
>>>

Thats a lot of commands!
Lets try one, type “vcops.get_resources()”. Wow, thats a lot of information… Let make it more readable

>>> import pprint
>>> pp = pprint.PrettyPrinter(indent=4)
>>> pp.pprint(vcops.get_resources())

Okay, so its formatted them more nicely, but thats still a lot of information… Return to your web browser and click on the ‘REST API documentation’ link: documentation Now scroll to “/api/resources/getResources” documentation Here we find you can limit the types of resources returned, this may be done using the ‘resourceKind’ parameter. I’m also going to limit myself to a single result, to make the output more managable:

>>> pp.pprint(vcops.get_resources(resourceKind="VirtualMachine", pageSize=1))
{   u'pageInfo': {   u'page': 0, u'pageSize': 1, u'totalCount': 18},
    u'resourceList': [   {   u'badges': [   {   u'color': u'GREEN',
                                                u'score': 19.0,
                                                u'type': u'WORKLOAD'},
                                            {   u'color': u'GREEN',
                                                u'score': 6.1481058597564715,
                                                u'type': u'STRESS'},
                                            {   u'color': u'GREEN',
                                                u'score': 21.489967618361163,
                                                u'type': u'CAPACITY_REMAINING'},
                                            {   u'color': u'GREEN',
                                                u'score': 100.0,
                                                u'type': u'HEALTH'},
                                            {   u'color': u'GREEN',
                                                u'score': 100.0,
                                                u'type': u'EFFICIENCY'},
                                            {   u'color': u'GREEN',
                                                u'score': 0.0,
                                                u'type': u'RISK'},
                                            {   u'color': u'RED',
                                                u'score': 236.276611328125,
                                                u'type': u'RECLAIMABLE_CAPACITY'},
                                            {   u'color': u'GREEN',
                                                u'score': 0.0,
                                                u'type': u'FAULT'},
                                            {   u'color': u'GREEN',
                                                u'score': 79.71819701520187,
                                                u'type': u'TIME_REMAINING'},
                                            {   u'color': u'GREEN',
                                                u'score': 100.0,
                                                u'type': u'COMPLIANCE'},
                                            {   u'color': u'GREEN',
                                                u'score': 33.0,
                                                u'type': u'ANOMALY'}],
                             u'creationTime': 1428479723314,
                             u'dtEnabled': True,
                             u'identifier': u'0236fc82-4458-4737-a4ee-aae2ccd21a39',
                             u'resourceHealth': u'GREEN',
                             u'resourceHealthValue': 100.0,
                             u'resourceKey': {   u'adapterKindKey': u'VMWARE',
                                                 u'name': u'lab1-edge01-0',
                                                 u'resourceIdentifiers': [   {   u'identifierType': {   u'dataType': u'STRING',
                                                                                                        u'isPartOfUniqueness': False,
                                                                                                        u'name': u'VMEntityName'},
                                                                                 u'value': u'lab1-edge01-0'},
                                                                             {   u'identifierType': {   u'dataType': u'STRING',
                                                                                                        u'isPartOfUniqueness': True,
                                                                                                        u'name': u'VMEntityObjectID'},
                                                                                 u'value': u'vm-69'},
                                                                             {   u'identifierType': {   u'dataType': u'STRING',
                                                                                                        u'isPartOfUniqueness': True,
                                                                                                        u'name': u'VMEntityVCID'},
                                                                                 u'value': u'e2e1ee92-b394-4eac-924b-a1a3a33ba38c'}],
                                                 u'resourceKindKey': u'VirtualMachine'},
                             u'resourceStatusStates': [   {   u'adapterInstanceId': u'a6a8e3e5-9e92-41db-bf68-e28d5268dc73',
                                                              u'resourceState': u'STARTED',
                                                              u'resourceStatus': u'DATA_RECEIVING',
                                                              u'statusMessage': u''}]}]}

Okay, now we are talking, we can clearly see the VM that is being returned (in my case an edge device). Lets write a very simple script to print out the identifiers and names of all the VMs:

>>> for resource in vcops.get_resources(resourceKind="VirtualMachine")['resourceList']:
...   print resource['identifier'], resource['resourceKey']['name']
... 
0236fc82-4458-4737-a4ee-aae2ccd21a39 lab1-edge01-0
39e22d19-5103-4350-b29d-38d775d9fbad Guest Introspection (3)
42b4b0e7-7e99-4fa8-bdd4-176268d08075 vrli01.lab.vrandom.com
481e61bf-3b20-4f80-9271-2a6fd3ac1a58 vro01.lab.vrandom.com
5234207a-1f91-4d29-980d-7e3a4f1de21d NSX_Controller_0668685e-391c-45ce-8dff-ca0089da2085
652fff13-a62e-4e98-b892-29fe7b77984e lab1-router01-0
6e53167f-fc67-422d-b055-b2420268de39 kali
6e663731-c429-4167-a638-b9d3c1261c4f vr01.lab.vrandom.com
76bdcd19-47f7-43e2-a149-b680551f3c64 VMware Data Security (2)
8a37a83f-418a-4a25-854c-7e6828aec93d Guest Introspection (1)
b16e88dc-81cf-47ae-b3fd-46c3e26ad547 vcsa01.lab.vrandom.com
c9ffde9b-1f7c-4c8f-b1b7-42d26f0120c0 VMware Data Security (3)
ca9c60f6-ffdf-486c-9a8b-7ac36810a52a vco01.lab.vrandom.com
d931f5c7-189e-468b-849b-3d5f7c5b357e VMware Data Security (1)
f186bc48-babb-4739-94e0-0a513b7dd387 Guest Introspection (2)
f62aeb04-cdbf-4b53-87e2-d8a89ba7bdbc web01.lab.vrandom.com
f82cc7bd-d6ab-445f-b408-87058eff7d93 dc01.vrandom.com
faa47ed1-7915-45ae-a669-2393ecd89c75 nsx01.lab.vrandom.com

If we wanted this to be a standalone script you would have something like this:

#!/usr/bin/python
print "Connecting to vROps"
import nagini
vcops = nagini.Nagini(host="vro01.lab.vrandom.com", user_pass=("admin", "yourpassword") )
for resource in vcops.get_resources(resourceKind="VirtualMachine")['resourceList']:
  print resource['identifier'], resource['resourceKey']['name']
print "Completed"

This should have given you a good starting point for installing and exploring the vROps API, its amazingly rich and offers many opportunities for integration.

References

vROps Publications
vROps Documentation
vCenter Server Simulator

FIN