title:Getting Started with the vRealize Automation REST API
posted:2022-06-03
tags:
See all 7 tags...["all", "vmware", "vra", "javascript", "vro", "automation", "rest", "api"]


Technology keeps moving but this post has not.

What you're about to read hasn't been updated in more than a year. The information may be out of date. Let me know if you see anything that needs fixing.

I've been doing a bit of work lately to make my vRealize Automation setup more flexible and dynamic and less dependent upon hardcoded values. To that end, I thought it was probably about time to learn how to interact with the vRA REST API. I wrote this post to share what I've learned and give a quick crash course on how to start doing things with the API.

Exploration Toolkit

Swagger

It can be difficult to figure out where to start when learning a new API. Fortunately, VMware thoughtfully included a Swagger specification for the API so that we can explore it in an interactive way. This is available for on-prem vRA environments at https://{vra-fqdn}/automation-ui/api-docs/ (so https://vra.lab.bowdre.net/automation-ui/api-docs/ in my case). You can also browse most of it online at www.mgmt.cloud.vmware.com/automation-ui/api-docs/1. Playing with Swagger on your on-prem instance will even let you perform requests straight from the browser, which can be a great way to gain familiarity with how requests should be structured.

The vRA Automation UI API Docs

I'm ultimately going to be working with the Infrastructure as a Service API but before I can do that I'll need to talk to the Identity API to log in. So let's start the exploration there, with the Login Controller.

Login Controller Request

That tells me that I'll need to send a POST request to the endpoint at /csp/gateway/am/api/login, and I'll need to include username, password, domain, and scope in the request body. I can click the Try it out button to take this endpoint for a spin and just insert appropriate values in the request:2 Trying it out

After hitting Execute, the Swagger UI will populate the Responses section with some useful information, like how the request would be formatted for use with curl: curl request format

So I could easily replicate this using the curl utility by just copying and pasting the following into a shell:

curl -X 'POST' \
'https://vra.lab.bowdre.net/csp/gateway/am/api/login' \
-H 'accept: */*' \
-H 'Content-Type: application/json' \
-d '{
"username": "vra",
"password": "********",
"domain": "lab.bowdre.net",
"scope": ""
}'

Scrolling further reveals the authentication token returned by the identity service: Authentication token

I can copy the contents of that cspAuthToken field and use it for authenticating other API operations. For instance, I'll go to the Infrastructure as a Service API Swagger UI and click the Authorize button at the top of the screen: Authorize me! And then paste the token into the header as Bearer [token]: Bearer bearing the token

Now I can go find an IaaS API that I'm interested in querying (like /iaas/api/flavor-profiles to see which flavor mappings are defined in vRA), and hit Try it out and then Execute: Using Swagger to query for flavor mappings

And here's the result:

