action包含两个部分:
action元数据文件和action的执行脚本文件。
action元数据文件是yaml格式,描述这个action的名称,以及执行脚本的位置,执行脚本需要的参数。
action的YAML参数如下:
name: 动作名称
runner_type: 执行动作的运行器类型
enabled: 当为disabled时,动作不能被调用
entry_point: 动作发布脚本相关的位置。
/opt/stackstorm/packs/${pack_name}/actions/
目录。
注意编写的脚本必须放在这里,默认不止定pack_name,那么就是default。
parameters: 一个参数字典和可选的用于描述类型和默认的元数据。
这个元数据以JSON格式来组织数据。共同的参数类型可以时:
string, boolean, number(例如 1.0, 1, 3.3333等),
object, integer(例如 1000)和array。
如果元数据被提供了,输入参数可以在动作执行的时候被校验。
否则,校验会省略。
该文件名为: count_sensor_action_meta.yaml
内容如下:
name: "count_action"
description: "count action description"
runner_type: "python-script"
enabled: true
entry_point: "count_sensor_action.py"
parameters:
content:
type: "string"
description: "the content parameter"
required: true
position: 0
该文件名为: count_sensor_action.py
内容如下:
from datetime import datetime
from st2common.runners.base_action import Action
class CountAction(Action):
# append content into file
def run(self, content):
fileName = "/home/count.txt"
try:
currTime = str(datetime.now())
# note, a+ means append instead of w+
with open(fileName, "a+") as fr:
realContent = str(content) + " time: " + currTime + "\n"
fr.write(realContent)
info = "content: {content}, time: {time}".format(
content=content,
time=currTime
)
print info
return (True, content)
except Exception as ex:
info = "write content : {content}, exception: {exp}, message: {mes}".format(
content=content,
exp=ex.__class__.__name__,
mes=ex
)
print info
return (False, content)
将上述count_sensor_action_meta.yaml和count_sensor_action.py
都放在/opt/stackstorm/packs/default/actions/目录下面
然后执行:
st2 action create /opt/stackstorm/packs/default/actions/count_sensor_action_meta.yaml
来注册一个单独的动作。为了加载所有的动作,请使用
st2ctl reload --register-actions
输出结果如下:
+---------------+------------------------------------------------+
| Property | Value |
+---------------+------------------------------------------------+
| id | 5c6d3ba79dc6d609a34b2e35 |
| uid | action:default:count_action |
| ref | default.count_action |
| pack | default |
| name | count_action |
| description | count action description |
| enabled | True |
| entry_point | count_sensor_action.py |
| runner_type | python-script |
| parameters | { |
| | "content": { |
| | "position": 0, |
| | "required": true, |
| | "type": "string", |
| | "description": "the content parameter" |
| | } |
| | } |
| metadata_file | actions/count_sensor_action_meta.yaml |
| notify | |
| output_schema | |
| tags | |
+---------------+------------------------------------------------+
执行:
st2 run default.count_action content=hello
输出结果如下所示:
.
id: 5c72016b9dc6d65bd9300199
status: succeeded
parameters:
content: hello
result:
exit_code: 0
result: hello
stderr: ''
stdout: 'content: hello, time: 2019-02-24 10:29:00.370398
'
查看内容是否真正写入到第3部分的/home/count.txt文件中
cat /home/count.txt
输出如下:
hello time: 2019-02-24 10:29:00.370398
验证action已经正确执行
参考:
[1] https://docs.stackstorm.com/actions.html
[2] https://blog.csdn.net/wlhdo71920145/article/details/80338798