GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing docs.stackstorm.com — Actions — StackStorm 3.9.0 documentation ActionsActions are pieces of code that can perform arbitrary automation or remediation tasks in your environment. They can be written in any programming language. To give you a better idea, here is a short list of tasks which can be implemented as actions:
Actions can be executed when a Rule with matching criteria is triggered. Multiple actions can be strung together into a Workflow. Actions can also be executed directly from the clients via CLI, API, or UI. Managing and Running ActionsThe CLI provides access to action management commands using the st2 action --help To get more information on a particular action command, run: st2 action list -h The following commands show examples of how to obtain information on available actions and their arguments: # List all available actions (note that output may be lengthy) st2 action list # List all actions in "linux" pack st2 action list -p linux # Display information for a particular action linux.check_loadavg st2 action get linux.check_loadavg # Alternatively, use CLI's run script to obtain information on an action's arguments: st2 run linux.check_loadavg -h To execute an action manually, you can use # Execute action immediately and display the results st2 run core.http url="http://httpbin.org/get" # Schedule action execution st2 action execute core.http url="http://httpbin.org/get" # Obtain execution results (the command below is provided as a tip in the output of the above command): st2 execution get 54fc83b9e11c711106a7ae01 # If you want to add a trace tag to execution when you run it, you can use: st2 run core.local cmd=date --trace-tag="simple-date-check-`date +%s`" Modification in Action Delete APIStackStorm offers functionality to delete actions/workflows by invoking API. Prior to 3.6 release this API was only de-registering actions from database. In the 3.6 release, with backward compatibility retained this API was modified to optionally delete related action files from disk as well. From CLI API action DELETE method with
st2 action delete [-h] [-t TOKEN] [--api-key API_KEY] [-j] [-y] [-r] ref-or-id
# Reference or ID of the action
ref-or-id
-h, --help show this help message and exit -t TOKEN, --token TOKEN Access token for user authentication. Get ST2_AUTH_TOKEN from the environment variables by default --api-key API_KEY Api Key for user authentication. Get ST2_API_KEY from the environment variables by default -j, --json Print output in JSON format -y, --yaml Print output in YAML format -r, --remove-files Delete action files from disk Cloning an ActionNote The action clone feature is only available in StackStorm v3.7.0 and above. Clone operation clones action from source pack to destination pack and renames them appropriately. This operation makes changes in destination action metadata files like action name, pack name, entry point name etc. Also, this operation registers the newly cloned action to the database. API endpoint From CLI
st2 action clone [-h] [-t TOKEN] [--api-key API_KEY] [-j] [-y] [-f] source-ref-or-id dest-pack-name dest-action-name
# Reference or ID of the source action source-ref-or-id # Destination pack name dest-pack-name # Destination action name dest-action-name
-h, --help Show this help message and exit -t TOKEN, --token TOKEN Access token for user authentication. Get ST2_AUTH_TOKEN from the environment variables by default --api-key API_KEY Api Key for user authentication. Get ST2_API_KEY from the environment variables by default -j, --json Print output in JSON format -y, --yaml Print output in YAML format -f, --force Overwrite action files on disk if destination exists. Action RunnersAn action runner is the execution environment for user-implemented actions. StackStorm comes with pre-canned action runners such as a remote runner and shell runner which provide for user-implemented actions to be run remotely (via SSH) and locally. The objective is to allow the action author to concentrate only on the implementation of the action itself rather than setting up the environment. Available RunnersThe environment in which the action runs is specified by the runner. Currently the system provides the following runners:
Runners come with their own set of input parameters. When an action is executed, it inherits the runner parameters, in addition to its own parameters. The built-in parameters can be over-ridden on a per-action basis. For a complete list of Runners and their parameters, see Action Runners. Writing Custom ActionsAn action is composed of two parts:
As noted above, an action script can be written in an arbitrary programming language, as long as it follows these conventions:
Action MetadataAction metadata is used to describe the action and is defined as YAML. These attributes can be present in the metadata file:
This is a sample metadata file for a Python action which sends an SMS via the Twilio web service: --- name: "send_sms" runner_type: "python-script" description: "This sends an SMS using twilio." enabled: true entry_point: "send_sms.py" parameters: from_number: type: "string" description: "Your twilio 'from' number in E.164 format. Example +14151234567." required: true position: 0 to_number: type: "string" description: "Recipient number in E.164 format. Example +14151234567." required: true position: 1 secret: true body: type: "string" description: "Body of the message." required: true position: 2 default: "Hello {% if system.user %} {{ st2kv.system.user }} {% else %} dude {% endif %}!" This action is using a Python runner ( In the example above, the Tip Does your parameter only accept certain values? Use See the examples.weather action in the examples pack for how to use this. Output SchemaStackStorm supports modeling the output of an action or runner via the For example, you have a python action that returns three keys: --- ... output_schema: type: object properties: errors: type: array items: type: string output: required: true type: array items: type: number status_code: required: true type: integer additionalProperties: false If the action output does not return the correct fields it will fail validation and the action itself will fail. This prevents propagating corrupt data to other actions in a workflow, which could lead to unpredictable results. In future this information will be used for pre-run workflow validation. Output schema validation is disabled by default in current versions of StackStorm. To enable it, set
If an action does not define any output schema, no enforcement is done. This allows you to progressively update your actions, rather than doing them all at once. As with all other input and output schema definitions in Stackstorm, we leverage
JSONschema (draft 4) to define For example, you have a python action that returns a secret token as a string. You can define the schema as follows: --- ... output_schema: type: string secret: true Or the python action could return the secret token as an object field: --- ... output_schema: type: object properties: super-awesome-token: type: string secret: true additionalProperties: false Parameters in ActionsIn the previous example, you probably noticed how you can access parameters from the key-value
store by using the parameters: user: type: "string" description: "User of this action." required: true default: "{{action_context.api_user}}" The prefix A simple execution via the API will only contain the variables In addition to --- name: "send_sms" runner_type: "python-script" description: "This sends an SMS using twilio." enabled: true entry_point: "send_sms.py" parameters: from_number: type: "string" description: "Your twilio 'from' number in E.164 format. Example +14151234567." required: false position: 0 default: "{{config_context.from_number}}" to_number: type: "string" description: "Recipient number in E.164 format. Example +14151234567." required: true position: 1 secret: true body: type: "string" description: "Body of the message." required: true position: 2 default: "Hello {% if system.user %} {{ st2kv.system.user }} {% else %} dude {% endif %}!" In ActionChains and workflows (see Workflow), every task in the workflow can
access the parent’s ... - name: "c2" ref: "core.local" parameters: cmd: "echo \"c2: parent exec is {{action_context.parent.execution_id}}.\"" on-success: "c3" on-failure: "c4" ... Action RegistrationTo register a new action:
The actions are grouped in packs and located at For hacking one-off actions, the convention is to use the Register an individual action by calling Built-in ParametersAction runners have their own built-in parameters. These are inherited by the action, and be over-ridden either in the action metadata, or by passing additional parameters when running the action. Some common parameters include:
For a full list of built-in parameters for each runner type, see Action Runners. Overriding Runner ParametersParameters of runners can be overridden. Sometimes it’s necessary to customize and simplify an
action. Take the following The --- name: 'rsync' runner_type: 'remote-shell-cmd' description: 'Copy file(s) from one place to another w/ rsync' enabled: true entry_point: '' parameters: source: type: 'string' description: 'List of files/directories to to be copied' required: true dest_server: type: 'string' description: "Destination server for rsync'd files" required: true destination: type: 'string' description: 'Destination of files/directories on target server' required: true cmd: immutable: true default: 'rsync {{args}} {{source}} {{dest_server}}:{{destination}}' connect_timeout: type: 'integer' description: 'SSH connect timeout in seconds' default: 30 args: description: 'Command line arguments passed to rysnc' default: '-avz -e "ssh -o ConnectTimeout={{connect_timeout}}"' Not all attributes for runner parameters can be overridden. A list of attributes which can be overriden is included below:
Overriding attributes such as Environment Variables Available to ActionsBy default, local, remote and Python runners make the following environment variables available to the actions:
Here is an example of how you can use these environment variables inside a local shell script action. #!/usr/bin/env bash # Retrieve a list of actions by hitting the API using cURL and the information provided # via environment variables RESULT=$(curl -H "X-Auth-Token: ${ST2_ACTION_AUTH_TOKEN}" ${ST2_ACTION_API_URL}/actions) echo ${RESULT} Converting Existing Scripts into ActionsIf you have an existing standalone script written in an arbitrary programming or scripting language and you want to convert it to an action, the process is very simple. Follow these steps: 1. Make sure the script conforms to conventionsYou should make sure that the script exits with a zero status code on success and non-zero on error. This is important since the exit code is used by StackStorm to determine if the script has finished successfully. 2. Create a metadata fileYou need to create a metadata file which describes the script name, description, entry point, which runner to use and script parameters (if any). When converting an existing script, you will want to use either the 2. Update argument parsing in the scriptNote If your script doesn’t take any arguments, you can skip this step. Local and remote script runners recognize two types of parameters:
All parameters are passed to the script via command-line arguments. Named argument are passed to the script in the following format: script.sh --param1=value --param2=value --param3=value By default, each parameter is prefixed with two dashes ( For example: --- name: "my_script" runner_type: "remote-shell-script" description: "Script which prints arguments to stdout." enabled: true entry_point: "script.sh" parameters: key1: type: "string" required: true key2: type: "string" required: true key3: type: "string" required: true kwarg_op: type: "string" immutable: true default: "-" In this case, arguments are passed to the script in the following format: script.sh -key1=value1 -key2=value2 -key3=value3 Positional arguments are passed to the script ordered by the script.sh value2 value1 value3 If your script only uses positional arguments (which is often the case for existing scripts), you
simply need to declare parameters with the correct value for the
Using this simple serialization format allows users to easily utilize those values in their
scripts by using standard Bash functionality ( If no value is provided for a particular positional parameter, StackStorm will pass an empty string
For example, if a second positional parameter is optional and user provides no value, the script will be called like this: script.sh value1 "" value3 The Example 1 - existing Bash script with positional argumentsLet’s say we have a simple Bash script named The script takes two arguments:
#!/usr/bin/env bash SERVER=$1 MESSAGE=$2 logger -n ${SERVER} ${MESSAGE} Since this script is using positional arguments, you only need to define them in the metadata file: --- name: "send_to_syslog.log" runner_type: "remote-shell-script" description: "Send a message to a provided syslog server." enabled: true entry_point: "send_to_syslog.sh" parameters: server: type: "string" description: "Address of the syslog server" required: true position: 0 message: type: "string" description: "Message to write" required: true position: 1 As you can see above, we declare two parameters - Writing Custom Python ActionsIn the simplest form, a Python action is a module which exposes a class which inherits from
Sample Python ActionMetadata file ( --- name: "echo_action" runner_type: "python-script" description: "Print message to standard output." enabled: true entry_point: "my_echo_action.py" parameters: message: type: "string" description: "Message to print." required: true position: 0 Action script file ( import sys from st2common.runners.base_action import Action class MyEchoAction(Action): def run(self, message): print(message) if message == 'working': return (True, message) return (False, message) This Python action prints text provided via the If the Another way to specify the status of an execution is returning a tuple with two items: the first item is a boolean indicating status, the second item is the result itself. For example, In the example above, if the For a more complex example, please refer to the actions in the Libcloud pack in StackStorm Exchange. Configuration FileNote The configuration file should be used to store “static” configuration options which don’t change between the action runs (e.g. service credentials, different constants, etc.). For options/parameters which are user defined or change often, you should use action parameters which are defined in the metadata file. Python actions can store arbitrary configuration in the configuration file which is global to the whole pack. The configuration is stored in a file named The configuration file format is YAML. Configuration is automatically parsed and passed to the action class constructor via the LoggingAll logging inside the action should be performed via the logger which is specific to this action
and available via the This logger is a standard Python logger from the For example: def run(self): ... success = call_some_method() if success: self.logger.info('Action successfully completed') else: self.logger.error('Action failed...') Action ServiceSimilar to sensors, Action service provides different services to the action via public methods. Right now it supports datastore management methods. This allows actions to utilize the datastore to store arbitrary data between executions. The action service provides the same datastore management methods as the ones available on the sensor service. You can find more details in the sensor datastore management documentation. Example storing a dict as JSON: def run(self): data = {'somedata': 'foobar'} # Add a value to the datastore self.action_service.set_value(name='cache', value=json.dumps(data)) # Retrieve a value value = self.action_service.get_value('cache') retrieved_data = json.loads(value) # Retrieve an encrypted value value = self.action_service.get_value('ma_password', decrypt=True) retrieved_data = json.loads(value) # Delete a value self.action_service.delete_value('cache') Sharing code between Python Sensors and ActionsRefer to documentation on sharing common code between python actions and sensors. Pre-defined ActionsThere are several predefined actions that come out of the box with StackStorm. These are in the
To see all actions in the st2 action list --pack=core What’s Next?
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |