Python automated O & M and Deployment Project tool Fabric use instance

Source: Internet
Author: User
Tags ssh access
Fabric is a Python library. as long as the target machine supports ssh access, fabric can be used for remote operations (such as running shell commands on host2 on host1). Obviously, because fabric is a Pythonpackage, other Pythonpackage can be imported to fabric-specific fabfile. in the py script, Fabric is a Python library. as long as the target machine supports ssh access, fabric can be used for remote operations (such as remotely running shell commands on host2 on host1). Obviously, since fabric is a Python package, other Python packages can be imported to fabric-specific fabfile. in the py script

Fabric is a good tool for automated O & M and deployment projects developed using Python. it can automate interaction with remote servers through SSH, such as uploading local files to servers, execute shell commands on the server.

The following is an example of automatic deployment of Django projects.

#-*-Coding: UTF-8-*-# the file name must be saved as fabfile. pyfrom _ future _ import unicode_literalsfrom fabric. api import * # login user and host name: env. user = 'root' # if not set, fabric will prompt you to enter env when you need to log on. password = 'youpassword' # if multiple hosts exist, fabric will automatically deploy env in sequence. hosts = ['www .example.com '] TAR_FILE_NAME = 'deploy.tar.gz' def pack (): "defines a pack task and makes a tar package: return: "tar_files = ['*. py ', 'static/*', 'Templates/* ', 'Vue _ app /','*/*. py ', 'requirements.txt'] exclude_files = ['fabfile. py ', 'ploy/*', '* .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' % (TAR_FILE_NAME ,''. join (exclude_files ),''. join (tar_files) print ('create a package file in the current directory: % s' % TAR_FILE_NAME) def deploy (): "defines a deployment task: return: "# pack () # remote_tmp_tar = '/tmp/% s' % TAR_FILE_NAME run ('rm-f % s' % remote_tmp_tar) # upload the tar file to the remote server, local_path, remote_path put (TAR_FILE_NAME, remote_tmp_tar) # decompress remote_dist_base_dir = '/home/python/django_app' # if it does not exist, run ('mkdir-p % s' % remote_dist_dir) # run the cd command to switch the working directory of the remote host to the specified directory with cd (remote_dist_dir ): print ('extract the file to the directory: % s' % remote_dist_dir) run ('Tar-xzvf % s' % remote_tmp_tar) print ('Install the dependency package in requirements.txt ') # I am using python3 to develop run ('pip3 install-r requirements.txt ') remote_settings_file =' % s/django_app/settings. py '% remote_dist_dir settings_file = 'ploy/settings. PY' % name print ('upload settings. py file % s' % settings_file) put (settings_file, remote_settings_file) nginx_file = 'ploy/django_app.conf 'remote_nginx_file ='/etc/nginx/conf. d/django_app.conf 'print ('upload nginx configuration file % s' % nginx_file) put (nginx_file, remote_nginx_file) # upload the supervisor configuration file in the deploy subdirectory of the current directory to the server supervisor_file = 'ploy/django_app.ini 'remote_supervisor_file ='/etc/supervisord. d/django_app.ini 'print ('upload the supervisor configuration file % s' % supervisor_file) put (supervisor_file, remote_supervisor_file) # reload the nginx configuration file run ('nginx-s reload ') run ('nginx-t') # Delete the local packaging file local ('rm-f % s' % TAR_FILE_NAME) # load the latest configuration file, stop the original process and start all processes run ('supervisorctl reload') according to the new configuration # An error will be prompted when executing restart all, start or stop fabric, then stop running # but check the log on the server. the supervisor has restarted # run ('supervisorctl restart all ')

Execute a pack task

fab pack

Execute a deploy task

fab deploy

I will share with you an automated deployment of code using Fabric.

# Coding = utf-8from fabric. api import local, abort, settings, env, cd, runfrom fabric. colors import * from fabric. contrib. console import confirmenv. hosts = ["root@115.28. * "] env. password = "×××××" def get_git_status (): git_status_result = local ("git status", capture = True) if "no file to submit, clean workspace "not in git_status_result: print red (" ***** the current branch still has Files not submitted ") print git_status_result abort (" ***** terminated ") def local_uni T_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, continue? "): Abort (" ***** terminated ") 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 (" *** unit test failed, continue? "): Abort (" ***** terminated ") def upload_code (): local (" git push origin dev ") print green ("***** code uploaded successfully") def deploy_at_server (): print green ("***** ssh to the server to perform the following operations ") with cd ("/var/www/××××××"): # print run ("pwd ") print green ("**** code will be downloaded from the remote repository") run ("git checkout dev") get_git_status () run ("git pull origin dev ") print green ("**** will run the unit test on the server") server_unit_test () run ("service apache2 restart", pty = False) print green ("***** restart apache2 succeeded") print green ("********** code deployment successful ********") def deploy (): get_git_status () local ("git checkout dev", capture = False) print green ("*** switch to dev branch") get_git_status () print green ("**** the unit test will start to run") local_unit_test () print green ("***** the unit test is complete, start uploading code") upload_code () deploy_at_server ()

Fabric can consolidate commands for automated deployment or multi-host operations into a script to reduce manual operations. The above was written after I first touched this thing today. it is indeed very practical. Runfab deployThat's all.

The main logic is to run the unit test on the local dev branch, submit it to the server, log on to the server via ssh, run the pull command, run the unit test, and restart apache2. The first write may be relatively simple and will be continuously improved.


For more articles about the use of Fabric, a Python automated O & M and Deployment Project tool, refer to PHP!


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.