Fabric 自动部署
部署大多都是一些重复的工作,故在这里记录一下学习fabric的过程,借鉴了网上的大神和文档,留作纪念。
环境配置
sudo pip install fabric # sudo 取决于OS
主要参考:官方文档
本机操作
from fabric.api import local, lcd
def test_local():
with lcd("./filename"):
local("ls")
# fab test_local
def test_local_params(name, value):
print(value, name)
# fab test_local_params:name=name, value=value
local() 可以执行linux命令 在这里不多描述了。
远端操作
from fabric.api import local, cd, run, env
env.hosts = ['hostname@ip:port', ]
env.password = 'pwd' # 密码自己处理,不建议保存明文.
def test_online():
with cd("/var/www/"):
run("ls -l")
# fab test_online
文件校验上传
from fabric.api import *
env.hosts = ['hostname@ip:port', ]
env.password = 'pwd'
@runs_once
@task
def tarfile():
with lcd('/tmp/file'):
local('tar czf messages.tar.gz messages')
@task
def putfile():
run('mkdir -p /tmp/file')
with cd('/tmp/file'):
with settings(warn_only=True):
result=put('/tmp/file/messages.tar.gz','/tmp/file')
if result.failed and not confirm('put file filed,Continue[Y/N]?'):
abort('Aborting file put task!')
@task
def checkfile():
with settings(warn_only=True):
lmd5=local('md5sum /tmp/file/messages.tar.gz',capture=True).split(' ')[0]
rmd5=run('md5sum /tmp/file/messages.tar.gz').split(' ')[0]
if lmd5==rmd5:
print 'ok'
else:
print 'error'
# 合并操作
@task
def main():
tarfile()
putfile()
checkfile()