2015年10月30日 星期五

[Linux] Python Fabric - 在 SSH 架構上,進行服務部署 @ Ubuntu 14.04

強者同事又獻技 fab 指令,從官網簡介:

Fabric is a Python (2.5-2.7) library and command-line tool for streamlining the use of SSH for application deployment or systems administration tasks.

原來如此!我還活在播接時代再把玩 bash script XDD 其實之前也有試過一些同時發 ssh remote command 的工具,但悲劇收場後,就沒再用了,現在就在來吸收這套吧!

$ sudo apt-get install fabric
$ fab
Fatal error: Couldn't find any fabfiles!

Remember that -f can be used to specify fabfile path, and use -h for help.

Aborting.


是的, fab 指令會尋找當前目錄下的 fabfile.py:

$ vim fabfile.py
def hello(what):
print 'hello ' + str(what)


$ fab hello:world
hello world

Done.


非常簡潔明瞭,反正 fab 後面接的字串就是個 fabfile.py 裡定義的函數,冒號後面就是給進去的參數。接著要寫一些遠端部署指令就是寫個 function 定義一些想傳的參數,接著就愉快地寫 python 就好!可以省去用一堆 ssh target_host "remote_command" 的方式了!

$ vim fabfile.py
from fabric.api import run, task, execute, runs_once
from fabric.colors import green, magenta
import fabric.api as api

@task(default=True)
def heartbeat():
        _info("hearbeat")
run("date")

def _info(message):
        print green(message + " on %s" % api.env.host_string)

def _warn(message):
        print magenta(message + " on %s" % api.env.host_string)
$ fab
hearbeat on None
No hosts found. Please specify (single) host string for connection: localhost
[localhost] run: date
[localhost] Login password for 'user':
[localhost] out: Fri Oct 30 12:51:51 UTC 2015
[localhost] out:


Done.
Disconnecting from localhost... done.

$ fab -H localhost
[localhost] Executing task 'heartbeat'
hearbeat on localhost
[localhost] run: date
[localhost] Login password for 'user':
[localhost] out: Fri Oct 30 12:53:09 UTC 2015
[localhost] out:


Done.
Disconnecting from localhost... done.


接下來,就可以想想一連串的行為了!

沒有留言:

張貼留言