Action是一個具體的代碼塊,可以運用各種語言。
以下是一個簡單的任務列表,可以通過Action實現:
1、重啟一個服務在一臺服務器上;
2、創建一個新的云主機;
3、確認Nagios發出的警報;
4、通過郵件或者短信發出報警信息;
5、通過IRC通道發出報警信息;
6、發送信息給slack;
7、快照虛擬機;
8、運行一個監控檢測;
當具有匹配條件的規則被觸發時,可以執行操作。可以將多個動作串聯到一個工作流中。操作也可以通過CLI、API或UI直接從客戶端執行。
Managing and Running Actions
在命令行下使用命令:
st2 action
st2action--help更多信息可以運行命令st2action -h例如:? ? st2actionlist -h
下面的命令展示了如何獲取關于可用操作及其參數的信息的示例:
# Listallavailable actions (note that output may be lengthy)st2actionlist#listallactionsin"linux"packst2actionlist -p linux st2actionlist --packlinux#顯示指定packlinux 下的動作check_loadavgst2actionget linux.check_loadavg#通過命令獲取使用linux.check_loadavg動作的參數信息:st2 run linux.check_loadavg -h
手動執行action命令如下:
st2 run or st2 action execute
#Execute action immediately and display the results#立即執行并返回結果#通過core.http動作執行訪問retail.belle.net.cn這個URL,直接輸出返回值;st2runcore.http url="http://retail.belle.net.cn"#使用execute方式操作,進行計劃執行st2 action execute core.http url="http://retail.belle.net.cn"#上述命令生成一個技術執行list,通過命令查詢獲取任務IDst2 executionlist-n1#獲取執行結果st2 executionget5a5c60ffe138237e295d453f#在執行動作上增加時間標記st2runcore.localcmd=date--trace-tag="simple-date-check-`date +%s`"
Action Runners
Action是需要根據用戶實現操作的執行環境。Stackstorm自帶的action如SSH等,其目的是運行行動的作者實施而不是搭建環境。
Available Runners
action 是通過runner指定執行運行的,目前系統提供下列runner:
1、local-shell-cmd: 這個是一個本地runner,這個runner是在運行Stackstorm的服務器上執行linux命令;2、local-shell-script:這個是一個本地runner,action是通過腳本實現的,在Stackstorm運行的服務器運行腳本;3、remote-shell-cmd: 這個運行程序在用戶提供的一個或多個遠程主機上執行Linux命令;4、remote-shell-script: 遠程在主機上執行腳本;5、python-script: 這個是一個Python的腳本,action通過Python的run()方法實現,在運行Stackstorm的服務器運行組件,通過run()返回一個元組成功的狀態標志和結果對象。6、http-request: 執行http的action,通過http客戶端訪問返回http值;7、action-chain:這個runner是執行一個簡單的工作流;8、mistral-v2: 這個是支持Openstack 的工作流runner;9、cloudslang: 這個是支持層cloudslang的工作流runner;10、inquirer: This runner providesthecore logicoftheInquiries?feature.
Writing Custom Actions
Action 是有兩部分組成:
1、yaml文件是Actions原數據的描述與它的輸入;
2、實現Action動作的腳本;
如上所述,腳本需要遵循如下約定:(不限制語言類型)
1、腳本成功執行退出狀態為0,異常執行退出狀態為非零;
2、所有日志均采用標準輸出;
Action Metadata
yaml文件是用于描述Action的行為動作定義。以下屬性存在元數據中:
name - Action的名字
runner_type -? 執行Action 的runner的類型
enable - Action是否可以被調用;
entry_point - Action運行腳本的所在目錄路徑:/opt/stackstorm/packs/${pack_name}/actions/
parameters - 描述元數據類型和默認值的參數字典。元數據是遵循JSON模式規范的結構化數據。常用參數類型含有 ‘string’ ,‘boolean’。‘number’(包含所有數字含小數等),‘object’,‘integer’(整數型)和 ‘array’。如果輸入的參數正確可以執行Action,否則將跳過此Action
以下是一個簡單的示例元數據文件,此文件類型是Python語言,通過Twilio web服務發送短信:
---name:"send_sms"runner_type:"python-script"description:"This sends an SMS using twilio."enabled:trueentry_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 %}!"
這個Action的runner是Python腳本。這個執行腳本send_sms.py與元數據在一個相同目錄下。這個Action含有三個參數(from_number,to_number,body)
在上述例子中,to_number 參數的屬性secret的值為true。如果一個屬性被標記為secret,值將會記錄在Stackstorm的服務日志中。
Parameters in Actions
在前一個的例子中,你可能會注意到你可以用st2kv.system前綴模板中的key-value存儲參數。可以執行環境中的變量。例如:
parameters:user:type:"string"description:"User of this action."required: truedefault:"{{action_context.api_user}}"
action_context是環境中調用的變量。根據如何運行Action和Action的類型(簡單或者工作流)來更改action_context的變量。
一個簡單的執行的API只需要包含user和pack變量。執行觸發的ChatOPS包含變量 api_user、user、pack和source_channel。在ChatOps中,api_user是Chatclient連接ChatOps的用戶名,user是Stackstorm使用配置hubot的用戶。source_channel 是接入ChatOps 命令集的通道。
除了action_context之外,通過config_context可以訪問包含pack配置文件的key-value存儲。在下面的例子中,如何給參數指定默認值:
---name:"send_sms"runner_type:"python-script"description:"This sends an SMS using twilio."enabled:trueentry_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 %}!"
在ActionChains 和工作流中,工作流中的每個任務/工作項都可以訪問上一級的execution_id.
例如,一個Action chain的任務如下所示:
...-? name:"c2"? ref:"core.local"? parameters:? ? cmd:"echo \"c2: parent exec is {{action_context.parent.execution_id}}.\""on-success:"c3"on-failure:"c4"...
Action Registration
新注冊一個Action:
1、將Action放置到指定目錄;
2、告知系統此Action是可用的;
Actions 的包目錄在 /opt/stackstorm/packs/。
一個action默認使用的是default pack,所以新創建的action的目錄默認是在/opt/stackstorm/packs/default/actions。當測試完此action后,應該將其挪至專用pack;
創建一個指定action可以通過 命令? st2 action create my_action_metadata.yaml。重新加載所有action,使用 st2ctl reload --register-actions
Built-in Parameters (內置參數)
在配置元數據時,有些默認的內置參數可以至直接使用,也可以覆蓋更改默認值實現各種runner:
args - (local-shell-script,remote-shell-script)? 定義傳遞給cmd 變量名內命令的參數;
cmd - (local-shell-script,remote-shell-script) 配置在目標系統上運行的命令;
cwd - (local-shell-script,remote-shell-script) 配置執行遠程命令所在目錄;
env - (local-shell-script,local-shell-script-script,remote-shell-script,remote-shell-script,python-script)? 可執行命令和腳本的環境變量;
dir - (local-shell-script , remote-shell-script) 配置在執行前將腳本從一個包復制到目標機器的目錄。默認 /tmp。
Overriding Runner Parameters (覆蓋參數)
runner的參數可以被覆蓋。有的時候需要自定義或者優化action。
可以采取以下 linux.rsync action 導入linux的包;
通過linux.rsync action中的rsync命令 傳遞覆蓋了cmd參數中的remote-shell-cmd屬性。
---? ? name:'rsync'runner_type:'remote-shell-cmd'description:'Copy file(s) from one place to another w/ rsync'enabled:trueentry_point:''parameters:source:? ? ? ? ? ? type:'string'description:'List of files/directories to to be copied'required:truedest_server:? ? ? ? ? ? type:'string'description:"Destination server for rsync'd files"required:truedestination:? ? ? ? ? ? type:'string'description:'Destination of files/directories on target server'required:truecmd:immutable:truedefault:'rsync {{args}} {{source}} {{dest_server}}:{{destination}}'connect_timeout:? ? ? ? ? ? type:'integer'description:'SSH connect timeout in seconds'default:30args:description:'Command line arguments passed to rysnc'default:'-avz -e "ssh -o ConnectTimeout={{connect_timeout}}"'
參數的屬性并不是所有都可以覆蓋的,可重寫屬性如下:
default
description
enum
immutable
required
Environment Variables Available to Actions(用于action的環境變量)
默認情況下,本地、遠程和Python運行程序為操作提供以下環境變量:
ST2_ACTION_PACK_NAME - 正在執行Action的所屬包的名;
ST2_ACTION_EXCUTION_ID -正在執行Action 的操作ID;
ST2_ACTION_API_URL -? Action的API的URL;
ST2_ACTION_AUTH_TOKEN - Action的可用令牌;Action執行完成后,令牌自動失效;
下面本里shell腳本Action的例子中,描述如何使用可用環境變量:
#!/usr/bin/env bash# Retrieve a list of actions by hitting the API using cURL and the information provided# via environment variablesRESULT=$(curl -H"X-Auth-Token: ${ST2_ACTION_AUTH_TOKEN}"${ST2_ACTION_API_URL}/actions)echo${RESULT}
Converting Existing Scripts into Actions (將現有腳本轉換成為Action)
將已有腳本轉換成action按照以下步驟操作即可:
首先確保腳本符合約定
確保你的腳本執行成功的狀態為0、失敗為非零轉態;
創建一個元數據文件
你需要創建一個元數據文件,它用于描述名稱、描述、執行腳本的名字、和runner的參數;
當你轉換腳本為action時,你需要執行local-shell-script或者remote-shell-script runner;
更新腳本中才參數
如果腳本不接受任何參數,可以跳過這步驟
? ? ? 本地和遠程腳本runnner 識別兩類參數:
named - 這參數不包括position具體屬性;
positional- 這參數包括position的具體屬性;
? ? ? 所有參數通過命令行狀態傳遞給腳本。
? ? ? 名稱參數通過以下格式傳遞給腳本:
script.sh --param=value--param2=value--param3=value
? ? 默認情況下,任何參數傳遞都要使用--,如果是使用-,可能一些參數沒有對應前綴,你需要在元數據配置文件周工配置kwarg_op參數,如下:
---name:"my_script"runner_type:"remote-shell-script"description:"Script which prints arguments to stdout."enabled:trueentry_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:"-"
在這個例子中,參數就可以通過以下方式傳遞:
script.sh-key1=value1-key2=value2-key3=value3
Posision參數通過以下格式傳遞至腳本:
script.sh value2 value1 value3
如果腳本只使用位置參數(這通常是現有腳本的情況),則只需在元數據文件中為位置屬性的正確值聲明參數。position參數規則如下下述描述:
string、integer,float - 序列字符串
boolean - 1為真、0為否
array - 序列為一個逗號分隔的字符串(eg? foo,bar,baz)
object - 序列json化
Stackstorm 通過空字符串“”代表一個沒有默認值的參數如:
script.sh value1""value3
Example 1 - existing Bash script with positional arguments
send_to_syslog.sh是一個簡單的shell腳本,通過命令行參數寫入日志提供信息。
這個腳本具有兩個參數:
1、日志系統服務器的地址;
2、寫入信息;
#!/usr/bin/env bashSERVER=$1MESSAGE=$2logger-n${SERVER}${MESSAGE}
由于這個腳本使用position 參數,所以需要在元數據中定義它們:
---name:"send_to_syslog.log"runner_type:"remote-shell-script"description:"Send a message to a provided syslog server."enabled:trueentry_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
上面代碼中,我們聲明了兩個參數“server”和“message”。它們都聲明一個位置屬性(0是server,1是message),這意味著它們將作為位置參數傳遞給Action腳本,因此腳本不需要任何更改。
Writing Custom Python Actions
最簡單的形式,一個Python的action是一個模塊從st2actions.ruuners/pythonrunner.Action繼承和實現run的方法。
Sample Python Action
Metadata file (my_echo_action.yaml):
---name:"echo_action"runner_type:"python-script"description:"Print message to standard output."enabled:trueentry_point:"my_echo_action.py"parameters:? ? message:? ? ? ? type:"string"? ? ? ? description:"Message to print."? ? ? ? required:true? ? ? ? position:0
Action script file (my_echo_action.py):
importsysfromst2actions.runners.pythonrunnerimportActionclassMyEchoAction(Action):? ? def run(self,message):? ? ? ? print(message)? ? ? ? if message == 'working':? ? ? ? ? ? return (True,message)? ? ? ? return (False,message)
這個Python的action將message信息打印到標準輸出。用戶提供的操作參數作為關鍵字參數傳遞給run方法。run方法執行完成后,返回的值和方法(任何值:布爾,字符串,列表,字典,等)被認為是其結果。如果出現異常將執行失敗;
指定執行狀態的另一種方法是返回帶有兩個項的元組:第一個項目是一個布爾指示狀態,第二項是結果本身。
例如:
return false 如果被執行成功將返回“False”,return(False,"Falsed!") 如果執行失敗將返回“Falsed!”的結果。
在上面的示例中,如果傳遞給action的message參數有效,則該操作將被視為成功(表示操作狀態為true的結果中的第一個標志)。如果傳入另一條消息,則操作將被視為失敗(表示操作狀態為false的結果元組中的第一個標志)。
更復雜的例子,可請閱讀?actions in the Libcloud pack in StackStorm Exchange.
Configuration File
配置文件用配置“靜態”不做改變的參數
對于用戶自己定義或者更改的值的參數,應該在元數據文件中配置。
Python可以在整個配置文件中配置,這個是針對pack全局的。配置文件的名為.yaml? 存儲在目錄/opt/stackstorm/configs/
配置文件是YAML格式。配置通過config參數自動解析并傳遞給Action構造類函數
Logging
日志里面的所有動作要通過記錄器是具體的行動,可通過self.logger類屬性進行。
這個記錄是從測井模塊標準Python記錄器所以記錄器方法象預期的那樣工作(如logger.debug,logger.info,等)。
例如:
defrun(self):? ? ...? ? success = call_some_method()ifsuccess:self.logger.info('Action successfully completed')else:self.logger.error('Action failed...')
Action Service
Action serice 是通過提供一個公共方法提供不同的服務。現在支持數據存儲方式。Action可以通過數據庫來提取執行之間的任意數據。
The action service provides the same datastore management methods as the ones available on the sensor service.?
例如:(JSON格式。)
defrun(self):? data = {'somedata':'foobar'}# Add a value to the datastoreself.action_service.set_value(name='cache', value=json.dumps(data))# Retrieve a valuevalue =self.action_service.get_value('cache')? retrieved_data = json.loads(value)# Retrieve an encrypted valuevalue =self.action_service.get_value('ma_password', decrypt=True)? retrieved_data = json.loads(value)# Delete a valueself.action_service.delete_value('cache')
Pre-defined Actions(預先定義的Action)
Stackstorm中有部分預先定義的Action。這些Action在core包中:
core.local
這個Action是可以執行linux下shell的命令。可以直接在命令行下執行,例如:
st2 run core.localcmd='ls-l'
core.remote?
這個Action是可以在遠程主機上執行linux命令,例如:
st2 run core.remote cmd='ls -l'hosts='host1,host2'username='user1'
core.http
這個Action是訪問http的返回值。例如curl執行:
st2 run core.http url="http://httpbin.org/get"method="GET"
基于http登錄,需要用戶名和密碼的基本認證
st2 run core.http url="http://httpbin.org/get"method="GET"username=user1 password=passwd1
To see all actions in the?core?pack:
st2actionlist --pack=core