Python automated operations and deployment project tools Fabric usage Examples

Source: Internet
Author: User
Tags ssh access
Fabric is a Python library that can be remotely manipulated using fabric as long as the target machine supports SSH access (such as running shell commands on host2 remotely on host1), apparently because fabric is a python package, Therefore, other Python package can be import into the fabric-specific fabfile.py script

Fabric is a great tool for automating operational and deployment projects developed using Python, which enables automated interaction with remote servers via SSH, such as uploading local files to the server and executing shell commands on the server.

Here's an example of automating the deployment of a Django project

#-*-coding:utf-8-*-# file name to save as Fabfile.pyfrom __future__ import unicode_literalsfrom fabric.api import *# login user and host name: ENV.U ser = ' root ' # if not set, Fabric will prompt for Env.password = ' Youpassword ' If there is more than one host, fabric will automatically deploy env.hosts = ['  www.example.com ']tar_file_name = ' deploy.tar.gz ' def Pack (): "" Defines a pack task, hitting a TAR package: 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 '% (Tar_file_name, '. Join (Exclude_files), '. Join (tar_files))) Print (' Create a packaged file in the current directory:%s '% tar_file_name) def deploy (): "" "Defines a deployment task: return:" "# First Pack Pack () # Temporary files for the remote server Remo Te_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 (TA R_file_name, RemotE_tmp_tar) # Unzip remote_dist_base_dir = '/home/python/django_app ' # if not present, 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 (' Unzip file to directory:%s '% remote_dist_dir) run (' tar-xzvf%s '% re Mote_tmp_tar) print (' Install dependencies in Requirements.txt ') # I'm using Python3 to develop run (' PIP3 install-r requirements.txt ') r Emote_settings_file = '%s/django_app/settings.py '% remote_dist_dir settings_file = ' deploy/settings.py '% name Prin T (' Upload settings.py file%s '% settings_file) put (settings_file, remote_settings_file) nginx_file = ' deploy/django_app.c onf ' remote_nginx_file = '/etc/nginx/conf.d/django_app.conf ' Print (' Upload nginx config file%s '% nginx_file) put (nginx_fil E, Remote_nginx_file) # The Supervisor profile in the current directory's subdirectory deploy is uploaded to the server Supervisor_file = ' Deploy/django_app.ini ' Remote_supe  Rvisor_file = '/etc/supervisord.d/django_app.ini ' Print (' Upload Supervisor config file%s '% supervisor_file) put (Supervisor_file, Remote_supervisor_file) # Reload Nginx config file run (' nginx-s reload ') run (' nginx-t ') # Delete the local package file locally (' rm-f%s '% tar_file_name) # Load the latest configuration file, Stop the original process and start all processes in the new configuration run (' Supervisorctl reload ') # Execute restart All,start or stop fabric will prompt the error and abort the run # but view the log on the server, Supervi The Sor has reboot # run (' supervisorctl restart all ')

Performing a pack task

fab pack

Perform the Deploy task

fab deploy

And then we'll share an automated deployment using fabric for code.

#coding =utf-8from fabric.api Import Local, abort, settings, env, CD, RunFrom fabric.colors import *from Fabric.contrib.con Sole Import confirmenv.hosts = ["root@115.28.xxxxx"]env.password = "xxxxx" Def get_git_status (): Git_status_result = Loca L ("Git Status", capture=true) if "No file to submit, clean workspace" Not in Git_status_result:print red ("* * * Current Branch still has file not submitted") Print Git_ Status_result Abort ("* * * has been terminated") def local_unit_test (): With settings (warn_only=true): Test_result = local ("Python ma nage.py test ") if Test_result.failed:print Test_result if not confirm (red (" * * * unit Test failed, do you want to continue? "): Abort (" * * * has been terminated ") def server_unit_test (): With settings (warn_only=true): Test_result = run (" Python manage.p Y test ") if Test_result.failed:print Test_result if not confirm (red (" * * * * unit Test failed, do you want to continue? "): Abort (" * * * has been terminated ") def Upload_code (): local (" Git push Origin dev ") Print green (" * * * * code upload succeeded ") def Deploy_at_serv ER (): Print Green ("****ssh to Server do the following") with CD ("/var/www/xxxxxx"): #print run (" pwd ") Print green (" * * * will download code in Remote Repository ") run (" Git Checkout Dev ") Get_git_status () run (" Git pull Origin dev ") Print green (" * * * will run unit tests on the server ") server_unit_test (" Service apache2 restart ", Pty=false) prin T Green ("Restart Apache2 success") Print green ("******** code Deployment succeeded ********") def deploy (): Get_git_status () local ("Git Checkout de V ", Capture=false) Print green (" Switch to Dev Branch ") get_git_status () Print Green (" * * * will start running Unit tests ") Local_unit_test () print Green ("* * * unit test completed, start uploading code") Upload_code () Deploy_at_server ()

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

The main logic is to run the local Dev Branch unit test, and then submit to the server, SSH login to the server, then pull down, then run the unit test, and then restart Apache2. The first write, may be relatively simple, 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.