1{
2 "content": [
3 {
4 "flavorMappings": {
5 "mapping": {
6 "1vCPU | 2GB [tiny]": {
7 "cpuCount": 1,
8 "memoryInMB": 2048
9 },
10 "1vCPU | 1GB [micro]": {
11 "cpuCount": 1,
12 "memoryInMB": 1024
13 },
14 "2vCPU | 4GB [small]": {
15 "cpuCount": 2,
16 "memoryInMB": 4096
17 }
18 }, { ... }
19 "_links": {
20 "region": {
21 "href": "/iaas/api/regions/3617c011-39db-466e-a7f3-029f4523548f"
22 }
23 }
24 },{ ... }
25 "externalRegionId": "Datacenter:datacenter-39056",
26 "cloudAccountId": "75d29635-f128-4b85-8cf9-95a9e5981c68",
27 "name": "",
28 "id": "61ebe5bf-5f55-4dee-8533-7ad05c067dd9-3617c011-39db-466e-a7f3-029f4523548f",
29 "updatedAt": "2022-05-05",
30 "organizationId": "61ebe5bf-5f55-4dee-8533-7ad05c067dd9",
31 "orgId": "61ebe5bf-5f55-4dee-8533-7ad05c067dd9",
32 "_links": {
33 "self": {
34 "href": "/iaas/api/flavor-profiles/61ebe5bf-5f55-4dee-8533-7ad05c067dd9-3617c011-39db-466e-a7f3-029f4523548f"
35 },
36 "region": {
37 "href": "/iaas/api/regions/3617c011-39db-466e-a7f3-029f4523548f"
38 }
39 }
40 },
41 {
42 "flavorMappings": {
43 "mapping": {
44 "2vCPU | 8GB [medium]": {
45 "cpuCount": 2,
46 "memoryInMB": 8192
47 },
48 "1vCPU | 2GB [tiny]": {
49 "cpuCount": 1,
50 "memoryInMB": 2048
51 },
52 "8vCPU | 16GB [giant]": {
53 "cpuCount": 8,
54 "memoryInMB": 16384
55 },
56 "1vCPU | 1GB [micro]": {
57 "cpuCount": 1,
58 "memoryInMB": 1024
59 },
60 "2vCPU | 4GB [small]": {
61 "cpuCount": 2,
62 "memoryInMB": 4096
63 },
64 "4vCPU | 12GB [large]": {
65 "cpuCount": 4,
66 "memoryInMB": 12288
67 }
68 }, { ... }
69 "_links": {
70 "region": {
71 "href": "/iaas/api/regions/c0d2a662-9ee5-4a27-9a9e-e92a72668136"
72 }
73 }
74 }, { ... }
75 "externalRegionId": "Datacenter:datacenter-1001",
76 "cloudAccountId": "75d29635-f128-4b85-8cf9-95a9e5981c68",
77 "name": "",
78 "id": "61ebe5bf-5f55-4dee-8533-7ad05c067dd9-c0d2a662-9ee5-4a27-9a9e-e92a72668136",
79 "updatedAt": "2022-05-05",
80 "organizationId": "61ebe5bf-5f55-4dee-8533-7ad05c067dd9",
81 "orgId": "61ebe5bf-5f55-4dee-8533-7ad05c067dd9",
82 "_links": {
83 "self": {
84 "href": "/iaas/api/flavor-profiles/61ebe5bf-5f55-4dee-8533-7ad05c067dd9-c0d2a662-9ee5-4a27-9a9e-e92a72668136"
85 },
86 "region": {
87 "href": "/iaas/api/regions/c0d2a662-9ee5-4a27-9a9e-e92a72668136"
88 }
89 }
90 }
91 ],
92 "totalElements": 2,
93 "numberOfElements": 2
94}

So that API call will tell me about the Flavor Profiles as well as which Region the profiles belong to.

As you can see, Swagger can really help to jump-start the exploration of a new API, but it can get a bit clumsy for repeated queries. And while I could just use curl for further API exercises, I'd rather use a tool built specifically for API tomfoolery:

HTTPie

HTTPie is a handy command-line utility optimized for interacting with web APIs. This will make things easier as I dig deeper.

Installing the Debian package is a piece of cake pie3:

curl -SsL https://packages.httpie.io/deb/KEY.gpg | sudo apt-key add -
sudo curl -SsL -o /etc/apt/sources.list.d/httpie.list https://packages.httpie.io/deb/httpie.list
sudo apt update
sudo apt install httpie

Once installed, running http will give me a quick overview of how to use this new tool:

http
usage:
http [METHOD] URL [REQUEST_ITEM ...]
 
error:
the following arguments are required: URL
 
for more information:
run 'http --help' or visit https://httpie.io/docs/cli

HTTPie cleverly interprets anything passed after the URL as a request item, and it determines the item type based on a simple key/value syntax:

Each request item is simply a key/value pair separated with the following characters: : (headers), = (data field, e.g., JSON, form), := (raw data field), == (query parameters), @ (file upload).

So my earlier request for an authentication token becomes:

https POST vra.lab.bowdre.net/csp/gateway/am/api/login username='vra' password='********' domain='lab.bowdre.net'

Working with Self-Signed Certificates

If your vRA endpoint is using a self-signed or otherwise untrusted certificate, pass the HTTPie option --verify=no to ignore certificate errors:

https --verify=no POST [URL] [REQUEST_ITEMS]

Running that will return a bunch of interesting headers but I'm mainly interested in the response body:

{
"cspAuthToken": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IjI4NDY0MjAzMzA2NDQwMTQ2NDQifQ.eyJpc3MiOiJDTj1QcmVsdWRlIElkZW50aXR5IFNlcnZpY2UsT1U9Q01CVSxPPVZNd2FyZSxMPVNvZmlh[...]HBOQQwEepXTNAaTv9gWMKwvPzktmKWyJFmC64FGomRyRyWiJMkLy3xmvYQERwxaDj_15-npz4Csv5FwcXt0fa"
}

