fabric Usage Tutorial of python's Three Magic Artifacts

  • 2021-06-28 09:31:54
  • OfStack

fabric is an python package and an ssh-based deployment Toolkit

Usually used for batch deployment of web microservices, etc. For example, I have 5 online servers that can be distributed from one to five to achieve the purpose of automatic deployment.

A brief introduction to common fabric commands

Common Commands


lcd(dir):  Enter a local directory 
local(cmd):  Execute commands locally 
cd(dir):  Enter a directory on the server 
run(cmd): Execute commands on the server 

Fabric

Fabric is an python library for remote execution of shell and is also a command line tool.It provides a rich interface to interact with SSH and can be used to automate and streamline the execution of Shell commands on local or remote machines.

Install Fabric

Fabric's official website is www.fabfile.org, and the source code is hosted on Github.You can source clone locally and install it with the following command.However, before source installation, you must first install Fabric's dependency package Paramiko.

python setup.py develop

It can also be installed using pip, since fabric is a third-party library of python, with only one command:

 pip install fabric

python3 was installed using fabric3: (You need to uninstall fabric before installing fabric3.)

# fabric3 Support for python3 pip uninstall fabric pip3 install fabric3

fabric is not just an Python module, fabric is also a command line tool, you can use fab-h to view help information


E:\my_data\hk-project>fab -V
Fabric3 1.14.post1
Paramiko 2.4.2
E:\my_data\hk-project>fab -h

Getting Started

fabric is used by writing an python file that contains multiple functions and then calling them with the fab command to do the appropriate tasks.These functions are called task in fabric.


# filename : abc.py​
 from fabric.api import *​
 def task1():
   print("hello")
 def hello():
   print("hello world")

Once you have written this python file, execute the functions in the file using the fab tool in the path of the current directory


[root@localhost python The directory where the file is located ]# fab -f abc.py hello
 hello world
 ​# -f  Appoint fabfile File, default is fabfile.py If the file name is in the current directory fabfile.py No need to specify 

Task parameters

At this point you might think, what if this function has parameters?How should parameters be passed to the function?Fabric supports Shell-compatible parameter usage: < Task Name > : < parameter > , < Keyword parameter name > = < parameter values > ,... that's how it works.


 def hello(name="world"):
   print("hello {}".format(name))

We can specify parameters like this


$ fab hello:name=Jeff  #  perhaps  fab hello:Jeff
 hello Jeff
 ​Done.

Calf knife

Now let's assume we need to write an fabfile.py to submit and run the latest code using git after each web project code update. The description of the requirements is clear. Let's go!


# fabfile.py
 #  It is recommended that this file be placed in the root directory of the project file for convenience. git Submit 
 from fabric.api import local
 def test():
   local('python manage.py test myapp')
   #  Test if it works 
 def commit():
   local('git add -p && git commit -m "for test"')
 def push():
   local('git push')
 def prepare_deploy():
   test()
   commit()
   push()

This prepare_The deploy task can be invoked individually or in finer-grained subtasks.

fault

Fabric checks the return values of the called programs, and Fabric terminates the operation if the programs do not exit cleanly.We did nothing, Fabric detected an error and terminated, and will not continue with the commit task.

We can also handle and judge the faults in a certain way


from fabric.api import local, settings, abort
 from fabric.contrib.console import confir
 def test():
   with settings(warn_only=True):
     result = local('./manage.py test my_app', capture=True) 
     # result.return_code Return code (0/1) and result.failed
   if result.failed and not confirm("Tests failed. Continue anyway?"): # confirm Judging user input 
     abort("Aborting at user request.") #  Specify error exit information 
 # 1 Named  warn_only  Settings for   environment variable   , usually abbreviated as  env var  ) You can change exit to warning to provide more flexible error handling.If set to False Then 1 If a command fails to run, it will exit and no longer execute the following command. 

Set up a connection

Finally, it's time to connect. The main function of this tool is to execute commands remotely. With this knowledge, we can execute commands from remote servers locally.


from fabric.api import *
 env.hosts = ['root@192.168.10.11:22']​
 def deploy():
   run('ls') # run() Used to execute remote commands, local() Execute local commands 
 #  You will be prompted to enter the password after execution, just enter the password 

At the end of the introduction, there are more api explanations to follow. Please pay attention!

Reference link:

fabric Official Chinese Document: https://fabric-chs.readthedocs.io/zh_CN/chs/tutorial.html

summary


Related articles: