Use Fabric for automated code deployment
Use Fabric for automated code deployment
# 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. ××××"]
Env. password = "×××××"
Def get_git_status ():
Git_status_result = local ("git status", capture = True)
If "no file is to be submitted, 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_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, 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 ("*** perform the following operations on the server through ssh ")
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 ("**** the unit test will be run on the server ")
Server_unit_test ()
Run ("service apache2 restart", pty = False)
Print green ("***** apache2 restarted successfully ")
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 running ")
Local_unit_test ()
Print green ("*** the unit test is completed and the code starts to be uploaded ")
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. Run fab deploy.
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.
Use Vagrant and Fabric for Integration Testing
Fabric: Python Remote Deployment Tool
This article permanently updates the link address: