依賴(lài)
python2.7
fabric==1.1
2.1 以上的的fabric感覺(jué)不是很好用念脯,而且在安裝的時(shí)候一堆問(wèn)題狞洋,資料也比較少,所以我們?cè)谏a(chǎn)環(huán)境采用的是 1.1 版本和二。
安裝
$pip install fabric==1.1
一個(gè)最簡(jiǎn)單的例子
直接使用 fab 命令:
當(dāng)前目錄新建 fabfile.py 文件徘铝,寫(xiě)入以下內(nèi)容:
from fabric.api import *
def hello():
print 'hello! %s' % local('echo "$USER"')
保存,在當(dāng)前目錄執(zhí)行
$fab hello
可以看到如下輸出
'$fab hello' output
fabric 做了以下:
- 加載 fabfile.py惯吕,并執(zhí)行 hello() 函數(shù)
- 本地執(zhí)行 ** echo "$USER" **惕它,并返回執(zhí)行結(jié)果
除了 local() 函數(shù)以外,fabric 還有以下常用函數(shù):
# Run a shell command on a remote host
# 在服務(wù)器上執(zhí)行命令
run(*args, **kwargs)
# Context manager that keeps directory state when calling remote operations.
# 上下文管理器废登,用于切換目錄
cd(path)
一個(gè)略復(fù)雜的例子
本例節(jié)選自數(shù)據(jù)組 nginx 自動(dòng)重啟腳本淹魄,主要行為:
- 鏈接服務(wù)器
- cd 到指定目錄,并從 gitlab 拉取最新 repo
- 將 repo 中的 conf 文件復(fù)制到指定目錄
- reload nginx
from __future__ import with_statement
from fabric.api import *
import json
env.hosts = ['xx.xx.xx.xx']
env.user = 'test_user'
def copy_config():
source_path = '/home/data/projects/focus-data-nginx-config/%s'
with open('./map.json') as f:
jo = json.load(f)
for j in jo:
target_path = j['target_path']
s_path = source_path % j['source_path']
run('cp %s %s' % (s_path, target_path))
def remote():
project_path = '/home/data'
with cd(project_path):
result = run('ls')
if 'projects' not in result:
run('mkdir projects')
pull_from_git_lab()
run('ls projects/focus-data-nginx-config')
copy_config()
nginx_reload()
def pull_from_git_lab():
with cd('projects'):
if 'focus-data-nginx-config' in run('ls'):
with cd('focus-data-nginx-config'):
run('git pull origin master ')
else:
run('git clone git@xxx.git')
def nginx_reload():
run('sudo nginx -s reload')
啟動(dòng)命令:
$fab remote
特別提醒
利用 fabric 起后臺(tái)應(yīng)用時(shí)會(huì)有問(wèn)題堡距,比如:
# 不能正常運(yùn)行甲锡,是 fabric 本身的問(wèn)題
run('nohup java /azkaban-flow-new-0.0.1-SNAPSHOT.jar &')
這時(shí)就需要加一個(gè)小 trick
# sleep 5 秒就 OK 了
run('nohup java /azkaban-flow-new-0.0.1-SNAPSHOT.jar & sleep 5; exit 0')