Processing Datasources With JavaScript

Datasources may use JavaScript to combine and transform data from one or more datasources to create a new datasource. The syntax used in this case is:

datasource <name> do

   run_script $<script>[, <term>]*

end

Where <script> is the name of script definition and the terms are parameters or datasources given to the script for execution. The script result defines the data returned by the datasource. Terms can be any type (including other datasources, which will show up as arrays of JavaScript Objects).

Note:Note the following:

The JavaScript Datasource supports the JavaScript ECMAScript 5/ES 5 Specification. Review this reference when writing a JavaScript Datasource.
The JavaScript Datasource includes the underscore library. This library includes some useful functions to assist in managing the data objects passed into the datasource. Version 1.4.4 of the library is currently included.

Scripts are defined using script definitions with the following syntax:

script <name>, type: "javascript" do

  parameters <string literal>[, <string literal]*

  result <string literal>

  code <string literal>

end

Where:

parameters is the list of parameters the script accepts. The parameters will automatically be set as JavaScript variables at the start of script execution.
result identifies the name of the JavaScript variable used to extract the data returned by the script. result is required.
code contains the actual JavaScript code. code is required.

Example:

datasource "merge_instances" do 

   run_script $merge, $instances_us_east, $instances_us_west 

end 

 

script "merge", type: "javascript" do 

  parameters "instances_us_east", "instances_us_west" 

  result "res" 

  code <<-EOS 

  res = [] 

  // Concatenate the different arrays of instances 

  var instances = [] 

  instances = instances_us_east.concat(instances_us_west) 

 

  // Build the array of json objects containing the instance information as described above. 

  var server_json = {} 

  for (var i = 0; i < instances.length; i++) { 

    var instance = instances[i] 

 

    var name = instance["name"] 

    var state = instance["state"] 

    var href = instance["href"] 

    var tags = instance['tags'] 

 

    // build the json object 

    server_json = { "name": name, "href": href, "state": state, "tags": tags } 

 

    // push object onto the output array 

    res.push(server_json) 

  } 

  EOS 

end 

For more complicated examples of JavaScript datasources including scripts that combine together multiple datasources see the List of Flexera Policies such as the open ports policy.