1. 程式人生 > 其它 >通過Jenkins實現伺服器端自動化部署 CI/CD

通過Jenkins實現伺服器端自動化部署 CI/CD

在應用伺服器上面實現自動拉取最新版本程式碼

# coding=utf-8
from locale import locale_alias
import os
import requests
import wget
import hashlib
import tarfile

def isnew(jen_live_ver,  local_live_ver):
    #如果有新版本,返回ture,否則返回false
    if not os.path.exists(local_live_ver):
        return True
    with open (local_live_ver, 'r') as f:
        a = f.read()
    r = requests.get(jen_live_ver)
    if r.text != a:
        return True
        
def isok(md5url, local_file_name):
    #如果檔案完整返回true
        #md5url通過requests讀出url的md5值,local_file_md5通過python MD5模組計算MD5值,在進行比較
    r = requests.get(md5url)
    r = r.text
    with open(local_file_name, 'rb') as f:
        m = hashlib.md5()
        m.update(f.read())
    if m.hexdigest() == r.strip():
        return True
   
def depoly(local_file_name, depoly_dir, link_dir):
    #把local_file_name解壓縮到depoly_dir,解壓後文件夾連線到link_dir
    tar = tarfile.open(local_file_name)
    tar.extractall(depoly_dir)
    depoly_link_dir = depoly_dir + '/webnew-%s' % r.text 
    if os.path.exists(link_dir):
        os.remove(link_dir)
        os.symlink(depoly_link_dir, link_dir)
    else:
        os.symlink(depoly_link_dir, link_dir)


if __name__ == '__main__':
    #判斷伺服器上是否有新版本
    jen_live_ver = 'http://192.168.1.203/dev/live_ver'
    local_ver_dir = '/var/www/html'
    local_live_ver = '/var/www/html/live_ver'
    if not isnew(jen_live_ver,  local_live_ver):
        print('沒有發現新版本')
        exit(1)
    
    #如果有新版本,下載新版本
    r = requests.get(jen_live_ver)
    download_dir = '/var/www/download'
    app_url = 'http://192.168.1.203/dev/pkgs/webnew-%s.tar.gz' % r.text
    wget.download(app_url, download_dir)

    #下載完成後進行檔案完整性校驗,如果檔案損壞,刪除檔案
    md5url = app_url + '.md5'
    local_file_name = download_dir + '/webnew-%s.tar.gz' % r.text
    # local_file_name = local_file_name.encode('utf-8')
    # print('222222?22222222', a)
    if not isok(md5url, local_file_name):
        print('檔案已損壞')        
        os.remove(local_file_name)
        exit(2)
    #部署軟體
    #1.解壓 壓縮包==》/var/www/depoly
    #2.進行軟連線
    depoly_dir = '/var/www/depoly'
    link_dir = '/var/www/html/new'
    depoly(local_file_name, depoly_dir, link_dir)

    #更新本地版本號
    #1.刪除本地live_ver檔案,再重新下載live_ver檔案
    if os.path.exists(local_live_ver):
        print('3333333333')
        os.remove(local_live_ver)
        wget.download(jen_live_ver, local_ver_dir)
    else:
        wget.download(jen_live_ver, local_ver_dir)