Python Automation and Deployment project tool fabric Use instance _python

Source: Internet
Author: User
Tags pack ssh

Fabric is a good tool for automating a peacekeeping deployment project that is developed using Python to automate interactions with remote servers via SSH, such as uploading local files to the server and executing shell commands on the server.

An example of automating the deployment of Django projects is given below

#-*-coding:utf-8-*-# file name to be saved as fabfile.py from __future__ import unicode_literals from fabric.api import * # login user and Host Name: Env.user = ' root ' # If there is no setting, when you need to log in, the fabric prompts for env.password = ' Youpassword ' # If there are multiple hosts, fabric will be automatically deployed env.hosts = [' www . example.com '] tar_file_name = ' deploy.tar.gz ' def Pack (): "" Define a pack task, make a TAR packet: 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] Loca L (' rm-f%s '% tar_file_name) local (' tar-czvf%s%s '% (Tar_file_name, '. Join (Exclude_files), '. Join (Tar_files)  )) print (' Create a packed file in the current directory:%s '% Tar_file_name ') def deploy (): "" Define a Deployment task: return: "" # First Pack pack () # Remote server temporary file Remote_tmp_tar = '/tmp/%s '% tar_file_name run (' rm-f%s '% remote_tmp_tar) # Upload tar file to remote server, local_pAth, Remote_path put (Tar_file_name, Remote_tmp_tar) # Extract remote_dist_base_dir = '/home/python/django_app ' # if not present, The Create folder run (' mkdir-p%s '% remote_dist_dir) # cd command switches the working directory of the remote host to the specified directory with CD (REMOTE_DIST_DIR): Print (' Extract files to directory :%s '% remote_dist_dir) run (' tar-xzvf%s '% remote_tmp_tar) print (' dependency pack in Installation Requirements.txt ') # I'm using Pytho N3 to develop run (' PIP3 install-r requirements.txt ') remote_settings_file = '%s/django_app/settings.py '% Remote_dist_di  R settings_file = ' deploy/settings.py '% name print (' Upload settings.py file%s '% settings_file) put (settings_file, Remote_settings_file) Nginx_file = ' deploy/django_app.conf ' remote_nginx_file = '/etc/nginx/conf.d/django_app.co NF ' Print (' Upload nginx config file%s '% nginx_file) put (Nginx_file, Remote_nginx_file) # Deploy in subdirectories of the current directory supervisor Config file upload to server Supervisor_file = ' Deploy/django_app.ini ' remote_supervisor_file = '/etc/supervisord.d/django_app.ini ' PR Int (' Upload Supervisor config file%s '% supervisor_file) put (Supervisor_file, remote_supervisor_file) # Reload Nginx profile run (' nginx-s reload ') run (' nginx-t ') # Delete local packaged files locally (' rm-f%s '% tar_file_name) # Load the latest configuration file, stop the original process and start all process run with the new configuration (' Supervisorctl Reloa d ') # Executing restart All,start or stop fabric prompts for an error, then aborts # but the log is on the server, Supervisor has reboot # run (' Supervisorctl restart all

 ')

Perform a pack task

fab pack

Perform deploy tasks

fab deploy

To share an automated deployment of code with 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 = ["root@115.28.xxxxx"] Env.password = "XXXXX" Def get_git_status (): Git_status_res
    ult = local ("Git status", capture=true) if "No file to submit, clean workspace" Not in Git_status_result:print red ("* * * Current Branch and File not submitted")  Print Git_status_result Abort ("* * * terminated") 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 ("* * * unit Test failed, Do you want to continue? ): Abort ("* * * terminated") def server_unit_test (): With settings (warn_only=true): Test_result = run ("Python ma nage.py test ") if Test_result.failed:print test_result if not confirm red (" * * * unit test failed, continue? ") ): Abort ("* * * terminated") def Upload_code (): local ("Git push Origin dev") Print green ("* * * * Upload Success") def Deplo Y_at_server (): Print Green ("* **ssh to the server for the following actions ") with CD ("/var/www/xxxxxx "): #print run (" pwd ") Print green (" * * * * will download code in remote Warehouse ") Run (" Git Checko
    UT dev ") get_git_status () run (" Git pull Origin dev ") Print green (" * * * will run unit tests on the server ") Server_unit_test ()


Run ("Service apache2 restart", pty=false) Print Green ("* * * reboot apache2 successful") Print green ("******** Code Deployment successful ********") def deploy (): Get_git_status () local ("Git Checkout dev", capture=false) Print Green ("* * * Switch to Dev branch") Get_git_statu S () Print green ("* * * will start to run unit tests") local_unit_test () Print Green ("* * * unit Test complete, start uploading code") Upload_code () Deploy_at_serv

 ER ()

Fabric can solidify commands for automated deployments or multiple-machine operations into a single script, reducing manual operations. It was written after the first contact with this thing today, and it was really practical. Run fab deploy on the line.

The main logic is the local dev Branch run unit test, and then submit to the server, SSH login to the server, and then pull down, then run unit test, and then restart Apache2. The first time writing, may be simpler, will continue to improve.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.