Python自動(dòng)化運(yùn)維和部署項(xiàng)目工具Fabric使用實(shí)例
Fabric 是使用 Python 開(kāi)發(fā)的一個(gè)自動(dòng)化運(yùn)維和部署項(xiàng)目的一個(gè)好工具,可以通過(guò) SSH 的方式與遠(yuǎn)程服務(wù)器進(jìn)行自動(dòng)化交互,例如將本地文件傳到服務(wù)器,在服務(wù)器上執(zhí)行shell 命令。
下面給出一個(gè)自動(dòng)化部署 Django 項(xiàng)目的例子
# -*- coding: utf-8 -*-
# 文件名要保存為 fabfile.py
from __future__ import unicode_literals
from fabric.api import *
# 登錄用戶和主機(jī)名:
env.user = 'root'
# 如果沒(méi)有設(shè)置,在需要登錄的時(shí)候,fabric 會(huì)提示輸入
env.password = 'youpassword'
# 如果有多個(gè)主機(jī),fabric會(huì)自動(dòng)依次部署
env.hosts = ['www.example.com']
TAR_FILE_NAME = 'deploy.tar.gz'
def pack():
"""
定義一個(gè)pack任務(wù), 打一個(gè)tar包
:return:
"""
tar_files = ['*.py', 'static/*', 'templates/*', 'vue_app/', '*/*.py', 'requirements.txt']
exclude_files = ['fabfile.py', 'deploy/*', '*.tar.gz', '.DS_Store', '*/.DS_Store',
'*/.*.py', '__pycache__/*']
exclude_files = ['--exclude=\'%s\'' % t for t in exclude_files]
local('rm -f %s' % TAR_FILE_NAME)
local('tar -czvf %s %s %s' % (TAR_FILE_NAME, ' '.join(exclude_files), ' '.join(tar_files)))
print('在當(dāng)前目錄創(chuàng)建一個(gè)打包文件: %s' % TAR_FILE_NAME)
def deploy():
"""
定義一個(gè)部署任務(wù)
:return:
"""
# 先進(jìn)行打包
pack()
# 遠(yuǎn)程服務(wù)器的臨時(shí)文件
remote_tmp_tar = '/tmp/%s' % TAR_FILE_NAME
run('rm -f %s' % remote_tmp_tar)
# 上傳tar文件至遠(yuǎn)程服務(wù)器, local_path, remote_path
put(TAR_FILE_NAME, remote_tmp_tar)
# 解壓
remote_dist_base_dir = '/home/python/django_app'
# 如果不存在, 則創(chuàng)建文件夾
run('mkdir -p %s' % remote_dist_dir)
# cd 命令將遠(yuǎn)程主機(jī)的工作目錄切換到指定目錄
with cd(remote_dist_dir):
print('解壓文件到到目錄: %s' % remote_dist_dir)
run('tar -xzvf %s' % remote_tmp_tar)
print('安裝 requirements.txt 中的依賴包')
# 我使用的是 python3 來(lái)開(kāi)發(fā)
run('pip3 install -r requirements.txt')
remote_settings_file = '%s/django_app/settings.py' % remote_dist_dir
settings_file = 'deploy/settings.py' % name
print('上傳 settings.py 文件 %s' % settings_file)
put(settings_file, remote_settings_file)
nginx_file = 'deploy/django_app.conf'
remote_nginx_file = '/etc/nginx/conf.d/django_app.conf'
print('上傳 nginx 配置文件 %s' % nginx_file)
put(nginx_file, remote_nginx_file)
# 在當(dāng)前目錄的子目錄 deploy 中的 supervisor 配置文件上傳至服務(wù)器
supervisor_file = 'deploy/django_app.ini'
remote_supervisor_file = '/etc/supervisord.d/django_app.ini'
print('上傳 supervisor 配置文件 %s' % supervisor_file)
put(supervisor_file, remote_supervisor_file)
# 重新加載 nginx 的配置文件
run('nginx -s reload')
run('nginx -t')
# 刪除本地的打包文件
local('rm -f %s' % TAR_FILE_NAME)
# 載入最新的配置文件,停止原有進(jìn)程并按新的配置啟動(dòng)所有進(jìn)程
run('supervisorctl reload')
# 執(zhí)行 restart all,start 或者 stop fabric 都會(huì)提示錯(cuò)誤,然后中止運(yùn)行
# 但是服務(wù)器上查看日志,supervisor 有重啟
# run('supervisorctl restart all')
執(zhí)行 pack 任務(wù)
fab pack
執(zhí)行 deploy 任務(wù)
fab deploy
再給大家分享一個(gè)使用Fabric進(jìn)行代碼的自動(dòng)化部署
#coding=utf-8
from fabric.api import local, abort, settings, env, cd, run
from fabric.colors import *
from fabric.contrib.console import confirm
env.hosts = ["root@115.28.×××××"]
env.password = "×××××"
def get_git_status():
git_status_result = local("git status", capture=True)
if "無(wú)文件要提交,干凈的工作區(qū)" not in git_status_result:
print red("****當(dāng)前分支還有文件沒(méi)有提交")
print git_status_result
abort("****已經(jīng)終止")
def local_unit_test():
with settings(warn_only=True):
test_result = local("python manage.py test")
if test_result.failed:
print test_result
if not confirm(red("****單元測(cè)試失敗,是否繼續(xù)?")):
abort("****已經(jīng)終止")
def server_unit_test():
with settings(warn_only=True):
test_result = run("python manage.py test")
if test_result.failed:
print test_result
if not confirm(red("****單元測(cè)試失敗,是否繼續(xù)?")):
abort("****已經(jīng)終止")
def upload_code():
local("git push origin dev")
print green("****代碼上傳成功")
def deploy_at_server():
print green("****ssh到服務(wù)器進(jìn)行下列操作")
with cd("/var/www/××××××"):
#print run("pwd")
print green("****將在遠(yuǎn)程倉(cāng)庫(kù)下載代碼")
run("git checkout dev")
get_git_status()
run("git pull origin dev")
print green("****將在服務(wù)器上運(yùn)行單元測(cè)試")
server_unit_test()
run("service apache2 restart", pty=False)
print green("****重啟apache2成功")
print green("********代碼部署成功********")
def deploy():
get_git_status()
local("git checkout dev", capture=False)
print green("****切換到dev分支")
get_git_status()
print green("****將開(kāi)始運(yùn)行單元測(cè)試")
local_unit_test()
print green("****單元測(cè)試完成,開(kāi)始上傳代碼")
upload_code()
deploy_at_server()
fabric可以將自動(dòng)化部署或者多機(jī)操作的命令固化到一個(gè)腳本里,從而減少手動(dòng)的操作。上面是今天第一次接觸這東西后寫的,確實(shí)很實(shí)用。運(yùn)行fab deploy就行了。
主要邏輯就是將本地的dev分支跑單元測(cè)試,然后提交到服務(wù)器,ssh登陸到服務(wù)器,然后pull下來(lái),再跑單元測(cè)試,然后重啟apache2。第一次寫,可能比較簡(jiǎn)單,將持續(xù)改進(jìn)。
相關(guān)文章
在keras中實(shí)現(xiàn)查看其訓(xùn)練loss值
這篇文章主要介紹了在keras中實(shí)現(xiàn)查看其訓(xùn)練loss值,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06
Python中類的創(chuàng)建和實(shí)例化操作示例
這篇文章主要介紹了Python中類的創(chuàng)建和實(shí)例化操作,涉及Python面向?qū)ο蟪绦蛟O(shè)計(jì)中類的定義、實(shí)例化、方法調(diào)用等相關(guān)操作技巧,需要的朋友可以參考下2019-02-02
Python獲取運(yùn)行目錄與當(dāng)前腳本目錄的方法
這篇文章主要介紹了Python獲取運(yùn)行目錄與當(dāng)前腳本目錄的方法,涉及Python目錄操作與系統(tǒng)相關(guān)變量的獲取技巧,需要的朋友可以參考下2015-06-06
在Python3 numpy中mean和average的區(qū)別詳解
今天小編就為大家分享一篇在Python3 numpy中mean和average的區(qū)別詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-08-08
Python標(biāo)準(zhǔn)庫(kù):內(nèi)置函數(shù)max(iterable, *[, key, default])說(shuō)明
這篇文章主要介紹了Python標(biāo)準(zhǔn)庫(kù):內(nèi)置函數(shù)max(iterable, *[, key, default])說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-04-04
Python Numpy庫(kù)datetime類型的處理詳解
這篇文章主要介紹了Python Numpy庫(kù)datetime類型的處理詳解,Python中自帶的處理時(shí)間的模塊就有time 、datetime、calendar,另外還有擴(kuò)展的第三方庫(kù),如dateutil等等。。當(dāng)我們用NumPy庫(kù)做數(shù)據(jù)分析時(shí),如何轉(zhuǎn)換時(shí)間呢?需要的朋友可以參考下2019-07-07
Python:合并兩個(gè)numpy矩陣的實(shí)現(xiàn)
今天小編就為大家分享一篇Python:合并兩個(gè)numpy矩陣的實(shí)現(xiàn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-12-12