There's the auth token4 that I'll need for subsequent requests. I'll store that in a variable so that it's easier to wield:

token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IjI4NDY0MjAzMzA2NDQwMTQ2NDQifQ.eyJpc3MiOiJDTj1QcmVsdWRlIElkZW50aXR5IFNlcnZpY2UsT1U9Q01CVSxPPVZNd2FyZSxMPVNvZmlh[...]HBOQQwEepXTNAaTv9gWMKwvPzktmKWyJFmC64FGomRyRyWiJMkLy3xmvYQERwxaDj_15-npz4Csv5FwcXt0fa

So now if I want to find out which images have been configured in vRA, I can ask:

https GET vra.lab.bowdre.net/iaas/api/images "Authorization: Bearer $token"

Request Items

Remember from above that HTTPie will automatically insert key/value pairs separated by a colon into the request header.

And I'll get back some headers followed by an JSON object detailing the defined image mappings broken up by region:

1{
2 "content": [
3 {
4 "_links": {
5 "region": {
6 "href": "/iaas/api/regions/3617c011-39db-466e-a7f3-029f4523548f"
7 }
8 },
9 "externalRegionId": "Datacenter:datacenter-39056",
10 "mapping": {
11 "Photon 4": {
12 "_links": {
13 "region": {
14 "href": "/iaas/api/regions/3617c011-39db-466e-a7f3-029f4523548f"
15 }
16 },
17 "cloudConfig": "",
18 "constraints": [],
19 "description": "photon-arm",
20 "externalId": "50023810-ae56-3c58-f374-adf6e0645886",
21 "externalRegionId": "Datacenter:datacenter-39056",
22 "id": "8885e87d8a5898cf12b5abc3e5c715e5a65f7179",
23 "isPrivate": false,
24 "name": "photon-arm",
25 "osFamily": "LINUX"
26 }
27 }
28 },
29 {
30 "_links": {
31 "region": {
32 "href": "/iaas/api/regions/c0d2a662-9ee5-4a27-9a9e-e92a72668136"
33 }
34 },
35 "externalRegionId": "Datacenter:datacenter-1001",
36 "mapping": {
37 "Photon 4": {
38 "_links": {
39 "region": {
40 "href": "/iaas/api/regions/c0d2a662-9ee5-4a27-9a9e-e92a72668136"
41 }
42 },
43 "cloudConfig": "",
44 "constraints": [],
45 "description": "photon",
46 "externalId": "50028cf1-88b8-52e8-58a1-b8354d4207b0",
47 "externalRegionId": "Datacenter:datacenter-1001",
48 "id": "d417648249e9740d7561188fa2a3a3ab4e8ccf85",
49 "isPrivate": false,
50 "name": "photon",
51 "osFamily": "LINUX"
52 },
53 "Windows Server 2019": {
54 "_links": {
55 "region": {
56 "href": "/iaas/api/regions/c0d2a662-9ee5-4a27-9a9e-e92a72668136"
57 }
58 },
59 "cloudConfig": "",
60 "constraints": [],
61 "description": "ws2019",
62 "externalId": "500235ad-1022-fec3-8ad1-00433beee103",
63 "externalRegionId": "Datacenter:datacenter-1001",
64 "id": "7e05f4e57ac55135cf7a7f8b951aa8ccfcc335d8",
65 "isPrivate": false,
66 "name": "ws2019",
67 "osFamily": "WINDOWS"
68 }
69 }
70 }
71 ],
72 "numberOfElements": 2,
73 "totalElements": 2
74}

This doesn't give me the name of the regions, but I could use the _links.region.href data to quickly match up images which exist in a given region.5

You'll notice that HTTPie also prettifies the JSON response to make it easy for humans to parse. This is great for experimenting with requests against different API endpoints and getting a feel for what data can be found where. And firing off tests in HTTPie can be a lot quicker (and easier to format) than with other tools.

Now let's take what we've learned and see about implementing it as vRO actions.

vRealize Orchestrator actions

My immediate goal for this exercise is create a set of vRealize Orchestrator actions which take in a zone/location identifier from the Cloud Assembly request and return a list of images which are available for deployment there. I'll start with some utility actions to do the heavy lifting, and then I'll be able to call them from other actions as things get more complicated/interesting. Before I can do that, though, I'll need to add the vRA instance as an HTTP REST endpoint in vRO.

