English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python 자동화 운영 및 배포 프로젝트 도구 Fabric 사용 예제

Fabric은 Python을 사용하여 개발된 자동화 운영 유지 및 배포 프로젝트의 좋은 도구로, SSH 방식으로 원격 서버와 자동으로 상호작용할 수 있습니다. 예를 들어, 로컬 파일을 서버에 전송하거나 서버에서 shell 명령어를 실행할 수 있습니다.

아래는 Django 프로젝트의 자동화 배포 예제를 제공합니다

# -*- coding: utf-8 -*-
# 파일 이름을 fabfile.py로 저장해야 합니다
from __future__ import unicode_literals
from fabric.api import *
# 로그인 사용자와 호스트 이름:
env.user = 'root'
# 설정되지 않으면, 로그인이 필요할 때 fabric이 입력을 요청합니다
env.password = 'youpassword'
# 여러 개의 호스트가 있으면, fabric이 차례대로 배포를 자동으로 수행합니다
env.hosts = ['www.example.com']
TAR_FILE_NAME = 'deploy.tar.gz'
def pack():
  """
  pack 작업 정의, 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('현재 디렉토리에 패키지 파일을 생성합니다: %s' % TAR_FILE_NAME)
def deploy():
  """
  하나의 배포 작업 정의
  :return:
  """
  # 先进行打包
  pack()
  # 远程服务器的临时文件
  remote_tmp_tar = '"/tmp/%s' % TAR_FILE_NAME
  run('rm -f %s' % remote_tmp_tar)
  # 上传tar文件至远程服务器, local_path, remote_path
  put(TAR_FILE_NAME, remote_tmp_tar)
  # 解压
  remote_dist_base_dir = '"/홈/python/django_app'
  #如果不存在, 则创建文件夹
  run('mkdir -p %s' % remote_dist_dir)
 # cd 命令将远程主机的工作目录切换到指定目录 
  with cd(remote_dist_dir):
    print('解压文件到到目录: %s' % remote_dist_dir)
    run('tar -xzvf %s' % remote_tmp_tar)
    print('安装 requirements.txt 中的依赖包')
    #我使用的是 python3 来开发
    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)
 #在当前目录的子目录 deploy 中的 supervisor 配置文件上传至服务器
  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)
  # 가장 최신의 설정 파일을 로드하고 기존 프로세스를 중지하고 새로운 설정에 따라 모든 프로세스를 시작
  run('supervisorctl reload')
  # restart all, start 또는 stop fabric을 실행하면 오류가 발생하고 실행이 중지됩니다
  # 하지만 서버에서 로그를 확인하면 supervisor가 재시작되었습니다
  # run('supervisorctl restart all')

pack 작업 실행

fab pack

deploy 작업 실행

fab deploy

Fabric을 사용하여 코드 자동 배포 방법을 또 한 번 공유해 드립니다

#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 = ["[email protected].×××××"]
env.password = "×××××"
def get_git_status():
  git_status_result = local("git status", capture=True)
  if "무 파일을 커밋할 것이 없음, 깨끗한 작업 공간" not in git_status_result:
    print red("****현재 브랜치에는 커밋되지 않은 파일이 있습니다)
    print git_status_result
    abort("****이미 종료됨)
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("****단위 테스트 실패, 계속하시겠습니까?")):
        abort("****이미 종료됨)
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("****단위 테스트 실패, 계속하시겠습니까?")):
        abort("****이미 종료됨)
def upload_code():
  local("git push origin dev")
  print green("****코드 업로드 성공))
def deploy_at_server():
  print green("****서버로 ssh 접속하여 다음 작업을 수행합니다)
  with cd("/var/www/××××××"):
    #print run("pwd")
    print green("****원격 저장소에서 코드를 다운로드합니다)
    run("git checkout dev")
    get_git_status()
    run("git pull origin dev")
    print green("****서버에서 단위 테스트를 실행합니다)
    server_unit_test()
    run("service apache2 restart", pty=False)
    print green("****apache 재시작2성공
    print green("********코드 배포 성공********)
def deploy():
  get_git_status()
  local("git checkout dev", capture=False)
  print green("****dev 분기로 전환합니다)
  get_git_status()
  print green("****단위 테스트를 시작합니다)
  local_unit_test()
  print green("****단위 테스트가 완료되면, 코드를 업로드하기 시작합니다)
  upload_code()
  deploy_at_server()

fabric은 자동화된 배포나 다중 서버 작업 명령을 스크립트에 고정하여 수동적인 작업을 줄일 수 있습니다. 이것에 대한 첫 번째 접촉 후에 썼으며, 매우 실용적입니다. fab deploy을 실행하면 됩니다.

주요 로직은 로컬의 dev 분기에서 단위 테스트를 실행하고 서버에 제출한 후, ssh로 서버에 로그인하여 pull을 수행하고, 다시 단위 테스트를 실행한 후 apache를 재시작하는 것입니다.2첫 번째 작성인 만큼 간단할 수 있지만, 지속적으로 개선될 것입니다。

선언: 이 문서의 내용은 인터넷에서 가져왔으며, 저작권은 원 저자에게 있으며, 인터넷 사용자가 자발적으로 기여하고 업로드한 내용입니다. 이 사이트는 소유권을 가지지 않으며, 인공적인 편집을 하지 않았으며, 관련 법적 책임도 부담하지 않습니다. 저작권 침해가 의심되는 내용이 있으면, notice#w로 이메일을 보내 주세요.3codebox.com(보내는 이메일에서 #을 @으로 변경하시고, 관련 증거를 제공하시면, 사실이 확인되면, 이 사이트는 즉시 저작권 침해 내용을 삭제합니다。)

아마도 좋아할 것