Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
First Published: August 04, 2014
Americas Headquarters
Cisco Systems, Inc.
170 West Tasman Drive
San Jose, CA 95134-1706
USA
http://www.cisco.com
Tel: 408 526-4000
800 553-NETS (6387)
Fax: 408 527-0883
THE SPECIFICATIONS AND INFORMATION REGARDING THE PRODUCTS IN THIS MANUAL ARE SUBJECT TO CHANGE WITHOUT NOTICE. ALL STATEMENTS,
INFORMATION, AND RECOMMENDATIONS IN THIS MANUAL ARE BELIEVED TO BE ACCURATE BUT ARE PRESENTED WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED. USERS MUST TAKE FULL RESPONSIBILITY FOR THEIR APPLICATION OF ANY PRODUCTS.
THE SOFTWARE LICENSE AND LIMITED WARRANTY FOR THE ACCOMPANYING PRODUCT ARE SET FORTH IN THE INFORMATION PACKET THAT SHIPPED WITH
THE PRODUCT AND ARE INCORPORATED HEREIN BY THIS REFERENCE. IF YOU ARE UNABLE TO LOCATE THE SOFTWARE LICENSE OR LIMITED WARRANTY,
CONTACT YOUR CISCO REPRESENTATIVE FOR A COPY.
The Cisco implementation of TCP header compression is an adaptation of a program developed by the University of California, Berkeley (UCB) as part of UCB's public domain version
of the UNIX operating system. All rights reserved. Copyright © 1981, Regents of the University of California.
NOTWITHSTANDING ANY OTHER WARRANTY HEREIN, ALL DOCUMENT FILES AND SOFTWARE OF THESE SUPPLIERS ARE PROVIDED “AS IS" WITH ALL FAULTS.
CISCO AND THE ABOVE-NAMED SUPPLIERS DISCLAIM ALL WARRANTIES, EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, THOSE OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OR ARISING FROM A COURSE OF DEALING, USAGE, OR TRADE PRACTICE.
IN NO EVENT SHALL CISCO OR ITS SUPPLIERS BE LIABLE FOR ANY INDIRECT, SPECIAL, CONSEQUENTIAL, OR INCIDENTAL DAMAGES, INCLUDING, WITHOUT
LIMITATION, LOST PROFITS OR LOSS OR DAMAGE TO DATA ARISING OUT OF THE USE OR INABILITY TO USE THIS MANUAL, EVEN IF CISCO OR ITS SUPPLIERS
HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
Any Internet Protocol (IP) addresses and phone numbers used in this document are not intended to be actual addresses and phone numbers. Any examples, command display output, network
topology diagrams, and other figures included in the document are shown for illustrative purposes only. Any use of actual IP addresses or phone numbers in illustrative content is unintentional
and coincidental.
Cisco and the Cisco logo are trademarks or registered trademarks of Cisco and/or its affiliates in the U.S. and other countries. To view a list of Cisco trademarks, go to this URL: http://
www.cisco.com/go/trademarks. Third-party trademarks mentioned are the property of their respective owners. The use of the word partner does not imply a partnership
relationship between Cisco and any other company. (1110R)
© 2014
Cisco Systems, Inc. All rights reserved.
CONTENTS
Preface
Preface v
Audience v
Conventions v
Related Documentation vii
Documentation Feedback vii
Obtaining Documentation and Submitting a Service Request vii
CHAPTER 1
Overview 1
About Cisco UCS Director 1
About the Cloupia Script 2
CHAPTER 2
Working with the Cloupia Script 3
Logging Within the Cloupia Script 3
Determining the Workflow Submitter Information 4
Provisioning a Catalog Multiple Times 4
Resizing a Virtual Machine Disk 6
Understanding the Cloupia Script Interpreter 6
Testing a JavaScript 8
Testing a JavaScript of a Custom Task 8
CHAPTER 3
Managing Reports 9
Accessing Reports 9
Emailing Reports 11
APPENDIX A
Cloupia Script Samples 15
Invoking Another Workflow 15
Integrating with ServiceNow Ticketing 16
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
iii
Contents
Sending Emails from the Cloupia Script 17
Archiving Older Service Requests Automatically 18
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
iv
Preface
This preface contains the following sections:
• Audience, page v
• Conventions, page v
• Related Documentation, page vii
• Documentation Feedback, page vii
• Obtaining Documentation and Submitting a Service Request, page vii
Audience
This guide is intended primarily for data center administrators who use Cisco UCS Director and who have
responsibilities and expertise in one or more of the following:
• Server administration
• Storage administration
• Network administration
• Network security
• Virtualization and virtual machines
Conventions
Text Type
Indication
GUI elements
GUI elements such as tab titles, area names, and field labels appear in this font.
Main titles such as window, dialog box, and wizard titles appear in this font.
Document titles
Document titles appear in this font.
TUI elements
In a Text-based User Interface, text the system displays appears in this font.
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
v
Preface
Conventions
Text Type
Indication
System output
Terminal sessions and information that the system displays appear in this
font.
CLI commands
CLI command keywords appear in this font.
Variables in a CLI command appear in this font.
Note
Tip
[]
Elements in square brackets are optional.
{x | y | z}
Required alternative keywords are grouped in braces and separated by vertical
bars.
[x | y | z]
Optional alternative keywords are grouped in brackets and separated by vertical
bars.
string
A nonquoted set of characters. Do not use quotation marks around the string or
the string will include the quotation marks.
<>
Nonprinting characters such as passwords are in angle brackets.
[]
Default responses to system prompts are in square brackets.
!, #
An exclamation point (!) or a pound sign (#) at the beginning of a line of code
indicates a comment line.
Means reader take note. Notes contain helpful suggestions or references to material not covered in the
document.
Means the following information will help you solve a problem. The tips information might not be
troubleshooting or even an action, but could be useful information, similar to a Timesaver.
Caution
Means reader be careful. In this situation, you might perform an action that could result in equipment
damage or loss of data.
Timesaver
Means the described action saves time. You can save time by performing the action described in the
paragraph.
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
vi
Preface
Related Documentation
Warning
IMPORTANT SAFETY INSTRUCTIONS
This warning symbol means danger. You are in a situation that could cause bodily injury. Before you
work on any equipment, be aware of the hazards involved with electrical circuitry and be familiar with
standard practices for preventing accidents. Use the statement number provided at the end of each warning
to locate its translation in the translated safety warnings that accompanied this device.
SAVE THESE INSTRUCTIONS
Related Documentation
Cisco UCS Director Documentation Roadmap
For a complete list of Cisco UCS Director documentation, see the Cisco UCS Director Documentation
Roadmap available at the following URL: http://www.cisco.com/en/US/docs/unified_computing/ucs/
ucs-director/doc-roadmap/b_UCSDirectorDocRoadmap.html.
Cisco UCS Documentation Roadmaps
For a complete list of all B-Series documentation, see the Cisco UCS B-Series Servers Documentation Roadmap
available at the following URL: http://www.cisco.com/go/unifiedcomputing/b-series-doc.
For a complete list of all C-Series documentation, see the Cisco UCS C-Series Servers Documentation Roadmap
available at the following URL: http://www.cisco.com/go/unifiedcomputing/c-series-doc.
Note
The Cisco UCS B-Series Servers Documentation Roadmap includes links to documentation for Cisco
UCS Manager and Cisco UCS Central. The Cisco UCS C-Series Servers Documentation Roadmap includes
links to documentation for Cisco Integrated Management Controller.
Documentation Feedback
To provide technical feedback on this document, or to report an error or omission, please send your comments
to [email protected]. We appreciate your feedback.
Obtaining Documentation and Submitting a Service Request
For information on obtaining documentation, submitting a service request, and gathering additional information,
see the monthly What's New in Cisco Product Documentation, which also lists all new and revised Cisco
technical documentation.
Subscribe to the What's New in Cisco Product Documentation as a Really Simple Syndication (RSS) feed
and set content to be delivered directly to your desktop using a reader application. The RSS feeds are a free
service and Cisco currently supports RSS version 2.0.
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
vii
Preface
Obtaining Documentation and Submitting a Service Request
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
viii
CHAPTER
1
Overview
This chapter contains the following sections:
• About Cisco UCS Director, page 1
• About the Cloupia Script, page 2
About Cisco UCS Director
Cisco UCS Director (formerly Cisco Cloupia Unified Infrastructure Controller) is a 64-bit appliance that uses
the following standard templates:
• Open Virtualization Format (OVF) for VMware vSphere
• Virtual Hard Disk (VHD) for Microsoft Hyper-V
Cisco UCS Director delivers unified, highly secure management for the industry's leading converged
infrastructure solutions, which are based on the Cisco UCS and Cisco Nexus platforms.
Cisco UCS Director extends the unification of computing and network layers through Cisco UCS to provide
data center administrators with a comprehensive visibility and management capability. It supports NetApp
FlexPod and ExpressPod, EMC Isilon, EMC VSPEX, EMC VPLEX, and VCE Vblock systems, based on the
Cisco UCS and Cisco Nexus platforms.
Cisco UCS Director automates the provisioning of resource pools across physical, virtual, and baremetal
environments. It delivers native, automated monitoring for health, status, and resource utilization. You can
do the following using Cisco UCS Director:
• Create, clone, and deploy service profiles and templates for all servers and applications
• Monitor organizational usage, trends, and capacity across a converged infrastructure on a continuous
basis, such as by viewing heat maps that show virtual machine (VM) utilization across all your data
centers
• Deploy and add capacity to ExpressPod and FlexPod infrastructures in a consistent, repeatable manner
• Manage, monitor, and report on Cisco UCS domains and their components
• Extend virtual service catalogs to include physical infrastructures services
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
1
Overview
About the Cloupia Script
• Manage secure multitenant environments to accommodate virtualized workloads that run with
nonvirtualized workloads
About the Cloupia Script
The Cloupia script is a combination of JavaScript and Cloupia libraries, which you can execute from within
the Cloupia server platform. You can access subset of Cloupia Java APIs and objects from the script. The
Cloupia script supports all JavaScript syntax. However, browser-based objects are not supported because the
Cloupia script contains a server-side scripting.
Figure 1: Cloupia Script—Workflow
Three predefined top-level implicit variables or objects are in any Cloupia script:
• ctxt—This variable or object points to the Cloupia Workflow Execution context. Using this object, the
script can access information about the current workflow, task, input, output and can access the Cloupia
APIs. Using the Cloupia APIs, you can invoke the create, read, update, and delete (CRUD) operations,
workflow tasks, and expose other REST APIs. The ctxt object maps to the platform API:
com.cloupia.service.cIM.inframgr.customactions.CustomActionTriggerContext.
• logger—This variable or object points to the Cloupia workflow logger object. All scripts must add
reasonable amount of logging statements, which will be logged into the Service Request log. The logger
implicit object maps to the platform API:
com.cloupia.service.cIM.inframgr.customactions.CustomActionLogger.
• util—Few built-in utility concepts can be accessed using this variable or object. The util implicit object
maps to the platform API: com.cloupia.lib.util.managedreports.APIFunctions.
For more information about these platform APIs, see the Cloupia Script Javadoc.
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
2
CHAPTER
2
Working with the Cloupia Script
This chapter contains the following sections:
• Logging Within the Cloupia Script, page 3
• Determining the Workflow Submitter Information, page 4
• Provisioning a Catalog Multiple Times, page 4
• Resizing a Virtual Machine Disk, page 6
• Understanding the Cloupia Script Interpreter, page 6
Logging Within the Cloupia Script
The Cloupia script provides APIs that you can use to log messages into the Service Request log.
The log window provides the log details as follows:
Service Request ID: 789
May 17, 2013 11:48:15 UTC Request submitted
May 17, 2013 11:48:15 UTC Executing workflow item number 1
May 17, 2013 11:48:15 Completed workflow item number 1, with status Completed
May 17, 2013 11:48:21 UTC Executing workflow item number 2
May 17, 2013 11:48:21 UTC Trigger context executeWorkFlowStep called
May 17, 2013 11:48:21 UTC Executing custom action Initiator Groups (Delete VMAX Initiator
Group)
May 17, 2013 11:48:21 UTC Executing custom action Initiator Groups (Delete VMAX Initiator
Group)
May 17, 2013 11:49:18 UTC Initiator group deleted successfully.
May 17, 2013 11:49:18 UTC Task #1 (Initiator Groups (Delete VMAX Initiator Group)) completed
successfully in 56 seconds
May 17, 2013 11:49:18 UTC Input/Ouput values for Task #1 (Initiator Groups (Delete VMAX
Initiator Group));
May 17, 2103 11:49:18 UTC [Local Input: Select VMAX Initiator Group = Default
Datacenter@Vmax20K@192604812@CUIC_DV3]
May 17, 2103 11:49:18 UTC [Local Input: Do you want to delete selected initiator group name?
= null]
May 17, 2013 11:49:18 UTC Completed workflow item number 2, with status Completed
May 17, 2013 11:49:22 UTC Executing workflow item number 3
May 17, 2013 11:49:22 UTC Completed workflow item number 3, with status completed
The Logger object provides the following methods for logging:
• addDebug—Displays the debug messages in gray.
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
3
Working with the Cloupia Script
Determining the Workflow Submitter Information
• addInfo—Displays the normal messages in black.
• addWarning—Displays the warning messages in orange.
• addError—Displays the error messages in red.
The example of how these methods are used is as follows:
logger.addDebug(“About to process the user request”);
logger.addInfo(“User “+ctxt.getUserId()+” has requested to provision this”);
logger.addWarning(“Resource has reached maximum capacity.”);
logger.addError(“Failed to provision the resource”);
Determining the Workflow Submitter Information
Each workflow context has the user ID of the workflow submitter. This value is available through the script
APIs as well as the variables. The Cloupia script allows you to access the user details, such as the first name,
last name, email addresses, and so on.
This example uses the following workflow level variables for capturing and saving the information that is
retrieved by the script and used by other tasks:
• SUBMITTER_EMAIL
• SUBMITTER_FIRSTNAME
• SUBMITTER_LASTNAME
• SUBMITTER_GROUPNAME
var userId = ctxt.getUserId();
// Get the current workflow submitter’s profile
var userProfile = ctxt.getAPI().userAPIGetMyLoginProfile();
var firstName = userProfile.getFirstName();
var lastName = userProfile.getLastName();
var groupName = userProfile.getGroupName();
var groupId = userProfile.getGroupId();
var role = userProfile.getRole();
var email = userProfile.getEmail();
// Add some debug statements into SR log
logger.addDebug(“UserId=“+userId+”, Name=“+
firstName + “ “+ lastName +
“, Email=“+email+”, group=“+groupName+”, “+
“Role=“+role);
// Save into workflow variables as needed
ctxt.updateInput("SUBMITTER_EMAIL", email);
ctxt.updateInput("SUBMITTER_FIRSTNAME", firstName);
ctxt.updateInput("SUBMITTER_LASTNAME", lastName);
ctxt.updateInput("SUBMITTER_GROUPNAME", groupName);
Provisioning a Catalog Multiple Times
If you are trying to provision a catalog N number of times in a loop, you can use the following workflow
script to provision a catalog multiple times by creating child workflows and waiting for them to complete.
The workflow script uses the following workflow level variables:
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
4
Working with the Cloupia Script
Provisioning a Catalog Multiple Times
• Catalog
• vDC
• Provision Quantity
// Full Script
importPackage(java.util);
importPackage(java.lang);
importPackage(com.cloupia.model.cIM);
importPackage(com.cloupia.service.cIM.inframgr);
// Assume the names of the Input Variables as below
var CATALOG_ID = "Catalog";
var VDC_ID = "vDC";
var PROVISION_QTY = "Provision Quantity";
// Set the duration of the VMs as -1 (or number of hours)
var duration = -1;
// set begin time to now
var beginTime = -1;
var
var
var
var
catId = ctxt.getInput(CATALOG_ID);
vdcId = ctxt.getInput(VDC_ID);
quantity = ctxt.getInput(PROVISION_QTY);
delaySecondsBetweenInvocation = 30;
var
var
var
var
vdc = VDCUtil.getVDC(vdcId);
vdcName = vdc.getVdcName();
cat = VDCUtil.getVDCCatalogItem(catId);
catName = cat.getCatalogItemName();
logger.addInfo("CatalogName: " + catName + " vdcName: " + vdcName);
logger.addInfo("Provision Qty ="+quantity);
var qty = 1;
try {
qty = Integer.valueOf(quantity);
} catch(e) {
logger.addWarning("Invalid quantity specified:"+quantity+ " provisioning one VM");
}
var childSrIdArray = [];
var comment = "";
for (var ctr = 0; ctr < qty; ctr = ctr + 1)
{
logger.addInfo("Provision VM ="+ (ctr+1) + " of "+qty);
var srId = ctxt.getAPI().userAPISubmitServiceRequest(catName, vdcName ,
duration, beginTime, 1, comment);
childSrIdArray[ctr] = srId;
// Allow some delay between provisioning
sleep();
}
function sleep()
{
var milliseconds = delaySecondsBetweenInvocation * 1000;
Thread.sleep(milliseconds);
}
for (var i=0; i<childSrIdArray.length; i++)
{
var childSrId = childSrIdArray[i];
var status = ctxt.waitForCompletion(childSrId, 1800000);
if (status == 0)
{
logger.addInfo("Provisioned SR ID ="+ childSrId+ "
successfully.");
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
5
Working with the Cloupia Script
Resizing a Virtual Machine Disk
} else {
logger.addError("SR ID
="+ childSrId+ " failed");
}
}
Resizing a Virtual Machine Disk
After provisioning a virtual machine (VM), you can use the Cloupia script to resize the disk of a VM.
The following script uses the input variable called VMID which points to the VM that needs to be resized:
importPackage(java.lang);
importPackage(java.util);
importPackage(com.cloupia.model.cIM);
importPackage(com.cloupia.service.cIM.inframgr);
function resizeVmDisk(vmidstr, diskName, sizeInGB)
{
var vmid = Integer.parseInt(vmidstr);
// create the Context to
var vmcontext = util.createContext("vm", null, vmidstr);
// obtain VM details
var vminfo = ctxt.getAPI().getVMwareVMInfo(vmid);
var vmname = vminfo.getName();
var nameparam = new ActionParam("vmName", vmname);
var sizeparam = new ActionParam("vmSize", sizeInGB);
var diskparam = new ActionParam("vmDiskLabel", diskName);
var paramarr = [ nameparam, sizeparam, diskparam ];
logger.addInfo("About to resize VM "+vmidstr+" name="+vmname);
var status = ctxt.getAPI().performAction(vmcontext,"diskResize","Resizing VM for
testing the script",ctxt.getUserId(),paramarr);
logger.addInfo("status
= "+status);
}
var vmidstr1 = ctxt.getInput("VMID");
resizeVmDisk(vmidstr1, "Hard Disk 1", "10");
Understanding the Cloupia Script Interpreter
The Cloupia Script interpreter is a JavaScript interpreter populated with built-in libraries and APIs. You can
use the Cloupia Script interpreter to execute functions and to define variables and functions.
The Cloupia Script interpreter offers the following functions:
• PrintObj—Takes in an object and prints out all the properties and methods in the object. The print result
provides the values for variables in the object and functions that are available to be executed with the
object. When you call toString() on a JavaScript function, for example, myFunction.toString(), the
method signature of that function is returned.
This example shows how to display the properties and methods of the ReportContext object and how
to return the source code of the setCloudName function.
session started
> importPackage(com.cloupia.model.cIM);
> var ctx = new ReportContext();
> printObj(ctx);
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
6
Working with the Cloupia Script
Understanding the Cloupia Script Interpreter
properties =
cloudName:null
class:class com.cloupia.model.cIM.ReportContext
filterId:null
id:null
targetCuicId:null
type:0
ids:[Ljava.lang.String;@4de27bc5
methods =
setIds
jdoReplaceField
jdoReplaceFields
toString
getCloudName
wait
getClass
jdoReplaceFlags
hashCode
jdoNewInstance
jdoReplaceStateManager
jdoIsDetached
notify
jdoGetVersion
jdoProvideField
jdoCopyFields
jdoGetObjectId
jdoGetPersistenceManager
jdoCopyKeyFieldsToObjectId
jdoGetTransactionalObjectId
getType
getFilterId
setType
jdoIsPersistent
equals
setCloudName
jdoNewObjectIdInstance
jdoIsDeleted
getTargetCuicId
setId
setFilterId
jdoProvideFields
jdoMakeDirty
jdoIsNew
requiresCloudName
getIds
notifyAll
jdoIsTransactional
getId
jdoReplaceDetachedState
jdoIsDirty
setTargetCuicId
jdoCopyKeyFieldsFromObjectId
> var func = ctx.setCloudName;
> func
void setCloudName(java.lang.String)
> func.toString();
function setCloudName() {/*
void setCloudName(java.lang.String)
*/}
• Upload—Uploads a JavaScript file to load into the interpreter. You can save the codes on a separate
file and upload the file using the upload command.
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
7
Working with the Cloupia Script
Testing a JavaScript
Testing a JavaScript
You can use Launch Interpreter to test a JavaScript for syntax errors, before loading it into Cisco UCS
Director.
Step 1
Step 2
Step 3
On the menu bar, choose Policies > Orchestration.
Click the Custom Workflow Tasks tab.
Click Launch Interpreter.
The Cloupia Script Interpreter dialog box appears.
Step 4
Enter the JavaScript code and press Enter.
The code is executed and the result is displayed. If there is any syntax error in the code, the error is displayed.
Testing a JavaScript of a Custom Task
You can use the Launch Interpreter with Context action that appears on selection of a custom task, to
evaluate the JavaScript of a custom task. This action will launch an interpreter with all the global variables
that are defined for executing a custom task during creation.
When you launch the interpreter, the interpreter gets the value for input fields that you set up while developing
the custom task and populates the input object of the task. So that, all the variables, including input, output,
logger, ctxt, and so on, that are expected for executing the custom task are made available.
Step 1
Step 2
Step 3
Step 4
On the menu bar, choose Policies > Orchestration.
Click the Custom Workflow Tasks tab.
Choose a custom task for which you need to test the JavaScript.
Click Launch Interpreter with Context.
The Launch Interpreter dialog box appears with input fields to collect input values for the custom task. The input fields
are displayed based on the input defined during the custom task creation.
Step 5
Click Submit.
The JavaScript code defined for the custom task is executed and the result is displayed in the Cloupia Script Interpreter
dialog box. If there is any syntax error in the code, the error is displayed.
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
8
CHAPTER
3
Managing Reports
This chapter contains the following sections:
• Accessing Reports, page 9
• Emailing Reports, page 11
Accessing Reports
You can access the reports by using the Cloupia script. You can use the report data to make dynamic decisions
for subsequent tasks.
For example, to allocate an unassociated Cisco UCS B-Series Blade Server that is greater than 2GB, use the
following script to query the list of all Cisco UCS servers that are managed by a specific Cisco UCS Manager.
This script shows how to filter a subset of values selectively.
importPackage(java.lang);
importPackage(java.util);
importPackage(com.cloupia.lib.util.managedreports);
function getReport(reportContext, reportName)
{
var report = null;
try
{
report = ctxt.getAPI().getConfigTableReport(reportContext, reportName);
} catch(e)
{
}
if (report == null)
{
return ctxt.getAPI().getTabularReport(reportName, reportContext);
} else
{
var source = report.getSourceReport();
return ctxt.getAPI().getTabularReport(source, reportContext);
}
}
function getReportView(reportContext, reportName)
{
var report = getReport(reportContext, reportName);
if (report == null)
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
9
Managing Reports
Accessing Reports
{
logger.addError("No such report exists for the specified context "+reportName);
return null;
}
return new TableView(report);
}
// following are only sample values and need to be modified based on actual UCSM account
name
var ucsmAccountName = "ucs-account-1";
// repot name is obtained from Repot Meta data and no need to change unless you need to
access a different report
var reportName = "UcsController.allservers.table_config";
var repContext = util.createContext("ucsm", null, ucsmAccountName);
// Enable Developer Menu in UCSD and find reportName in the Report Metadata for the specific
report
//Creating a ReportContext
//@param contextName
// Refer to UCSD API Guide for the available contexts
// @param cloud
// should be null unless contextName is "cloud" or "host node"
// @param value
// identifier of the object that is going to be referenced
Report var report = getReportView(repContext, reportName);
// Get only the rows for which Server Type column value is B-Series
report = report.filterRowsByColumn("Server Type", "B-Series", false);
// now look for unassociated servers only
report = report.filterRowsByColumn("Operation State", "unassociated", false);
// Make sure servers are actually in available state
report = report.filterRowsByColumn("Availability", "available", false);
var matchingIds = [];
var count = 0;
// Now look for Servers with memory of 32 GB or more
for (var i=0; i<report.rowCount(); i++)
{
var memory = Integer.parseInt(report.getColumnValue(i, "Total Memory (MB)"));
logger.addDebug("Possible Server "+report.getColumnValue(i, "ID")+", mem="+memory);
if (memory >= 32*1024)
{
matchingIds[count++] = report.getColumnValue(i, "ID");
}
}
if (count == 0)
{
ctxt.setFailed("No servers matched the criteria");
ctxt.exit();
}
// Now randomly pick one of the item from the filtered list
var id = matchingIds[Math.round(Math.random()*count)];
logger.addInfo("Allocated server "+id);
// Save the Server-ID to the global inputs
ctxt.updateInput("SELECTED_UCS_SERVER_ID", id);
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
10
Managing Reports
Emailing Reports
Accessing Tabular Reports
If you are using the getTabularReport (reportName, reportContext) API to access a tabular report, you can
view the report details in the user interface (UI) in one of the following ways:
• Reports Customization tab—To access the reports customization tab, choose Administration > User
Interface Settings and choose Reports Customization. The customization tab displays the report details
such as menu, context, report type, and so on. To customize the table columns, click the Customize
Table Columns icon and check the check box of the column item to be shown. For example, to display
the report ID, check the ID check box.
• Report Metadata—The report metadata link appears in the UI only when the developer menu is enabled.
To enable the developer menu, click Admin and check the Enable Developer Menu check box in the
Advanced tab. The report metadata for the corresponding UI report displays information on the report
context name (integer mapping) and the context value. The metadata also provides the REST API URL
to invoke the report from the REST API.
Some of the important report details are:
• API report ID—You can use the API report ID column to get the value for the reportID parameter that
is used in the REST URL when you are using the userAPIGetTabularReport API. This REST API is
used to retrieve the tabular report from the Firefox REST client.
• ID—The ID column displays the report name. You can use the ID column to get the reportName parameter
when you are using the getTabularReport API in the Cloupia script. This parameter is also applicable
for the getConfigTableReport API.
• context—To construct the ReportContext, you need the two input parameters: contextName and
contextValue. For regular contexts, use the util.createContext ("contextName", null, "instanceName").
For example, util.createContext("vm",null, vmId), where vmId is the integer VM ID value to uniquely
identify a VM in UCS Director. For cloud contexts, use the
util.createContext("contextName","cloudInstanceName", null) , or
util.createContext("contextName",null,"cloudInstanceName"). For example,
util.createContext("cloud","All Clouds",null) , or util.createContext("cloud", null, "All Clouds").
Emailing Reports
You can use the Cloupia script to email a report to a user. If you need this report to be emailed on a periodic
basis, you can set up a workflow schedule for this workflow at the desired frequency.
The following script is used to email a list of all powered on VMs to a user specified in the workflow input
variable Email Address.
importPackage(java.util);
importPackage(java.lang);
importPackage(java.io);
importPackage(com.cloupia.model.cEvent.notify);
importPackage(com.cloupia.model.cIM);
importPackage(com.cloupia.lib.util.mail);
importPackage(com.cloupia.fw.objstore);
importPackage(com.cloupia.lib.util.managedreports);
function getMailSettings()
{
return ObjStoreHelper.getStore((new MailSettings()).getClass()).getSingleton();
}
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
11
Managing Reports
Emailing Reports
function getReport(reportContext, reportName)
{
var report = null;
try
{
report = ctxt.getAPI().getConfigTableReport(reportContext, reportName);
} catch(e)
{
}
if (report == null)
{
return ctxt.getAPI().getTabularReport(reportName, reportContext);
} else
{
var source = report.getSourceReport();
return ctxt.getAPI().getTabularReport(source, reportContext);
}
}
function getReportView(reportContext, reportName)
{
var report = getReport(reportContext, reportName);
if (report == null)
{
logger.addError("No such report exists for the specified context "+reportName);
return null;
}
return new TableView(report);
}
// Assume the To Email Addres is in the input variable 'Email Address'
var toEmail = [ ctxt.getInput("Email Address") ];
var message = new EmailMessageRequest();
message.setToAddrs(toEmail);
message.setSubject("VM List Reportl");
message.setFromAddress("[email protected]");
var buffer = new StringWriter();
var printer = new PrintWriter(buffer);
// Formatter exists in multiple packages, so it needs fully qualified name
var formatter = new com.cloupia.lib.util.managedreports.Formatter(new File("."), printer);
var reportName = "GLOBAL_VM_LIST_REPORT";
var repContext = util.createContext("global", null, null);
var report = getReportView(repContext, reportName);
// Filter Active State VMs
report = report.filterRowsByColumn("Power State", "ON", false);
formatter.printTable(report);
printer.close();
var body = "<head><style type='text/css'>";
// Specify CSS for the report
body = body + "table { font-family: Verdana, Geneva, sans-serif; font-size: 12px; border:
thin solid #039; border-spacing: 0; background: #ffffff; } ";
body = body + " th { background-color: #6699FF; color: white; font-family: Verdana, Geneva,
sans-serif; font-size: 10px; font-weight: bold; border-color: #CCF; border-style: solid;
border-width: 1px 1px 0 0; margin: 0; padding: 5px; } ";
body = body + " td { font-family: Verdana, Geneva, sans-serif; font-size: 10px; border-color:
#CCF; border-style: solid; border-width: 1px 1px 0 0; margin: 0; padding: 5px; background:
#ffffff; }";
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
12
Managing Reports
Emailing Reports
body = body + "</style></head>";
body = body+ "<body><h1>List of Powered ON VMs</h1><br>" + buffer.toString();
message.setMessageBody(body);
logger.addInfo("Sending email");
// Now, send the report via email. First parameter is just a label used in the
logs
MailManager.sendEmail("VM List Report", getMailSettings(), message);
internal
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
13
Managing Reports
Emailing Reports
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
14
APPENDIX
A
Cloupia Script Samples
This appendix contains the following sections:
• Invoking Another Workflow, page 15
• Integrating with ServiceNow Ticketing, page 16
• Sending Emails from the Cloupia Script, page 17
• Archiving Older Service Requests Automatically, page 18
Invoking Another Workflow
Using the Cloupia script, you can invoke another named workflow.
In this example, a workflow called CreateAssetX is invoked and the following inputs are passed to the workflow:
• Input_A
• Input_B
• Input_C
One of the workflow tasks of the CreateAssetX workflow, called Task_Y, produces the output D:
// Create name value pairs for the input of the workflow
var params = util.createNameValueList();
params.addNameValue(util.createNameValue(“Input_A”, “a”));
params.addNameValue(util.createNameValue(“Input_B”, 1000));
params.addNameValue(util.createNameValue(“Input_C”, “something”));
// Pass three arguments into the following API
//
- Name of the workflow
//
- Parameter List object
//
- Current SR ID so that child can be automatically linked to this one
var childSrId= ctxt.getAPI().userAPISubmitWorkflowServiceRequest(“Create Asset X”, params,
ctxt.getSrId());
// wait for completion of the workflow. Or a maximum of 60 seconds
var status = ctxt.waitForCompletion(vfsrId, 60000);
// status code can be one 0 (Success), 1 (failed), -1 (Invalid SR ID)
// Now that workflow is complete, we can access the output variables of the workflow
var output_y = ctxt.getOutput(”Task_Y.D”", childSrId);
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
15
Cloupia Script Samples
Integrating with ServiceNow Ticketing
Integrating with ServiceNow Ticketing
ServiceNow provides several demo instances, which you can use for testing. The demo login and password
is admin/admin.
Note
The demo login and password should be verified in ServiceNow, because they will change from time to
time.
ServiceNow resets the data on each demo instance each day. You must enable JSON plugin on ServiceNow
to make this API work. For instructions to enable JSON plugin, see the Activating the Plugin section in
http://wiki.servicenow.com/index.php?title=JSON_Web_Service#Activating_the_Plugin.
This example script helps to open a ticket on ServiceNow:
importPackage(java.util);
importPackage(java.io);
importPackage(com.cloupia.lib.util);
importPackage(com.cloupia.model.cIM);
importPackage(com.cloupia.service.cIM.inframgr);
importPackage(org.apache.commons.httpclient);
importPackage(org.apache.commons.httpclient.cookie);
importPackage(org.apache.commons.httpclient.methods);
importPackage(org.apache.commons.httpclient.auth);
//var login= ctxt.getInput("LOGIN")
//var password = ctxt.getInput("PASSWORD");
var
var
var
var
login = "admin";
password = "admin";
instance = "demo011.service-now.com";
url
= "/incident.do?JSON&sysparm_action=insert";
// Link to Service-now documentation
//http://wiki.servicenow.com/index.php?title=JSON_Web_Service#insert
var map = new HashMap();
map.put("sysparm_action", "insert");
map.put("short_description", "Sample incident #5");
map.put("impact", "2");
map.put("urgency", "2");
map.put("caller_id", "Joe Z");
map.put("category", "software");
var data = JSON.javaToJsonString(map, map.getClass());
logger.addInfo("JSON Data = "+data);
var httpClient = new HttpClient();
httpClient.getHostConfiguration().setHost(instance, 443, "https");
httpClient.getParams().setAuthenticationPreemptive(true);
httpClient.getParams().setCookiePolicy("default");
var defaultcreds = new UsernamePasswordCredentials(login, password);
httpClient.getState().setCredentials(new AuthScope(instance, -1, null), defaultcreds);
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
16
Cloupia Script Samples
Sending Emails from the Cloupia Script
var httpMethod = new PostMethod(url);
httpMethod.setRequestEntity(new StringRequestEntity(data));
httpMethod.addRequestHeader("Content-Type", "application/json");
httpClient.executeMethod(httpMethod);
var statuscode = httpMethod.getStatusCode();
logger.addInfo("STATUSCODE = "+statuscode);
if (statuscode != 200)
{
logger.addError("Ticket opening failed with code "+statuscode);
if (statuscode == 302)
{
logger.addWarning("Likely cause of the failure is JSON plugin is not activated on
the Service Now instance. ");
logger.addWarning("Check documentation on how to enable the plugin: "+
"http://wiki.servicenow.com/index.php?title=JSON_Web_Service#insert "+
" (see section 2)");
}
httpMethod.releaseConnection();
// Set this task as failed.
ctxt.setFailed("Unable to open ticket");
} else
{
var reader = new InputStreamReader(httpMethod.getResponseBodyAsStream());
var resp = JSON.getJsonElement(reader, null);
logger.addInfo("Response = "+resp);
var entry = resp.get("records").get(0);
logger.addInfo("Ticket Number "+entry.get("number"));
logger.addInfo("Ticket Sys_id "+entry.get("sys_id"));
httpMethod.releaseConnection();
}
Sending Emails from the Cloupia Script
The Cisco UCS Director has built-in tasks to send an email.
This example shows how to send a custom email using the Cloupia script:
importPackage(com.cloupia.model.cEvent.notify);
importPackage(com.cloupia.model.cIM);
importPackage(com.cloupia.lib.util.mail);
importPackage(com.cloupia.fw.objstore);
function getMailSettings()
{
return ObjStoreHelper.getStore((new MailSettings()).getClass()).getSingleton();
}
// Assume the To Email Addres is in the input variable 'Email Address'
var toEmail = [ ctxt.getInput("Email Address") ];
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
17
Cloupia Script Samples
Archiving Older Service Requests Automatically
var message = new EmailMessageRequest();
message.setToAddrs(toEmail);
// other
//
//
//
//
list
//
list
methods in the message object are
setToAddr(emailAddress)
-- to set a single email address in To list
setCcAddr(emailAddress)
-- to set a single email address in Cc list
setBccAddr(emailAddress)
-- to set a single email address in Bcc list
setCcAddrs(emailAddressArray)
-- to set a an array of email addresses in Cc
setBccAddrs(emailAddressArray)
-- to set a an array of
email addresses in Bcc
message.setSubject("Test Email");
message.setFromAddress("[email protected]");
var body = "<h1>This is a sample Email </h1><br><b>Sample content</b>";
message.setMessageBody(body);
// By default, content type if text/html. Following method can be used to modify content
type
//
message.setContentType("text/plain");
logger.addInfo("Sending email");
MailManager.sendEmail("Sample Email", getMailSettings(), message);
Archiving Older Service Requests Automatically
You can archive the service requests using the Cloupia script.
The following script shows how to set up the script for archiving all service requests (SRs) that are older than
30 days. You can execute this workflow set up once a day to make sure that only the SRs in the last 30 days
are shown in the main report.
importPackage(com.cloupia.model.cIM);
importPackage(com.cloupia.fw.objstore);
importPackage(com.cloupia.service.cIM.inframgr.workflowmgr);
importPackage(com.cloupia.service.cIM.inframgr.cmdb);
importPackage(java.lang);
function getOlderSRs(ageInDays)
{
var timeStamp = System.currentTimeMillis() - (ageInDays*(24*60*60*1000));
var store = ObjStoreHelper.getStore((new ServiceRequest()).getClass());
return store.query("isArchived == false && requestTime < "+timeStamp);
}
var srList = getOlderSRs(30);
logger.addInfo("There are "+srList.size()+" SRs to be archived");
for (var i=0; i<srList.size(); i++)
{
var sr = srList.get(i);
logger.addDebug("["+i+"] Archiving SR "+sr.getRequestId());
// Archive the SR
WorkFlowManager.getInstance().archive(sr.getRequestId());
// Add an entry into the Change Log
CMDB.getInstance().change(ctxt.getUserId(), 0, "Request archived by Workflow", sr);
}
Cisco UCS Director Cloupia Script Configuration Guide, Release 5.0
18
© Copyright 2026 Paperzz