# Automation Actions

A JavaScript based automation action step is a method to perform custom actions to automate complex tasks and perform custom logic within a larger automation workflow.

Automation actions can either be performed on the agent or on the Avantra server itself. The APIs that are available differ in these scenarios.

- Agent-based steps

  Provides powerful APIs to access the managed object and perform complex actions depending on the managed object type. For example can call SAP RFCs, perform database queries, and execute operating system commands.

- Server-based steps

  The server-side type steps have access to a rich information API from the data that Avantra has collected, system information and check statuses etc. This type of step also allows users to update some information in Avantra, for example create external check results.

In both cases, we also provide an API to report the status and details of the step that has been executed. We always have access to the following building blocks:

- Using (Monitoring) Parameters

  Access parameters set in Avantra for the managed object the step is run on to control the logic. (Only applies to agent-based steps)

- Calling Web Services

  Access to a simple HTTP client to call web services to validate operations or perform actions.

| This page describes general step behaviours. For more information on the additional APIs available for server-side steps please see Server-based steps.

## Code Walkthrough

The action API is very simple to use and is only present to allow you to log details of your logic to tell your users what the step did and to report the outcome of the step, whether it was successful or not.

Check out the building blocks relevant to the monitored system this action is run on for details of affecting the system in question.

### Reporting Status

There are three simple properties of the action global variable that allow developers to pass status back to the user. This example shows how to use each:

    // The message should be concise as it is displayed on the
    // `Execution Output` of the step in the Avantra UI.
    action.message = "This is a message from an action";

    // Set the success of the action. The default is true = OK
    action.success = true;
    // If an error occurs set this to false like below:
    // action.success = false;

    // We use this to generate 100 lines of log output
    // - The format is `This is log line 1` etc.
    // in real automation actions, this could be the output from
    // an SAP RFC call, or an Operating System program execution.
    const log = Array.apply(null, Array(100))
                    .map((line, i) => `This is log line ${i+1}`)
                    .join("\n");

    // The action details can be displayed in the `Details` tab
    // when displaying the Automation Execution and can be much
    // longer to give more details on what was performed:
    action.details = log;

### Using Parameters

When running in the Automation Step Library, actions have access to two additional variables `action.input` and `action.output`. These variables allow the developer to programmatically read the parameters configured in the JavaScript step.

    const fileToRead = action.input.myFile;
    if (fileToRead) {
        // ... do something
    }

    // Output results:
    action.output.fileName = "myFile";

| Best practice is for parameters to be named with alphanumeric characters and starting with a letter. This is so we can use the dot notation above to access their values. Starting a variable with a number requires the developer to use bracket notation, e.g. `action.output["1param"] = …​`.

## Examples

Example 1. Example: Unlock a user in SAP

The example uses the SAP API to call a remote function module (RFC) to unlock a user in the system.

| This example is an agent-based step and runs on an agent managing an SAP system.

    // Read the user to unlock and the client from our input variables
    //  -- or take the defaults chosen.
    const sapClient = action.input.sapClient || "001";
    const userName = action.input.userName || "TESTUSER";

    // Execute the function module BAPI_USER_UNLOCK
    const unlockFn = sap.login(sapClient)
                        .getFunction("BAPI_USER_UNLOCK")
                        .withParameter("USERNAME", userName)
                        .execute();

    // This function module returns messages through RETURN table
    const msgs = unlockFn.result("RETURN");

    // To work out if we had an error, we look at the TYPE column
    const hasError = msgs.map(msg => msg.TYPE)
    // Filter out those that are success messages or warnings (S/W)
                        .filter(type => type != "S" && type != "W")
    // If we have any messages left, we have an error!
                        .length > 0;

    // Set the success of the action as the opposite of hasError!
    action.success = !hasError;

    // Output a high-level message depending on if we have errors
    if (hasError) {
        action.message = "BAPI_USER_UNLOCK had errors!";
    } else {
        action.message = "BAPI_USER_UNLOCK succesful!"
    }

    // Loop again through the logs and extract only the MESSAGE
    // table field. Then join together with newlines for the log.
    const msgLog = msgs.map(msg => msg.MESSAGE).join("\n");
    action.details = "Messages:\n" + msgLog;

## API Reference

### Global Variable action

The action global variable allows access to set the result of the action. Use the properties to influence the outcome of the automation.

#### setDetails(..)

    setDetails(details: string): void

Use this to set detailed information (available in the logs) for debugging and analysis of the automation step.

Parameters

  - `details`: string

    further details of the step

