3.7 Fabric应用实例

3.7.1 开发环境中的Fabric应用实例

笔者公司在开发环境下使用的都是Xen和KVM虚拟机器,有不少数据,因为是内网环境,所以直接用root和SSH密码连接。系统统一为CentOS 6.4 x86_64,内核版本为2.6.32-358.el6.x86_64,Python版本为2.6.6。

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

实例1,同步Fabric跳板机的/etc/hosts文件,脚本如下:

#!/usr/bin/python

# -*- coding: utf-8 -*-

from fabric.api import *

from fabric.colors import *

from fabric.context_managers import *

#fabric.context_managers是

Fabric的上下文管理类,这里需要

import是因为下面会用到

with

env.user = 'root'

env.hosts = ['192.168.1.200','192.168.1.205','192.168.1.206']

env.password = 'bilin101'

@task

#限定只有

put_hosts_file函数对

fab命令可见

def put_hosts_files():

print yellow("rsync /etc/host File")

with settings(warn_only=True): #出现异常时继续执行,不终止

put("/etc/hosts","/etc/hosts")

print green("rsync file success!")

'''这里用到

with是确保即便发生异常,也将尽早执行下面的清理操作,一般来说,

Python中的

with语句一般多用于执行清理操作(如关闭文件),因为

Python中打开文件以后的时间是不确定的,如果有其他程序试图访问打开的文件会导致出现问题。

'''

for host in env.hosts:

env.host_string = host

put_hosts_files()

实例2,同步公司内部开发服务器的git代码,现在互联网公司的开发团队应该都比较倾向于采用git作为开发版本管理工具了,此脚本稍微改动下应该也可以应用于线上的机器,脚本如下:

#!/usr/bin/python

# -*- coding: utf-8 -*-

from fabric.api import *

from fabric.colors import *

from fabric.context_managers import *

env.user = 'root'

env.hosts = ['192.168.1.200','192.168.1.205','192.168.1.206']

env.password = 'redhat'

@task

#同上面一样,指定

git_update函数只对

fab命令可见

def git_update():

with settings(warn_only=True):

with cd('/home/project/github'):

sudo('git stash clear')

#清理当前

git中所有的储藏,以便于我们

stashing最新的工作代码

sudo('git stash')

'''如果想切换分支,但是又不想提交正在进行的工作

,那么就得储藏这些变更。为了往

git堆栈推送一个新的储藏,只需要运行

git stash命令即可

'''

sudo('git pull')

sudo('git stash apply')

#完成当前代码

pull以后,取回最新的

stashing工作代码,这里使用命令

git stash apply

sudo('nginx -s reload')

for host in env.hosts:

env.host_string = host

git_update()