Archives For API

As with the rest of NSX for vSphere components any competent admin would like to configure a remote syslog server for the NSX Controllers, in my homelab I have vRealize Log Insight and recently I decided to configure it on my NSX Controllers and document the procedure here mostly as self-reference.

NSX Manager has the option to configure a remote syslog server using its management web site, but where is the option for the Controllers? Well, if you lurk around NSX interface in vSphere Web Client will quickly notice that the option is somehow missing.  Actually the only option to enable it is using NSX REST API. Let’s see how to do it.

For this post I will use Firefox REST Client Add-on but you can use your favorite REST client. Firstly any REST API call will require at least the Authentication header, in Firefox REST Client click on Authentication drop-down menu, select Basic Authentication and enter the admin credentials.

Screen Shot 2015-09-30 at 02.25.19

Additionally PUT and POST methods will require you to set a custom header with the following values that will define the content of the HTTP Request body. Use these values.

  • Name: Content-Type
  • Value: application/xml

With these two headers set enter the API URL, in my case it is:

https://nsxm-01.mcorp.local/api/2.0/vdn/controller/controller-1/syslog

To construct this URL you will need the controller ID that can be get in the NSX interface in vSphere Web Client as shown below.

Screen Shot 2015-09-30 at 02.50.38

Select POST as the method. You will need to enter the body for the HTTP Request, in XML format. Use the below code as an example to build the content for the HTTP Request body.

This XML code will indicate the NSX Manager to set the IP address in the syslogServer node as the remote syslog server for the controller in the URL. The protocol, port and log level are also defined.

Screen Shot 2015-09-17 at 01.14.19

Submit the request and if everything is configured as described you will receive a 200 OK status code.

Screen Shot 2015-09-17 at 01.15.06

At this point the syslog server is configured for all NSX Controllers, you can check the status using also an API call with the same URL and selecting GET method.

Comments are welcome.

Juanma.

In the first post of the series we discussed Chargeback API basics and how to interact with it using Firefox REST Client. In this second and final post we will see how Chargeback integrates with vCenter Orchestrator.

VMware provides a plugin for the integration between vCO and CBM, however there some caveats with that plugin. First it is for version 2.0 and to be able to use it with 2.5 or above there are some changes to perform, the whole process is described in VMware KB 203145.

Second gotcha of the plugin is that it doesn’t cover every possible API within Chargeback, yes you heard it correctly. To cover those parts we need to use the vCO plugin for REST APIs, of course this plugin needs some configuration before being able to interact with Chargeback but will see later how to do it.

Add Chargeback server to vCenter Orchestrator inventory

Open vCenter Orchestrator configuration website at https://vco_server:8283 and install Chargeback and REST plugins. I’m not going to describe the process of installing a plugin since it is fairly well documented in vCO documentation.

Next we need to import Chargeback SSL certificate, go to Network and then to SSL Trust Manager tab. Enter Chargeback server URL in the Import from URL textbox and click Import.

image

A screen with the details of our Chargeback server will appear, click Import to accept the certificate.

image

Now from the Chargeback (2.0.0) area go to New Server tab, enter Chargeback server details and click Apply Changes.

image

In vCO client our new Chargeback server will appear.

image

Using vCO plugin for Chargeback Integration

vCenter Orchestrator plugin for Chargeback allows to perform several administration tasks in a Chargeback server and also cost management and configuration tasks. Following are several example workflows for both type of actions.

List all hierarchies

We are going to automate a very easy task as our first example. Create a new workflow and name it List Hierarchies. As workflow parameters add:

  • cbmServer – Your Chargeback server. Type Chargeback:ChargebackServer.
  • cbmVersion – Chargeback API version, 2.0. Type string.
  • hierarchyList – The list of hierarchies- Type Array/Chargeback:Hierarchy.

In the Schema tab drag an Action element, a new windows will pop up to choose the action. Search for getAllHiearchies and select it.

image

Check that the workflows attributes are correctly mapped as the input (cbmServer and cbmVersion) and output (hierarchyList) parameters of the action.

Next add a Scriptable task element to the workflow and edit it. Map hierarchyList attribute as input parameter. In the Scripting tab paste this code.

Validate the workflow and save it. The scheme has to look like this.

image

In the execution go to the Logs sub-tab in the main Scheme tab to check the results of the execution, if everything went as expected you should see something similar to the screenshot.

image

You should be thinking that this example is a bit silly, and to be honest it is. There are few use cases that will require to dump the hierarchy list to vCO log. The purpose of this workflow is to illustrate Chargeback plugin Action elements. Open vCO API Explorer and have a look at all the already implemented Actions that can be used in your workflows.

image

From basic administration tasks to search and reporting. Also Chargeback plugin comes with a set of Scripting Classes and objects that cover all Chargeback objects although as I mentioned before not all available methods are implemented.

image

Make a call to a method from a scripting class is relatively easy as we will see in the following example. We want to get a hierarchy and later use in a different task. We can use a method from CbServer class: getHierarchyByName. It accepts the hierarchy name and CBM API version as parameters. Basic syntax would be:

The hierarchy scripting object is now instantiated and we can get any property from it, like its ID.

Using vCO HTTP-REST plugin with Chargeback

vCenter Orchestrator has available an HTTP-REST plugin that enables it to interface with systems without a plugin or, like CBM case, to be able to execute some operations not implemented in the plugin. Current vCO plugin doesn’t have implemented the possibility to manage fixed costs in Chargeback. However using the plugin for REST APIs we can circumvent that shortage. But before creating any workflow we need to configure the REST plugin for Chargeback.

Configure REST plugin

vCenter Orchestrator plugin for REST APIs comes with a set of workflows for configuration purposes.

image

We need to add first our Chargeback server as REST host. Launch the Add a REST host workflow. Enter the name of the REST host and the base URL for the API, leave the timeout settings with the default values.

image

In the next two steps select Basic authentication mode…

image

…shared session and enter Chargeback server credentials.

image

Click submit and have a look at the workflow execution.

If everything went fine we cam see our new REST host in vCO inventory under HTTP-REST. Next step is add the API operations we need to execute using this plugin. Or course you have to add a Login and Logout operation and for our example we are going to add the following ones:

  • Create new Hierarchy
  • Add new Fixed Cost
  • Get Task Status – We will not use this one in any of the workflows of the post but I decided to add it to show how to add URL parameters

Launch Add a REST operation workflow and enter the following parameters:

  • Parent host – Our previously added REST host.
  • Name – a unique name for the operation.
  • Template URL – This the API signature in the case of Chargeback. The URL can contain placeholder for parameters to be provided during request phase of the operation.
  • HTTP Method .
  • Content Type – Optional parameter only for POST and PUT methods. Below are the screenshots and parameters for the five REST operations we need to add.

– Login:

image

 

– Logout:

image

– Create a new hierarchy:

image

– Add a new Fixed Cost:

image

– Get task status:

image

Look at in the inventory in vCenter Orchestrator client and check that all the new added operations appear under Chargeback REST host.

image

Now we can proceed to create our workflows.

Add a new Hierarchy to Chargeback

We are going to reproduce one the examples from Part 1 using vCO. First create a new empty workflow. As attributes we are going to use the following ones:

  • cbmVersion – Chargeback API version, 2.0.
  • cbmUser – User with administrative privileges in Chargeback
  • cbmPassword – Password of the above user
  • restLogin – Login REST Operation
  • restLogout – Logout REST Operation
  • restCreateHierarchy – Create hierarchy REST Operation
  • loginStatus – Status of the login REST Operation.

image

Next configure the input parameters, basically for our purposes here we will need the hierarchy name description.

image

At the presentation layer the parameters will shown as Name of the new hierarchy and Description for the new hierarchy.

image

Add two Scriptable tasks to the workflow, name the first as API Login and the second as API Logout and paste the code from the previous Login and Logout examples. Now add a third scriptable task to be executed after the login, name it as “Create Hierarchy” and edit it. Paste the below code in the Scripting tab.

Edit the API Login element and in the scripting tab add the following Javascript code.

With this chunk of code will suffice to launch the operation, however there is no error control. The HTTP status code is not enough because the login operation can fail even with a 200 code, like the example below.

image

To solve this we need to parse the response content. REST plugin scripting API provides a method to retrieve the content of the response as a string.

image

The following code will do the trick.

Firstly we need to convert the string to and array, then we get the second element of the array since and look for a successful status. The element has loginStatus as output parameter bind to the attribute of the same name. The System.log statements are not required but can be useful for troubleshooting purposes.

Add a Decision element to the workflow and bind the decision to the loginStatus parameter.

image

Change the failure branch of the decision from End workflow to Throw exception and bind it to loginStatus. With this decision element we can force the workflow to end the execution if the API login operation was unsuccessful.

Next edit the Create hierarchy element. Bind restCreateHierarchy, cbmUser, cbmPassword and cbmVersion attributes as input parameters, also bind hierarchyName and hierarchyDescription as input parameters.

image

In the scripting tab paste this code.

The last part, this is the REST operation output is optional but again it can be useful if we need to troubleshoot the workflows using vCO logs.

Our workflow is done and it should look like this.

image

Launch it and enter a name and a description to test it.

image

Click Submit, check the workflow logs for any errors and if everything went as expected go to Chargeback UI and see that the new hierarchy is there.

image

Add new Fixed Cost

For our second workflow we are going the same structure as before. hence the first task is duplicate our first workflow and edit the copy. As input parameters we will use:

  • cbmVersion – Chargeback API version, 2.0.
  • cbmUser – User with administrative privileges in Chargeback
  • cbmPassword – Password of the above user
  • restLogin – Login REST Operation
  • restLogout – Logout REST Operation
  • restAddFixed Cost – Add new fixed cost REST Operation
  • loginStatus – Status of the login REST Operation.

image

Very similar to the hierarchy one. However in this case as input parameters we will need much more information.

  • fixedCostName – Fixed Cost name
  • fixedCostDescription – Fixed Cost Description
  • fixedCostCurrency – ID for the currency. A full list of the currencies supported by Chargeback can be found in the API Reference. US Dollar is 104 and Euro 31.
  • isProrated – Configure the new fixed cost as prorated or not. Default value is true. Cannot be used with one-time fixed costs.
  • isPowerStateBased – Configure the fixed cost to be applied only if the virtual machine is powered on. It’s not mandatory, default value is false.
  • fixedCostType – Fixed cost type. A value of 0 represents a recurring fixed cost and 1 represents a one-time fixed cost. It’s not mandatory and the default value is 0.

image

Some of the input parameters are optional but we will use all to illustrate the example with all the possible details. At Presentation add a new property for the name and description to make them mandatory. You can also set the default values for the rest of the parameters.

image

Change the name of the second scriptable task to Add new Fixed Cost and edit it. Bind all the needed parameters and attributes.

image

In the XML payload we need to reflect all these parameters. Below is code for the scripting part.

Validate the workflow and save it. Execute it and fill in the input parameters.

image

Check in the Chargeback UI our newly created Fixed Cost.

image

We can also have a look at the API response in the workflow logs.

image

And we are done. This is the end of this two-post series and I hope that know you all have a better understanding of Chargeback API. As your next step my advice is to try to automate simple API tasks, even if they don’t seem to be very useful, and then combine thme into  more complex automation workflows along with vCenter and vCloud Director plugins.

In future posts I’ll show a couple of real world examples about how I have used CBM and REST plugins in some customer deployments.

Juanma.

vCenter Chargeback provides a fully featured API that allows to automate many tasks like user and rights management, cost configuration or reporting.

Chargeback API is a REST-based one, this means that it will receive requests and send responses using HTTP protocol and methods. CBM API implements a set of basic CRUD operations, and each of them maps with an HTTP method as shown in he below table.

POST CREATE
GET READ
PUT UPDATE/CREATE
DELETE DELETE

API syntax is actually very easy, it is composed of:

  • Request method
  • Base URL
  • API signature

It’s better illustrated with an example:

POST https://chargeback.corp.local/vCenter-CB/api/login?version=2.5

We can map the above example with the different elements of the API syntax:

We have also included the API version, I usually includes the version as an URL parameter but as we will see later is not really required. Some of the tasks will need also URL parameters that will be placed after the signature.

If there is need for more complex information either in the request or the response an XML payload have to be sent, just like in many other REST APIs. Even to perform a simple login an XML has to be sent, just like the next example.

For our first ride with CBM API we will use Firefox REST Client add-on, can be found here, this handy add-on provides a visual an easy way to quickly ramp up with any REST API. I personally have used it a lot with Chargeback to try the different API operations during a development project for a customer.

I’m not going to review every possible API, just a few examples to illustrate how it works.

imageLogin operation:

This is the most basic operation of all. In the REST Client paste the XML payload in the Body area, select POST as the method to use and fill the URL field.

 

Get hierarchy list:

Not every task needs an XML payload, in the following example we are going to get a list of the hierarchies using a GET method and with no message body. The URL to make the request would be:

https://<chargeback_server>/vCenter-CB/api/hierarchies?version=2.5

After executing the request we can see in the REST Client the response from Chargeback in XML format.

get_hierarchies

If we go to Chargeback web UI we’ll see the listed hierarchies.

hierarchy_cbm_ui

Get all Pricing Models:

Another simple request with no XML payload, with a similar syntax to the previous one:

GET https://<chargeback_server>/vCenter-CB/api/costModels?version=2.5

It will produce however a much more detailed response XML with the details of each of the configured Pricing Models.

<?xml version="1.0" encoding="UTF-8"?>
<Response xmlns="http://www.vmware.com/vcenter/chargeback/2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" status="success" isValidLicense="true">
  <CostModels>
    <CostModel id="31">
      <Name>Default Allocation Based Chargeback Pricing Model</Name>
      <Description>(DONT DELETE) This is only for optimization reports, only base rates are allowed for editing.</Description>
      <Currency id="104">
        <Name>USD</Name>
      </Currency>
    </CostModel>
    <CostModel id="30">
      <Name>Default Chargeback Pricing Model</Name>
      <Description>This is the default pricing model shipped with VMware vCenter Chargeback Manager.</Description>
      <Currency id="104">
        <Name>USD</Name>
      </Currency>
    </CostModel>
    <CostModel id="558">
      <Name>VMware Cloud Director Actual Usage Pricing Model</Name>
      <Description>Apply this pricing model to charge for actual usage in hierarchy</Description>
      <Currency id="104">
        <Name>USD</Name>
      </Currency>
    </CostModel>
    <CostModel id="548">
      <Name>VMware Cloud Director Allocation Pool Pricing Model</Name>
      <Description>Apply this pricing model on vDC with Allocation model as 'Allocation Pool' in hierarchy</Description>
      <Currency id="104">
        <Name>USD</Name>
      </Currency>
    </CostModel>
    <CostModel id="550">
      <Name>VMware Cloud Director Networks Pricing Model</Name>
      <Description>Apply this pricing model on organization networks in hierarchy</Description>
      <Currency id="104">
        <Name>USD</Name>
      </Currency>
    </CostModel>
    <CostModel id="556">
      <Name>VMware Cloud Director Overage Allocation Pool Pricing Model</Name>
      <Description>Apply this pricing model to charge for overage on vDC with Allocation model as 'Allocation Pool' in hierarchy</Description>
      <Currency id="104">
        <Name>USD</Name>
      </Currency>
    </CostModel>
    <CostModel id="554">
      <Name>VMware Cloud Director Pay As You Go - Fixed Charging Pricing Model</Name>
      <Description>Apply this pricing model for 'Fixed charging' on vDC with Allocation model as 'Pay As You Go' in hierarchy</Description>
      <Currency id="104">
        <Name>USD</Name>
      </Currency>
    </CostModel>
    <CostModel id="552">
      <Name>VMware Cloud Director Pay As You Go - Resource Based Charging Pricing Model</Name>
      <Description>Apply this pricing model for 'Resource based charging' on vDC with Allocation model as 'Pay As You Go' in hierarchy</Description>
      <Currency id="104">
        <Name>USD</Name>
      </Currency>
    </CostModel>
    <CostModel id="546">
      <Name>VMware Cloud Director Reservation Pool Pricing Model</Name>
      <Description>Apply this pricing model on vDC with Allocation model as 'Reservation Pool' in hierarchy</Description>
      <Currency id="104">
        <Name>USD</Name>
      </Currency>
    </CostModel>
  </CostModels>
</Response>

Add a new hierarchy:

invoked using a POST method, that corresponds with the CREATE operation from the table at the beginning of the post. The syntax for the request would be:

POST https://<chargeback_server>/vCenter-CB/api/hierarchy

In this case I’m not going to put the version as a parameter. An XML payload with the details of the new hierarchy is required.

image

Login to Chargeback web interface to check that the new hierarchy is there.

image

I hope that now you have at least a general understanding of how Chargeback API works and how easy is to interact with it. In the second post of the series we will review how to automate Chargeback using vCenter Orchestrator.

Juanma.

Anyone with some experience and knowledge about VMware HA knows how to perform a Reconfigure for HA operation in a host from the vSphere client and I’m no exception to that rule. However I never did with PowerCLI.

I created a new cluster in my homelab with a problem in one of the hosts, I fixed the problem, put my mind to work and after an hour or so digging through PowerCLI and the vSphere API Reference Documentation I came up with the following easy way to do it.

First we are going to create a variable that contained the configuration of the ESXi I wanted to reconfigure.

C:\
[vSphere PowerCLI] % $vmhost = Get-VMHost esxi06.vjlab.local
C:\
[vSphere PowerCLI] %
C:\
[vSphere PowerCLI] % $vmhost | Format-List

State                 : Connected
ConnectionState       : Connected
PowerState            : PoweredOn
VMSwapfileDatastoreId :
VMSwapfilePolicy      : Inherit
ParentId              : ClusterComputeResource-domain-c121
IsStandalone          : False
Manufacturer          : VMware, Inc.
Model                 : VMware Virtual Platform
NumCpu                : 2
CpuTotalMhz           : 5670
CpuUsageMhz           : 869
MemoryTotalMB         : 2299
MemoryUsageMB         : 868
ProcessorType         : Intel(R) Core(TM)2 Quad CPU    Q9550  @ 2.83GHz
HyperthreadingActive  : False
TimeZone              : UTC
Version               : 4.1.0
Build                 : 260247
Parent                : cluster3
VMSwapfileDatastore   :
StorageInfo           : HostStorageSystem-storageSystem-143
NetworkInfo           : esxi06:vjlab.local
DiagnosticPartition   : mpx.vmhba1:C0:T0:L0
FirewallDefaultPolicy :
ApiVersion            : 4.1
CustomFields          : {[com.hp.proliant, ]}
ExtensionData         : VMware.Vim.HostSystem
Id                    : HostSystem-host-143
Name                  : esxi06.vjlab.local
Uid                   : /VIServer=administrator@vcenter1.vjlab.local:443/VMHost=HostSystem-host-143/

C:\
[vSphere PowerCLI] %

Next with the cmdlet Get-View I retrieved the .NET objects of the host ID and stored them in another variable.

C:\
[vSphere PowerCLI] % Get-View $vmhost.Id

Runtime             : VMware.Vim.HostRuntimeInfo
Summary             : VMware.Vim.HostListSummary
Hardware            : VMware.Vim.HostHardwareInfo
Capability          : VMware.Vim.HostCapability
ConfigManager       : VMware.Vim.HostConfigManager
Config              : VMware.Vim.HostConfigInfo
Vm                  : {}
Datastore           : {Datastore-datastore-144}
Network             : {Network-network-11}
DatastoreBrowser    : HostDatastoreBrowser-datastoreBrowser-host-143
SystemResources     : VMware.Vim.HostSystemResourceInfo
Parent              : ClusterComputeResource-domain-c121
CustomValue         : {}
OverallStatus       : red
ConfigStatus        : red
ConfigIssue         : {0}
EffectiveRole       : {-1}
Permission          : {}
Name                : esxi06.vjlab.local
DisabledMethod      : {ExitMaintenanceMode_Task, PowerUpHostFromStandBy_Task, ReconnectHost_Task}
RecentTask          : {}
DeclaredAlarmState  : {alarm-1.host-143, alarm-101.host-143, alarm-102.host-143, alarm-103.host-143...}
TriggeredAlarmState : {}
AlarmActionsEnabled : True
Tag                 : {}
Value               : {}
AvailableField      : {com.hp.proliant}
MoRef               : HostSystem-host-143
Client              : VMware.Vim.VimClient

C:\
[vSphere PowerCLI] % $esxha = Get-View $vmhost.Id

Now through the $esxha variable I invoked the method ReconfigureHostForDAS to reconfigure the ESXi, this method is part of the HostSystem object and its description can be found here in the vSphere API reference.

As it can be seen in the above screenshot, the task is displayed in the vSphere client. You can also monitor the operation with the Get-Task cmdlet.

Finally I created the below script to simplify things in the future :-)

# Reconfigure-VMHostHA.ps1
# PowerCLI script to reconfigure for VMware HA a VM Host
#
# Juan Manuel Rey - juanmanuel (dot) reyportal (at) gmail (dot) com
# https://jreypo.wordpress.com
#

param([string]$esx)

$vmhost = Get-VMHost $esx
$esxha = Get-View $vmhost.Id
$esxha.ReconfigureHostForDAS()

Juanma.