CLI Reference
The StackStorm command line client (CLI)st2 allows you to operate your StackStorm system using thecommand line. It communicates with the StackStorm processes using public APIs.
Installation
The CLI client is installed by default on your StackStorm system. It can also be installed on a clientsystem usingpip:
pipinstallst2client
Configuration
The command line client can be configured using one or more of the approacheslisted below:
Configuration file (
~/.st2/config)Environment variables (
ST2_API_URL, etc.)Command line arguments (
st2--cacert=...actionlist, etc.)
Command line arguments have highest precedence, followed by environment variables, and thenconfiguration file values.
If the same value is specified in multiple places, the value with the highest precedence will beused. For example, ifapi_url is specified in the configuration file and in an environmentvariable ($ST2_API_URL), the environment variable will be used.
Configuration File
The CLI can be configured through an ini-style configuration file. By default,st2 willuse the file at~/.st2/config.
If you want to use configuration from a different file (e.g. you have one config per deploymentor environment), you can select which file to use using theST2_CONFIG_FILE environmentvariable or the--config-file command line argument.
For example (environment variable):
ST2_CONFIG_FILE=~/.st2/prod-configst2actionlist
For example (command line argument):
st2--config-file=~/.st2/prod-configactionlistAn example configuration file with all the options and the corresponding explanations isincluded below:
# Configuration file for the StackStorm CLI[general]base_url=http://127.0.0.1api_version=v1# Path to the CA cert bundle used to validate the SSL certificatescacert=[cli]debug=True# True to cache the retrieved auth token during authentication in ~/.st2/token# and use the cached token in the subsequent API requestscache_token=True# Timezone used for timestamps displayed in the CLI. If not provided it defaults# to UTCtimezone=Europe/Ljubljana[credentials]# Credentials used to authenticate against the auth API and retrieve the auth# tokenusername=test1password=testpassword# or authenticate with an api key.# api_key = <key># Optional additional http basic auth credentials which are sent with each HTTP# request except the auth request to /v1/auth/tokens endpoint.# Available in StackStorm >= v3.4.0# NOTE: Username can't contain colon (:) character.# basic_auth = username:password[api]url=http://127.0.0.1:9101/v1# or for a remote instance# url = https://example.com/api/v1[auth]url=http://127.0.0.1:9100/# or for a remote instance#url = https://example.com/auth/v1[stream]url=http://127.0.0.1:9102# or for a remote instance# url = https://example.com/stream/v1
If you want the CLI to skip parsing of the configuration file, you can do that by passing the--skip-config flag to the CLI:
st2--skip-configactionlist
Authentication and Auth Token Caching
The previous section showed an option for storing your password in plaintext in your configurationfile. Thest2login command offers an alternative that does not store the password in plaintext.Similar tost2auth, you must provide your username and password:
st2loginst2admin--password'Password1!'This command caches your authentication token, but also modifies the CLI configuration to includethe referenced username. This way, future commands will know which cached token to use forauthentication, since tokens are cached using thetoken-<username> format. The password itselfdoes not need to be stored in the config file.
Warning
st2login will overwrite the “credentials” section of the configuration.It will overwrite the configured username and will remove any configured password.
These auth tokens are by default cached on the local filesystem (in the~/.st2/token-<username>file) and re-used for subsequent requests to the API service. You will need to re-login once thegenerated token has expired, or use of the--write-password flag, which writes the password tothe config.
Thest2whoami command will tell you who is the currently authenticated user.
You can switch between users by re-running thest2login command. Any existing users’ tokencache files will remain, but the CLI configuration will be changed to point to the new username.
Note
As with many otherst2 commands,st2login will not create the configuration filefor you. Keep this in mind especially if you’re leveraging the--config-file CLI option,or similar.
You can still use the “old” method of supplying both username and password in the configurationfile. If both a username and password are present in the configuration, then the client willautomatically try to authenticate with these credentials.
If you want to disable auth token caching and want the CLI to retrieve a new auth token on eachinvocation, setcache_token toFalse:
[cli]cache_token=False
The CLI will by default also try to retrieve a new token if an existing one has expired.
If you have manually deleted or revoked a token before expiration you can clear the cached tokenby removing the~/.st2/token file.
If the configuration file has an API key as authentication credentials, the CLI will use that asthe primary method of authentication instead of auth token.
Using Debug Mode
The command line tools accepts the--debug flag. When this flag is provided,debug mode will be enabled. Debug mode consists of the following:
On error/exception, full stack trace and client settings (API URL, auth URL, proxy information,etc.) are printed to the console.
The equivalent
curlcommand for each request is printed to the console. This makes it easyto reproduce actions performed by the CLI usingcurl.Raw API responses are printed to the console.
For example:
st2--debugactionlist--pack=coreExample output (no error):
st2--debugactionlist--pack=core# -------- begin 140702450464272 request ----------curl-XGET-H'Connection: keep-alive'-H'Accept-Encoding: gzip, deflate'-H'Accept: */*'-H'User-Agent: python-requests/2.5.1 CPython/2.7.6 Linux/3.13.0-36-generic''http://localhost:9101/v1/actions?pack=core'# -------- begin 140702450464272 response ----------[{"runner_type":"http-runner","name":"http","parameters":{...
Example output (error):
st2--debugactionlist--pack=coreERROR:('Connection aborted.',error(111,'Connection refused'))Clientsettings:----------------ST2_BASE_URL:http://localhostST2_AUTH_URL:https://localhost:9100ST2_API_URL:http://localhost:9101/v1Proxysettings:---------------HTTP_PROXY:HTTPS_PROXY:Traceback(mostrecentcalllast):File"./st2client/st2client/shell.py",line175,inrunargs.func(args)File"/data/stanley/st2client/st2client/commands/resource.py",line218,inrun_and_printinstances=self.run(args,**kwargs)File"/data/stanley/st2client/st2client/commands/resource.py",line37,indecoratereturnfunc(*args,**kwargs)...
Using CLI in Scripts
The CLI returns a non-zero return code for any erroneous operation. You can capturethe return code of CLI commands to check whether the command succeeded.
For example:
st2actiongettwilio.send_sms+-------------+--------------------------------------------------------------+|Property|Value|+-------------+--------------------------------------------------------------+|id|54bfff490640fd2f6224ac1a||ref|twilio.send_sms||pack|twilio||name|send_sms
Now, let’s get the exit code of the previous command:
echo$?0
Now, let’s run a command that we know will fail:
st2actiongettwilio.make_callAction"twilio.make_call"isnotfound.Let’s check the exit code of the last command:
echo$?2
Obtaining an Authentication Token in Scripts
If you want to authenticate and obtain an authentication token inside your (shell) scripts, you canuse thest2auth CLI command in combination with the-t flag.
This flag will cause the command to only print the token tostdout on successfulauthentication. This means you don’t need to deal with parsing JSON or CLI output format.
Example usage:
st2authtest1-p'testpassword'-t0280826688c74bb9bd541c26631df298Example usage inside a Bash script:
TOKEN=$(st2authtest1-p'testpassword'-t)# Now you can use the token (e.g. pass it to other commands, set an# environment variable, etc.)echo${TOKEN}
Changing the CLI Output Format
By default, the CLI returns and prints results in a user-friendly table-orientedformat:
st2actionlist--pack=slack+--------------------+-------+--------------+-------------------------------+|ref|pack|name|description|+--------------------+-------+--------------+-------------------------------+|slack.post_message|slack|post_message|PostamessagetotheSlack|||||channel.|+--------------------+-------+--------------+-------------------------------+
If you want a raw JSON result as returned by the API (e.g. you are using the CLI as part of yourscript and you want the raw result which you can parse), you can pass the-j flag:
st2actionlist-j--pack=slack[{"description":"Post a message to the Slack channel.","name":"post_message","pack":"slack","ref":"slack.post_message"}]
Only Displaying a Particular Attribute
By default, when retrieving the action execution result usingst2executionget,the whole result object will be printed:
st2executionget54d8c52e0640fd1c87b9443fSTATUS:succeededRESULT:{"failed":false,"stderr":"","return_code":0,"succeeded":true,"stdout":"Mon Feb 9 14:33:18 UTC 2015"}
If you only want to retrieve a specific result attribute, use the-k<attributename> flag:
st2executionget-kstdout54d8c52e0640fd1c87b9443fMonFeb914:33:18UTC2015
If you only want to retrieve and print out a specific attribute of the execution,you can do that using--attr<attributename> flag.
For example, if you only want to printstart_timestamp attribute of the resultobject:
st2executionget54d8c52e0640fd1c87b9443f-astart_timestampstart_timestamp:2015-02-24T23:01:15.088293ZYou can also specify multiple attributes:
st2executionget54d8c52e0640fd1c87b9443f--attrstatusresult.stdoutresult.stderrstatus:succeededresult.stdout:MonFeb914:33:18UTC2015result.stderr:
Similarly for theexecutionlist command:
st2executionlist-aidstatusresult+--------------------------+-----------+---------------------------------+|id|status|result|+--------------------------+-----------+---------------------------------+|54eb51000640fd34e0a9a2ce|succeeded|{u'succeeded':True,u'failed':||||False,u'return_code':0,||||u'stderr':u'',u'stdout':||||u'2015-02-23 || | | 16:10:39.916375\n'}||54eb51000640fd34e0a9a2d2|succeeded|{u'succeeded':True,u'failed':||||False,u'return_code':0,||||u'stderr':u'',u'stdout':||||u'2015-02-23 || | | 16:10:40.444848\n'}|
Escaping Shell Variables
When you use local and remote actions (e.g.core.local,core.remote, etc.), you need towrapcmd parameter values in a single quote or escape the variables. Otherwise, the shellvariables will be expanded locally which is something you usually don’t want.
Using single quotes:
st2runcore.localenv='{"key1": "val1", "key2": "val2"}'cmd='echo "ponies ${key1} ${key2}"'
Escaping the variables:
st2runcore.remotehosts=localhostenv='{"key1": "val1", "key2": "val2"}'cmd="echo ponies \${key1} \${key2}
Specifying Parameters with Type “array”
When running an action usingst2run command, you specify the value of parameters with typearray as a comma delimited string.
Inside the CLI, this string gets split on commas and passed to the API as a list.
Example 1 - Simple Case (Array of Strings)
st2runmypack.myactionparameter_name="value 1,value2,value3"
In this case, theparameter_name value would get passed to the API as a list (JSON array) withthree items -["value1","value2","value3"].
Example 2 - Complex Case (Array of Objects)
When you want to pass more complex type (e.g. arrays of objects) value to an action, you can do itlike this:
st2run--auto-dictmypack.set_interfaces\nic_info="target:eth0,ipaddr:192.168.0.10,netmask:255.255.255.0,mtu:1454"\nic_info="target:eth1,ipaddr:192.168.0.11,netmask:255.255.255.0,mtu:2000"
In this case, thenic_info value passed to themypack.set_interfaces action would be parsedand look like this:
[{'netmask':'255.255.255.0','ipaddr':'192.168.0.10','target':'eth0','mtu':1454},{'netmask':'255.255.255.0','ipaddr':'192.168.0.11','target':'eth1','mtu':2000}]
Note
The st2 cli option--auto-dict is required to use this functionality. When you run actionwithout this option, each colon separated parameters are not parsed as dict object but just string.
And this option and its functionality will be deprecated in the next release in favor of a morerobust conversion method.
To parse each value in the object as an expected type, you need to specify the type of each valuein the action metadata, like this.
parameters:nic_info:type:arrayproperties:target:type:stringipaddr:type:stringnetmask:type:stringmtu:type:integer
Or you can use JSON notation:
st2runmypack.myactionparameter_name='[{"Name": "MyVMName"}]'
Note
When using JSON string notation, parameter value needs to be wrapped inside singlequotes (e.g.parameter='{"Key":"Value"}'), otherwise quotes (") inside the JSONstring need to be escaped with a backslash (\ - e.g.parameter="{\"Key\":\"Bar\"}").
Specifying Parameters with Type “object”
When running an action usingst2run command, you can specify the value of parameters with typeobject using two different approaches:
JSON String Notation
For complex objects, you should use JSON notation:
st2runcore.remotehosts=localhostenv='{"key1": "val1", "key2": "val2"}'cmd="echo ponies \${key1} \${key2}
Note
When using JSON string notation, parameter value needs to be wrapped inside singlequotes (e.g.parameter='{"Key":"Value"}'), otherwise quotes (") inside the JSONstring need to be escaped with a backslash (\ - e.g.parameter="{\"Key\":\"Bar\"}").
Comma-delimitedkey=value Pairs String Notation
For simple objects (such as specifying a dictionary where both keys and values are simple strings),use this notation:
st2runcore.remotehosts=localhostenv="key1=val1,key2=val2"cmd="echo ponies \${key1} \${key2}"
Reading Parameter Values From a File
The CLI also supports the special@parameter notation which makes it read parametervalues from a file.
An example of when this might be useful is when you are using http runner actions, or when you wantto read information such a private SSH key content from a file.
Example:
st2runcore.remotehosts=<host>username=<username>@private_key=/home/myuser/.ssh/id_rsacmd=<cmd>
Re-running an Action
To re-run a particular action, you can use thest2executionre-run<existingexecutionid> command.
By default, this command re-runs an action with the same set of input parameterswhich were used with the original action.
The command takes the same arguments as therun/actionexecute command. This means you canpass additional runner or action specific parameters to the command. Those parameters are thenmerged with the parameters from the original action and used to run a new action.
For example:
st2runcore.localenv="VAR=hello"cmd='echo $VAR; date'.+-----------------+--------------------------------+|Property|Value|+-----------------+--------------------------------+|id|54e37a3c0640fd0bd07b1930||context|{|||"user":"stanley"|||}||parameters|{|||"cmd":"echo$VAR; date",|||"env":{|||"VAR":"hello"|||}|||}||status|succeeded||start_timestamp|Tue,17Feb201517:28:28UTC||result|{|||"failed":false,|||"stderr":"",|||"return_code":0,|||"succeeded":true,|||"stdout":"hello || | Tue Feb 17 17:28:28 UTC 2015 || | "|||}||action|core.local||callback|||end_timestamp|Tue,17Feb201517:28:28UTC|+-----------------+--------------------------------+st2runre-run54e37a3c0640fd0bd07b1930.+-----------------+--------------------------------+|Property|Value|+-----------------+--------------------------------+|id|54e37a630640fd0bd07b1932||context|{|||"user":"stanley"|||}||parameters|{|||"cmd":"echo$VAR; date",|||"env":{|||"VAR":"hello"|||}|||}||status|succeeded||start_timestamp|Tue,17Feb201517:29:07UTC||result|{|||"failed":false,|||"stderr":"",|||"return_code":0,|||"succeeded":true,|||"stdout":"hello || | Tue Feb 17 17:29:07 UTC 2015 || | "|||}||action|core.local||callback|||end_timestamp|Tue,17Feb201517:29:07UTC|+-----------------+--------------------------------+st2runre-run7a3c0640fd0bd07b1930env="VAR=world".+-----------------+--------------------------------+|Property|Value|+-----------------+--------------------------------+|id|54e3a8f50640fd140ae20af7||context|{|||"user":"stanley"|||}||parameters|{|||"cmd":"echo$VAR; date",|||"env":{|||"VAR":"world"|||}|||}||status|succeeded||start_timestamp|Tue,17Feb201520:47:49UTC||result|{|||"failed":false,|||"stderr":"",|||"return_code":0,|||"succeeded":true,|||"stdout":"world || | Tue Feb 17 20:47:49 UTC 2015 || | "|||}||action|core.local||callback|||end_timestamp|Tue,17Feb201520:47:49UTC|+-----------------+--------------------------------+
Cancel an Execution
When dealing with long running executions, you may want to cancel some of them before they havecompleted.
To cancel an execution, run:
st2executioncancel<existingexecutionid>
Passing Environment Variables to Runner asenv Parameter
Local, remote and Python runners support theenv parameter. This parameter tells the runnerwhich environment variables should be accessible to the action which is being executed.
User can specify environment variables manually using theenv parameter in the same manner asother parameters:
st2runcore.remotehosts=localhostenv="key1=val1,key2=val2"cmd="echo ponies \${key1} \${key2}"
In addition to that, users can pass the-e/--inherit-env flag to theactionruncommand.
This flag will cause the command to inherit all the environment variables which are accessible tothe CLI and send them as anenv parameter to the action.
Keep in mind that some global shell login variables such asPWD,PATH and others areignored and not inherited. The full list of ignored variables can be found in theaction.py file.
For example:
st2run--inherit-envcore.remotecmd=...