This post brought to you by...

A lot of what follows was borrowed heavily from a very helpful post by Oktawiusz Poranski over at Automate Clouds so be sure to check out that site for more great tips on working with APIs!

Creating the endpoint

I can use the predefined Add a REST host workflow to create the needed endpoint. Add a REST host workflow - host properties

Configuring the host properties here is very simple: just give it a name and the URL of the vRA instance.

Add a REST host workflow - authentication On the Authentication tab, I set the auth type to NONE; I'll handle the authentication steps directly.

With those parameters in place I can kick off the workflow. Once it completes, I can check Administration > Inventory > HTTP-REST to see the newly-created endpoint: New HTTP-REST endpoint

Creating a Configuration for the endpoint

I don't want to hardcode any endpoints or credentials into my vRO actions so I'm also going to create a Configuration to store those details. This will make it easy to reference those same details from multiple actions as well.

To create a new Configuration, I'll head to Assets > Configurations, select a folder (or create a new one) where I want the Configuration to live, and then click the New Configuration button. Location of the Configurations

I'm going to call this new Configuration Endpoints since I plan to use it for holding host/credentials for additional endpoints in the future. After giving it a name, I'll go ahead and click Save to preserve my efforts thus far.

Creating the new Configuration

I'll then click over to the Variables tab and create a new variable to store my vRA endpoint details; I'll call it vRAHost, and hit the Type dropdown and select New Composite Type.

Creating the new variable

This new composite type will let me use a single variable to store multiple values - basically everything I'll need to interact with a single REST endpoint:

VariableType
hostREST:RESTHost
usernamestring
domainstring
passwordSecureString

Creating a new composite type

I can then map the appropriate values for this new variable and hit Create. Assigning values to the vRAHost

I make sure to Save my work and then gaze at the new Configuration's majesty: Newly-created Configuration

Okay, enough prep work - let's get into some Actions!

Utility actions

getConfigValue action

I'll head into Library > Actions to create a new action inside my com.virtuallypotato.utility module. This action's sole purpose will be to extract the details out of the configuration element I just created. Right now I'm only concerned with retrieving the one vRAHost configuration but I'm a fan of using generic pluggable modules where possible. This one will work to retrieve the value of any variable defined in any configuration element so I'll call it getConfigValue.

getConfigValue action

InputTypeDescription
pathstringPath to Configuration folder
configurationNamestringName of Configuration
variableNamestringName of desired variable inside Configuration
1/*
2JavaScript: getConfigValue action
3 Inputs: path (string), configurationName (string), variableName (string)
4 Return type: string
5*/
6 
7var configElement = null;
8for each (configElement in Server.getConfigurationElementCategoryWithPath(path).configurationElements) {
9 if (configElement.name.indexOf(configurationName) === 0) { break; };
10}
11var attribValue = configElement.getAttributeWithKey(variableName).value;
12return attribValue;
vraLogin action

Next, I'll create another action in my com.virtuallypotato.utility module which will use the getConfigValue action to retrieve the endpoint details. It will then submit a POST request to that endpoint to log in, and it will return the authentication token. Later actions will be able to call upon vraLogin to grab a token and then pass that back to the IaaS API in the request headers - but I'm getting ahead of myself. Let's get the login sorted:

vraLogin action

1/*
2JavaScript: vraLogin action
3 Inputs: none
4 Return type: string
5*/
6var restHost = System.getModule("com.virtuallypotato.utility").getConfigValue("vPotato", "Endpoints", "vRAHost");
7var host = restHost.host;
8var loginObj = {
9 domain: restHost.domain,
10 password: restHost.password,
11 username: restHost.username
12};
13var loginJson = JSON.stringify(loginObj);
14var request = host.createRequest("POST", "/csp/gateway/am/api/login", loginJson);
15request.setHeader("Content-Type", "application/json");
16var response = request.execute();
17var token = JSON.parse(response.contentAsString).cspAuthToken;
18System.debug("Created vRA API session: " + token);
19 
20return token;
vraLogout action

I like to clean up after myself so I'm also going to create a vraLogout action in my com.virtuallypotato.utility module to tear down the API session when I'm finished with it.

vraLogout action

InputTypeDescription
tokenstringAuth token of the session to destroy
1/*
2JavaScript: vraLogout action
3 Inputs: token (string)
4 Return type: string
5*/
6var host = System.getModule("com.virtuallypotato.utility").getConfigValue("vPotato", "Endpoints", "vRAHost").host;
7var logoutObj = {
8 idToken: token
9};
10var logoutJson = JSON.stringify(logoutObj);
11 
12var request = host.createRequest("POST", "/csp/gateway/am/api/auth/logout", logoutJson);
13request.setHeader("Content-Type", "application/json");
14request.execute().statusCode;
15System.debug("Terminated vRA API session: " + token);
vraExecute action

My final "utility" action for this effort will run in between vraLogin and vraLogout, and it will handle making the actual API call and returning the results. This way I won't have to implement the API handler in every single action which needs to talk to the API - they can just call my new action, vraExecute.

vraExecute action

InputTypeDescription
tokenstringAuth token from vraLogin
methodstringREST Method (GET, POST, etc.)
uristringPath to API controller (/iaas/api/flavor-profiles)
contentstringAny additional data to pass with the request
1/*
2JavaScript: vraExecute action
3 Inputs: token (string), method (string), uri (string), content (string)
4 Return type: string
5*/
6var host = System.getModule("com.virtuallypotato.utility").getConfigValue("vPotato", "Endpoints", "vRAHost").host;
7System.log(host);
8if (content) {
9 var request = host.createRequest(method, uri, content);
10} else {
11 var request = host.createRequest(method, uri);
12}
13request.setHeader("Content-Type", "application/json");
14request.setHeader("Authorization", "Bearer " + token);
15var response = request.execute();
16var statusCode = response.statusCode;
17var responseContent = response.contentAsString;
18if (statusCode > 399) {
19 System.error(responseContent);
20 throw "vraExecute action failed, status code: " + statusCode;
21}
22 
23return responseContent;
Bonus: vraTester action

That's it for the core utility actions - but wouldn't it be great to know that this stuff works before moving on to handling the request input? Enter vraTester! It will be handy to have an action I can test vRA REST requests in before going all-in on a solution.

This action will:

  1. Call vraLogin to get an API token.
  2. Call vraExecute with that token, a REST method, and an API endpoint to retrieve some data.
  3. Call vraLogout to terminate the API session.
  4. Return the data so we can see if it worked.

Other actions wanting to interact with the vRA REST API will follow the same basic formula, though with some more logic and capability baked in.

Anyway, here's my first swing:

1/*
2JavaScript: vraTester action
3 Inputs: none
4 Return type: string
5*/
6var token = System.getModule('com.virtuallypotato.utility').vraLogin();
7var result = JSON.parse(System.getModule('com.virtuallypotato.utility').vraExecute(token, 'GET', '/iaas/api/zones')).content;
8System.log(JSON.stringify(result));
9System.getModule('com.virtuallypotato.utility').vraLogout(token);
10return JSON.stringify(result);

Pretty simple, right? Let's see if it works: vraTester action

It did! Though that result is a bit hard to parse visually, so I'm going to prettify it a bit:

