部署系统基于Salt Runner编写,Salt Runner使用salt-run命令执行的命令行工具,可以通过调用Salt API很轻松构建。Salt Runner与Salt的执行模块很像,但是在Salt Master上运行而非Salt Minion上。
配置Salt Master 配置文件(/etc/salt/master.d/publish.conf)如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 svn: username: 'publish' password: '#1qaz@WSX#ht' publish: master: 'admin.grid.mall.com' cwd: '/data1/vhosts' projects: www.mall.com: remote: 'svn://172.16.100.81/www.mall.com' target: - '172.16.100.21::www_mall_com' - '172.16.100.22::www_mall_com' - '172.16.100.23::www_mall_com'
另外还要配置runner的放置目录:runner_dirs: [/srv/salt/_runners],配置完成后要重启Puppet master。
Web前端部署rsync服务 rsync服务由/srv/salt/rsync模块进行管理,rsync配置文件(etc/rsyncd.conf)如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 uid = nobody gid = nobody use chroot = yes max connections = 150 pid file = /var/run/rsyncd.pid log file = /var/log/rsyncd.log transfer logging = yes log format = %t %a %m %f %b syslog facility = local3 timeout = 300 incoming chmod = Du=rwx,Dog=rx,Fu=rw,Fgo=r hosts allow=172.16.100.0/24 [www_mall_com] path=/data1/vhosts/www.mall.com/htdocs/ read only=no
编写runner脚本 部署系统在Salt Master上把代码从SVN中检出,通过rsync命令部署到web前端。runner脚本(/srv/salt/_runners/publish.py)如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 ''' Functions to publish code on the master ''' import salt.clientimport salt.outputdef push (project, output=True) : ''' publish code to web server. CLI Example: .. code-block:: bash salt-run publish.push project ''' client = salt.client.LocalClient(__opts__['conf_file' ]) ret = client.cmd(__opts__['publish' ]['master' ], 'svn.checkout' , [ __opts__['publish' ]['cwd' ], __opts__['projects' ][project]['remote' ] ], kwarg={ 'target' :project, 'username' :__opts__['svn' ]['username' ], 'password' :__opts__['svn' ]['password' ] } ) if ret: msg = 'URL: %s\n%s' %(__opts__['projects' ][project]['remote' ], ret[__opts__['publish' ]['master' ]]) ret = {'Check out code' : msg} if output: salt.output.display_output(ret, '' , __opts__) for target in __opts__['projects' ][project]['target' ]: cmd = '/usr/bin/rsync -avz --exclude=".svn" %s/%s/trunk/* %s/' %(__opts__['publish' ]['cwd' ], project, target) ret[target] = client.cmd(__opts__['publish' ]['master' ], 'cmd.run' , [ cmd, ], ) title = '\nSending file to %s' %target.split(':' )[0 ] ret = {title: ret[target][__opts__['publish' ]['master' ]]} if output: salt.output.display_output(ret, '' , __opts__) return ret
注意,一个项目(svn://172.16.100.81/www.mall.com )通常会建立三个SVN子目录:trunk、branches、tags,上面脚本推送时只会将trunk目录下的代码部署到web前端。
代码部署
publish为上文runner脚本名,push为此脚本中定义的推送函数,www.mall.com为salt master中定义的项目名。
参考:Salt Runners Python client API