See Also

  - details

#### setMessage(..)

    setMessage(message: string): void

Use this to set a message to inform users of what happened in the automation step.

Parameters

  - `message`: string

    information to report back to the user about what happened

See Also

  - message

#### setSuccess(..)

    setSuccess(success: boolean): void

Use this to set the outcome of the automation step. Always set a message to inform users of why this status was set.

The default value is `true`.

Parameters

  - `success`: boolean

    false only if the automation step failed

See Also

  - success

#### details

    details: string

Use this to set detailed information (available in the logs) for debugging and analysis of the automation step.

See Also

  - setDetails(details: string)

Type

  string

#### input

    readonly input: any

Access the values of the input parameters of an automation step.

This object holds the input parameter values that have been passed to this workflow step as constants or workflow inputs or values from previous steps.

This object is accessed as a regular JSON object with the objects keys as the parameter names.

For example, when the input parameters `systemType`, `tableName` and `tableData` are configured for the step, this is how they can be accessed in the script:

    // Check if we are running on HANA:
    if (action.input.systemType === "HANA") {
        // ... do HANA specific logic
    }

    // Read the required table from parameters or use the default:
    const table = action.input.tableName || "Z_DEFAULT_TABLE";

    // Read any input table data:
    const data = JSON.parse(action.input.tableData);

Type

  any

Modifiers

  Readonly

Since

  21.11.4

#### message

    message: string

Use this to set a message to inform users of what happened in the automation step.

See Also

  - setMessage(message: string)

Type

  string

#### output

    readonly output: any

Set the values of the output parameters (result) of an automation step.

This object holds the values that will be returned to the automation workflow and can be used in subsequent steps or as an output of the workflow itself.

This object is accessed as a regular JSON object with the objects keys as the parameter names.

For example, when the output parameters `tableData` and `tableCount` are configured for the step, this is how they can be accessed in the script:

    const records = [];
    // ... Query SAP and fill the records array ...

    // Output the number of records found:
    action.output.tableCount = records.length;

    // Output the record information for further processing
    action.output.tableData = JSON.stringify(records);

Note the object is a read only property which means you cannot directly assign a new JavaScript object in your script to `action.output`. However you can change property values on the object as described above.

| Care should be taken to match the variable type of the output parameters. You can use `JSON.stringify(…​)` and `JSON.parse(…​)` methods to export/import more complex data between steps.

Type

  any

Modifiers

  Readonly

Since

  21.11.4

#### success

    success: boolean

Use this to set the outcome of the automation step. Always set a message to inform users of why this status was set.

The default value is `true`.

See Also

  - setSuccess(success: boolean)

Type

  boolean

### Global Variable log

Log utilities for automation steps.

#### debug(..)

    debug(msg: string): void

Log debug information to this workflow’s execution log.

    log.error('Step 4 of 5 was not OK!')
    log.warn('There were some issues detected')
    log.info('Default message displayed to users')
    log.debug('More technical information for fault-finding')

Since

  23.3

Parameters

  - `msg`: string

    the debug information to log

#### error(..)

    error(msg: string): void

Log an error to this workflow’s execution log.

    log.error('Step 4 of 5 was not OK!')
    log.warn('There were some issues detected')
    log.info('Default message displayed to users')
    log.debug('More technical information for fault-finding')

Since

  23.3

Parameters

  - `msg`: string

    the error to log

#### info(..)

    info(msg: string): void

Log an information message to this workflow’s execution log.

This is the default log level shown to the user.

    log.error('Step 4 of 5 was not OK!')
    log.warn('There were some issues detected')
    log.info('Default message displayed to users')
    log.debug('More technical information for fault-finding')

Since

  23.3

Parameters

  - `msg`: string

    the message to log

#### log(..)

    log(msg: string): void

Output a log message to this Workflow’s execution log.

The execution log is updated while a step is executing, so it’s an ideal way to show the progress of a long-running step to a step user while it’s running.

    log.log('Step 4 of 5 completed!')

Note: In 23.3 (and above) this defaults to log level 'Info'. Prefer using `log.debug`, `log.warn` etc. for finer control of the logs displayed.

Since

  23.1

Parameters

  - `msg`: string

    the message to log

#### warn(..)

    warn(msg: string): void

Log a warning to this workflow’s execution log.

    log.error('Step 4 of 5 was not OK!')
    log.warn('There were some issues detected')
    log.info('Default message displayed to users')
    log.debug('More technical information for fault-finding')

Since

  23.3

Parameters

  - `msg`: string

    the warning to log