SQL databases
Workflows often need somewhere to keep records that outlive a run: what was built, for whom, and when; a list of names already handed out; numbers for a monthly report. Orchestrator’s own database isn’t the place for them. A database of your own is, and the SQL plug-in connects workflows to it over JDBC. It works with PostgreSQL, Microsoft SQL Server, Oracle, and MySQL.
In this recipe you register a small PostgreSQL database, check it with a query that needs no code, and then write a workflow that records the facts of a few VMs, one row each, and an action that reads the latest rows back. On the way you’ll see why building SQL from strings needs care.
Getting ready
- A PostgreSQL server that Orchestrator can reach on TCP 5432. This recipe uses
db01.vmw.lab, with a databasevcfguideowned by the uservcfguide. - The action
com.vcfguide.chapter4/getVmFactsfrom recipe 4.2, and the vCentervc01.vmw.labregistered with the vCenter plug-in. - A login with administrator rights, the action module
com.vcfguide.chapter5, and the workflow folder VCF Orchestrator Guide/Chapter 5.
How to do it
Prepare the database
- On the PostgreSQL server, as the user
vcfguide, create the table the workflow writes to:
CREATE TABLE vm_facts ( id serial PRIMARY KEY, vm_name varchar(255) NOT NULL, power_state varchar(32) NOT NULL, cpus integer NOT NULL, memory_mb integer NOT NULL, guest_os varchar(255), recorded_at timestamp NOT NULL DEFAULT now());- Check that the server accepts connections from
vco01.vmw.lab: itspg_hba.confneeds a line for the appliance’s address, or its network, with thescram-sha-256method.
Register the database
- In the Orchestrator Client, go to Library > Workflows, search with the tags
sqlandconfiguration, and run Add a database. - Enter the Name
db01-vcfguide, choose the database type PostgreSQL, and enter the Connection URLjdbc:postgresql://db01.vmw.lab:5432/vcfguide. - On the User credentials tab, choose Shared Session and enter the user
vcfguideand its password. Click Run. - Run Add tables to a database, select
db01-vcfguide, select the tablevm_facts, and click Run. - Go to Administration > Inventory > SQL. The database is listed, with
vm_factsunder it.
Run dialog of Add a database: Name db01-vcfguide, database type PostgreSQL, Connection URL jdbc:postgresql://db01.vmw.lab:5432/vcfguide; the User credentials tab visible.
Run a query without code
- Search with the tag
sqland run Read a custom query from a database. Selectdb01-vcfguide, enter the querySELECT count(*) AS row_count FROM vm_facts, and click Run. - The run’s result is an array with one element, a set of properties with
row_count=0.
Write rows from a workflow
- In Library > Actions, create two actions in
com.vcfguide.chapter5. The first,getDatabase, has the inputnameof typestringand the Return typeSQL:Database:
// Returns the database registered with the SQL plug-in under this name.var databases = SQLDatabaseManager.getDatabases();for (var i = 0; i < databases.length; i++) { if (databases[i].name === name) { return databases[i]; }}throw "getDatabase: no database named " + name + " in the SQL plug-in";- The second,
sqlText, has the inputvalueof typeAnyand the Return typestring. It turns a value into a safe SQL literal:
// Returns value as an SQL string literal, with any single quote doubled,// or NULL. Use it for every value you put into an SQL statement.if (value === null || value === undefined) { return "NULL";}return "'" + String(value).replace(/'/g, "''") + "'";- Create the workflow Record VM facts in VCF Orchestrator Guide/Chapter 5, with the inputs
vmsof typeArray/VC:VirtualMachineanddatabaseNameof typestring, defaultdb01-vcfguide, and the outputrowsWrittenof typenumber. Add one scriptable task, Write rows, with this script:
var chapter4 = System.getModule("com.vcfguide.chapter4");var chapter5 = System.getModule("com.vcfguide.chapter5");var database = chapter5.getDatabase(databaseName);
rowsWritten = 0;for (var i = 0; i < vms.length; i++) { var facts = chapter4.getVmFacts(vms[i]); var sql = "INSERT INTO vm_facts (vm_name, power_state, cpus, memory_mb, guest_os) VALUES (" + chapter5.sqlText(facts.get("name")) + ", " + chapter5.sqlText(facts.get("powerState")) + ", " + parseInt(facts.get("cpus"), 10) + ", " + parseInt(facts.get("memoryMb"), 10) + ", " + chapter5.sqlText(facts.get("guestOs")) + ")"; rowsWritten += database.executeCustomQuery(sql);}System.log(rowsWritten + " rows written to " + databaseName);- Run the workflow with three VMs from
vc01.vmw.lab. The log says3 rows written to db01-vcfguide. Run the query from step 8 again:row_countis now3.
Run of Record VM facts with three VMs, Logs tab with 3 rows written to db01-vcfguide, Variables tab with rowsWritten = 3.
Checked on 9.1.1: the type names are SQL:Database and SQL:Table (SQLDatabase is rejected as an unknown type), and SQLDatabaseManager.getDatabases() runs and returns an array, empty on a server with no database added.
executeCustomQuery returns the number of rows changed as a number.Read rows back
- Create the action
latestVmFacts, with the inputsdatabaseNameof typestringandmaxRowsof typenumber, and the Return typeArray/string:
// Returns the most recent rows of vm_facts, newest first, one line each.var database = System.getModule("com.vcfguide.chapter5").getDatabase(databaseName);var limit = parseInt(maxRows, 10);if (isNaN(limit) || limit < 1) { limit = 10;}var rows = database.readCustomQuery( "SELECT vm_name, power_state, cpus, memory_mb, recorded_at FROM vm_facts " + "ORDER BY recorded_at DESC, id DESC LIMIT " + limit);
var lines = [];for (var i = 0; i < rows.length; i++) { var row = rows[i]; lines.push(row.get("vm_name") + ": " + row.get("power_state") + ", " + row.get("cpus") + " vCPU, " + row.get("memory_mb") + " MB at " + row.get("recorded_at"));}return lines;- Run it with
db01-vcfguideand5. You get the three rows from step 13, newest first.
Run of action com.vcfguide.chapter5/latestVmFacts with db01-vcfguide and 5: result array with three lines, VM name, power state, vCPUs, memory and time.
readCustomQuery returns each column: whether the keys are the column names in lower case, as PostgreSQL reports them, and what type a timestamp and an integer column arrive as in JavaScript.How it works
Add a database stores a connection in Orchestrator’s database: a name, a JDBC connection URL, a database type that picks the driver, and the credentials. Every workflow and script then uses that connection by name, so the password is entered once, by an administrator, and never appears in a workflow. With Shared Session, all runs use that one account. With Session Per User, the plug-in logs in as the Orchestrator user who runs the workflow, which only works if the database knows that user by the same plain name.
Two calls do most of the work. executeCustomQuery(sql) runs a statement that changes something, such as INSERT, UPDATE, or DELETE, and returns how many rows it changed. readCustomQuery(sql) runs a query that returns rows and gives you an array of Properties, one per row, keyed by column name. The built-in workflows Execute a custom query on a database and Read a custom query from a database are the same two calls with a form around them.
Why sqlText? Both calls take one string of SQL, and the database can’t tell your SQL from the values you pasted into it. A VM called it's-a-test breaks a statement built with plain +, and a value such as x'); DROP TABLE vm_facts; -- from a form turns into a second statement. sqlText doubles every single quote, which is how standard SQL writes a quote inside a string, and the numbers go through parseInt, so nothing but digits reaches the statement. Treat every value that comes from outside the script this way, including names that come from vCenter.
Tables in the inventory. Add tables to a database makes a table an inventory object of type SQL:Table. You don’t need it for custom queries, but the generated workflows and the record methods below work on tables, not on SQL text.
There's more
Generate CRUD workflows. Run Generate CRUD workflows for a table, select vm_facts, pick the folder VCF Orchestrator Guide/Chapter 5, and choose not to overwrite existing workflows. You get workflows to create, read, update, and delete rows, with an input for each column. On the Select read-only columns tab, mark id and recorded_at, which the database fills in itself.
Writing records without SQL text. A table object has methods that take the values as properties, so no quoting is needed. table.createRecord(values, …) inserts a row from a Properties object of column names and values, and readRecords, updateRecord, and deleteRecords do the rest. Get the table from database.getTables().
SQLTable.createRecord, readRecords, and deleteRecords in the API Explorer on 9.1.1 (each takes a Properties object and a boolean in older releases), what the boolean does, and the name of the method that lists a database’s tables.Microsoft SQL Server. Two database types exist for SQL Server. The jTDS type is included and uses URLs like jdbc:jtds:sqlserver://sql01.vmw.lab:1433/vcfguide. The Microsoft JDBC type uses jdbc:sqlserver://… and Microsoft’s own driver, which you add to Orchestrator first; it’s the one to choose for Always On availability groups with multiSubnetFailover=true, which jTDS doesn’t support (KB 381859). For a TLS connection to any database, import its certificate with Import a certificate from URL before Add a database.
/data/vco/var/run/vco/plugins/SQL/lib/ on every node and set the system property o11n.plugin.SQL.classpath in Control Center, which 9.x doesn’t have. Check whether vracli vro properties set (recipe 2.8) replaces that step, and whether the 9.0 page Adding a JDBC connector for the VCF Operations orchestrator SQL plug-in describes another way.One statement per call. Each executeCustomQuery and readCustomQuery sends one statement and waits for the answer. Ten inserts in a loop are ten round trips to the database, which is fine for tens of rows. For thousands, build one multi-row INSERT … VALUES (…), (…), … statement, or let the database load a file.
Test the URL first. The sample workflow Test a JDBC connection tries a connection URL, user, and password without registering anything. It’s the quickest way to find out whether a failure is the URL, the network, or the account.
See also
- 4.2 Writing and reusing actions, for
getVmFacts. - 3.6 Building input forms, for validating values before they get anywhere near SQL.
- 5.1 How plug-ins work, for configuration workflows and the inventory.
- Broadcom TechDocs (VCF 9.0): Using the SQL plug-in, Configuring the SQL plug-in, Add a Database, Running SQL Operations, and Adding a JDBC connector for the VCF Operations orchestrator SQL plug-in.
- Broadcom TechDocs (Aria Automation 8.14 and 8.18): Generate CRUD workflows for a table and Running the SQL sample workflows.
- Broadcom KB 381859: connecting to SQL Server with the Microsoft JDBC driver.
- PostgreSQL documentation: String constants, on doubling single quotes.