1[
2 {
3 "tags": [],
4 "tagsToMatch": [
5 {
6 "key": "compute",
7 "value": "nuc"
8 }
9 ],
10 "placementPolicy": "DEFAULT",
11 "customProperties": {
12 "zone_overlapping_migrated": "true"
13 },
14 "folder": "vRA_Deploy",
15 "externalRegionId": "Datacenter:datacenter-1001",
16 "cloudAccountId": "75d29635-f128-4b85-8cf9-95a9e5981c68",
17 "name": "NUC",
18 "id": "3d4f048a-385d-4759-8c04-117a170d060c",
19 "updatedAt": "2022-06-02",
20 "organizationId": "61ebe5bf-5f55-4dee-8533-7ad05c067dd9",
21 "orgId": "61ebe5bf-5f55-4dee-8533-7ad05c067dd9",
22 "_links": {
23 "projects": {
24 "hrefs": [
25 "/iaas/api/projects/9c3d1e73-1276-42e7-8d8e-cac40251a29e"
26 ]
27 },
28 "computes": {
29 "href": "/iaas/api/zones/3d4f048a-385d-4759-8c04-117a170d060c/computes"
30 },
31 "self": {
32 "href": "/iaas/api/zones/3d4f048a-385d-4759-8c04-117a170d060c"
33 },
34 "region": {
35 "href": "/iaas/api/regions/c0d2a662-9ee5-4a27-9a9e-e92a72668136"
36 },
37 "cloud-account": {
38 "href": "/iaas/api/cloud-accounts/75d29635-f128-4b85-8cf9-95a9e5981c68"
39 }
40 }
41 },
42 {
43 "tags": [],
44 "tagsToMatch": [
45 {
46 "key": "compute",
47 "value": "qtz"
48 }
49 ],
50 "placementPolicy": "DEFAULT",
51 "customProperties": {
52 "zone_overlapping_migrated": "true"
53 },
54 "externalRegionId": "Datacenter:datacenter-39056",
55 "cloudAccountId": "75d29635-f128-4b85-8cf9-95a9e5981c68",
56 "name": "QTZ",
57 "id": "84470591-74a2-4659-87fd-e5d174a679a2",
58 "updatedAt": "2022-06-02",
59 "organizationId": "61ebe5bf-5f55-4dee-8533-7ad05c067dd9",
60 "orgId": "61ebe5bf-5f55-4dee-8533-7ad05c067dd9",
61 "_links": {
62 "projects": {
63 "hrefs": [
64 "/iaas/api/projects/9c3d1e73-1276-42e7-8d8e-cac40251a29e"
65 ]
66 },
67 "computes": {
68 "href": "/iaas/api/zones/84470591-74a2-4659-87fd-e5d174a679a2/computes"
69 },
70 "self": {
71 "href": "/iaas/api/zones/84470591-74a2-4659-87fd-e5d174a679a2"
72 },
73 "region": {
74 "href": "/iaas/api/regions/3617c011-39db-466e-a7f3-029f4523548f"
75 },
76 "cloud-account": {
77 "href": "/iaas/api/cloud-accounts/75d29635-f128-4b85-8cf9-95a9e5981c68"
78 }
79 }
80 }
81]

I can see that it returned two Cloud Zones, named NUC (for my NUC 9 host) and QTZ (for my Quartz64 SBC running ESXi-ARM). Each Zone also includes data about other objects associated with the Zone, such as that _links.region.href property I mentioned earlier.

My compute targets live at the Zone level, each Zone lives inside a given Region, and the Image Profiles reside within a Region. See where this is going? I now have the information I need to link a Zone to the Image Profiles available within that Zone.

Input actions

So now I'm ready to work on the actions that will handle passing information between the vRA REST API and the Cloud Assembly deployment request form. For organization purposes, I'll stick them in a new module which I'll call com.virtuallypotato.inputs. And for the immediate purposes, I'm going to focus on just two fields in the request form: Zone (for where the VM should be created) and Image (for what VM template it will be spawned from). The Zone dropdown will be automatically populated when the form loads, and Image options will show up as soon as a the user has selected a Zone.

vraGetZones action

This action will basically just repeat the call that I tested above in vraTester, but parse the result to extract just the Zone names. It will pop those into an array of strings which can be rendered as a dropdown on the Cloud Assembly side.

vraGetZones action

1/*
2JavaScript: vraGetZones action
3 Inputs: none
4 Return type: Array/string
5*/
6var zoneNames = new Array();
7var token = System.getModule("com.virtuallypotato.utility").vraLogin();
8var zones = JSON.parse(System.getModule("com.virtuallypotato.utility").vraExecute(token, "GET", "/iaas/api/zones", null)).content;
9zones.forEach(
10 function (zone) {
11 zoneNames.push(zone.name);
12 }
13);
14zoneNames.sort();
15System.getModule("com.virtuallypotato.utility").vraLogout(token);
16return zoneNames;
vraGetImages action

Once the user has selected a Zone from the dropdown, the vraGetImages action will first contact the same /iaas/api/zones API to get the same list of available Zones. It will look through that list to find the one with the matching name, and then extract the ._links.region.href URI for the Zone.

Next it will reach out to /iaas/api/images to retrieve all the available images. For each image, it will compare its associated ._links.region.href URI to that of the designated Zone; if there's a match, the action will add the image to an array of strings which will then be returned back to the request form.

Oh, and the whole thing is wrapped in a conditional so that the code only executes when zoneName has been set on the request form; otherwise it simply returns an empty string.

