js: Using javascript for transforms

Modified on Thu, 25 May, 2023 at 12:30 PM

Sometimes it's necessary to do really complex transformations, which jq cannot support (or if jq statements become too complex).


Below is an extract from a state showing how to use javascript:

  #
  # Snapshot the volumes and tag the snapshots with the change details from Servicenow.com
  #
  - id: snapshot-gcp-volumes
    # log: jq(.)
    log: "Creating snapshot for the volumes selected in ServiceNow"
    type: foreach
    array: 'jq( [ .result[] | select(.u_delete=="1") ] )'
    action:
      function: gcp-cli
      secrets: ["GCP_KEY", "GCP_PROJECT", "GCP_ACCOUNT"]
      input: 
        account: jq(.secrets.GCP_ACCOUNT)
        project: jq(.secrets.GCP_PROJECT)
        key: jq(.secrets.GCP_KEY | @base64 )
        commands:
        - command: gcloud compute disks snapshot jq(.u_volume_id) --zone=jq(.u_availability_zone) --format=json
    catch:
      - error: "*"
        transition: exception-catch
    transform: 
      result: |
        js(
            var newArray = new Array();
            snapsArray = data.return;
            changesArray = data.result;

            snapsArray.forEach(snapItem => {
              changesArray.forEach(changeItem => {
                if (snapItem.gcp[0].result[0].sourceDisk === changeItem['u_volume_id']) {
                  changeItem["u_snapshot_id"] = snapItem.gcp[0].result[0].name 
                  newArray.push(changeItem)
                }
              })
            })

            items = new Object();
            items.items = newArray;
            return items;
        )
    transition: delete-gcp-volumes

The jq statement can be replaced with a js statement as part of the workflow configuration. 

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article