InputTypeDescription
zoneNamestringThe name of the Zone selected in the request form
1/* JavaScript: vraGetImages action
2 Inputs: zoneName (string)
3 Return type: array/string
4*/
5if (!(zoneName == "" || zoneName == null)) {
6 var arrImages = new Array();
7 var regionUri = null;
8 var token = System.getModule("com.virtuallypotato.utility").vraLogin();
9 var zones = JSON.parse(System.getModule("com.virtuallypotato.utility").vraExecute(token, "GET", "/iaas/api/zones", null)).content;
10 System.debug("Zones: " + JSON.stringify(zones));
11 for each (zone in zones) {
12 if (zone.name === zoneName) {
13 System.debug("Matching zone: " + zone.name);
14 regionUri = zone._links.region.href;
15 }
16 if (regionUri != null) { break; };
17 }
18 System.debug("Matching region URI: " + regionUri);
19 var images = JSON.parse(System.getModule("com.virtuallypotato.utility").vraExecute(token, "GET", "/iaas/api/images", null)).content;
20 System.debug("Images: " + JSON.stringify(images));
21 images.forEach(
22 function (image) {
23 if (image._links.region.href === regionUri) {
24 System.debug("Images in region: " + JSON.stringify(image.mapping));
25 for (var i in image.mapping) {
26 System.debug("Image: " + i);
27 arrImages.push(i);
28 }
29 }
30 }
31 );
32 arrImages.sort();
33 System.getModule("com.virtuallypotato.utility").vraLogout(token);
34 return arrImages;
35} else {
36 return [""];
37}

I'll use the Debug button to test this action real quick-like, providing the NUC Zone as the input: vraGetImages action

It works! Well, at least when called directly. Let's see how it does when called from Cloud Assembly.

Cloud Assembly request

For now I'm really only testing using my new vRO actions so my Cloud Template is going to be pretty basic. I'm not even going to add any resources to the template; I don't even need it to be deployable.

Completely blank template

What I do need are two inputs. I'd normally just write the inputs directly as YAML, but the syntax for referencing vRO actions can be a bit tricky and I don't want to mess it up. So I pop over to the Inputs tab in the editor pane on the right and click the New Cloud Template Input button.

Need input!

I'll start with an input called zoneName, which will be a string: zoneName input

I'll then click on More Options and scroll to the bottom to select that the field data should come from an External Source: zoneName more options

I click the Select button and can then search for the vraGetZones action I wish to use: zoneName selecting the action

And then hit Create to add the new input to the template.

Next I'll repeat the same steps to create a new image input. This time, though, when I select the vraGetImages action I'll also need to select another input to bind to the zoneName parameter: Binding the input

The full code for my template now looks like this:

1formatVersion: 1
2inputs:
3 zoneName:
4 type: string
5 title: Zone
6 $dynamicEnum: /data/vro-actions/com.virtuallypotato.inputs/vraGetZones
7 image:
8 type: string
9 title: Image
10 $dynamicEnum: /data/vro-actions/com.virtuallypotato.inputs/vraGetImages?zoneName={{zoneName}}
11resources: {}

And I can use the Test button at the bottom of the Cloud Assembly template editor to confirm that everything works:

Testing the request fields

It does!

Conclusion

This has been a very quick introduction on how to start pulling data from the vRA APIs, but it (hopefully) helps to consolidate all the knowledge and information I had to find when I started down this path - and maybe it will give you some ideas on how you can use this ability within your own vRA environment.

In the near future, I'll also have a post on how to do the same sort of things with the vCenter REST API, and I hope to follow that up with a deeper dive on all the tricks I've used to make my request forms as dynamic as possible with the absolute minimum of hardcoded data in the templates. Let me know in the comments if there are any particular use cases you'd like me to explore further.

Until next time!


  1. The online version is really intended for the vRealize Automation Cloud hosted solution. It can be a useful reference but some APIs are missing. ↩︎

  2. This request form is pure plaintext so you'd never have known that my password is actually ******** if I hadn't mentioned it. Whoops! ↩︎

  3. GIF from Supernatural wherein Dean ogles some delicious pie. ↩︎

  4. Well, most of it. ↩︎

  5. That knowledge will come in handy later. ↩︎


Celebrate this post: 

runtimeterror  


 jbowdre