How can you automate your tasks with Fabric

  • 2020-05-17 05:41:34
  • OfStack

Let's start with an example. We know that under *NIX, uname The command is to view the distribution of the system.

You can write an Fabric script like this:


from fabric.api import run
def host_type():
 run('uname -s')

Save the above script as fabfile.py and you can pass it fab The command executes the host_type script on multiple hosts:


$ fab -H localhost,linuxbox host_type
[localhost] run: uname -s
[localhost] out: Darwin
[linuxbox] run: uname -s
[linuxbox] out: Linux

Execution may require you to enter the system password.

The installation

If you see this, you're starting to get interested in Fabric. However, the above operation cannot be performed in your place, because you have not installed Fabric. Installing Fabric is easy and works pip or easy_install , you can also download the original code to install.

Task function

Well, installing Fabric doesn't bother you. You may have successfully performed the previous task, but let's go a little further.

The task in Fabric is an python function, let's call it a "task function". Since it is the python function, some usage of the function also applies to the task function. Such as passing parameters, calling each other, returning values, and so on.

First look at an example of passing parameters:


def hello(name="world"):
 print("Hello %s!" % name)

In the execution of the task, can pass fab The command line parameter is passed to the task function:


$ fab hello:name=Holbrook
Hello Holbrook!

Examples of combining tasks are as follows:


from fabric.api import run
def host_type():
 run('uname -s')

def hello(name="world"):
 print("Hello %s!" % name)

def composite(name="world"):
 hello(name)
 host_type()

Commands provided by Fabric

We saw earlier in the fabric.api module run Function that executes commands on a remote host. The local function is also provided in fabric.api to execute local (host of Fabric) commands.

As follows:


from fabric.api import local
def lslocal():
 local('ls')

Like remote and local commands, Fabric also distinguishes between remote and local directories. Operations on remote and local directories provided by Fabric are cd and lcd, respectively. This is easy to understand if you've ever used the command line ftp.

Let's take a look at an example:


def filepath():
 remote_dir = '/opt/xxx'
 with cd(remote_dir):
  run("touch README")

The function of the above code is to go into the remote /opt/xxx directory and create an README file.

Fabric also provides a number of commands, such as file manipulation.

Manage server connections

In the previous examples, you need to specify server in the fab command-line argument. It can be cumbersome to manage a large number of servers. Fabric provides the dictionary env for environment variables, which contains the hosts dictionary entry, and defines the server to connect to.

As follows:


from fabric.api import env, run

env.hosts = ['host1', 'host2']
def mytask():
 run('ls /var/www')

You can also specify a separate list of host tasks to perform for each task:


from fabric.api import env, run

def set_hosts():
 env.hosts = ['host1', 'host2']

def mytask():
 run('ls /var/www')

This implementation fab set_hosts mytask When, it can be set_hosts The two specified in host perform mytask The task. If you're too lazy to write a function fab The command line also specifies the same:


fab mytask:hosts="host1;host2"

For easier batch tasks, Fabric also defines Role, which you can read in its official documentation.

Manage SSH passwords, users, and ports

Although SSH public key authentication is more recommended, Fabric provides a mechanism for managing passwords. Fabric provides two layers of passwords.

If your server has the same password, it can be used in env.password Set the default password; If the server password is different, it can still be used env.passwords Set (host,password) pairs for each server, and set a separate ssh password for each server.

The host string above is in this format: username @hostname :port. So, when you specify the ssh password, you also specify the ssh user. Same as password 1, you can also in env.user Specifies a default user. If none is specified, execute fab The command will prompt you for your password.

With Fabric, you can manage the SSH connections (hostname, user, password) to series 1 host, define the series 1 task functions, and then flexibly specify which tasks to perform on which host. This is especially useful in scenarios where you need to manage a large amount of host, such as operations, private cloud management, application automation, and so on.

conclusion

This article is just an introductory document, far less powerful than Fabric. In fact, Fabric includes a number of features, such as the definition of Role, remote interaction and exception handling, concurrent execution, file manipulation, and more, and is not limited to the command line. You can call Fabric in your application.

That's the end of this article, and I hope it will get you interested in Fabric and help you solve problems in your application. If you have any questions, please leave a message.


Related articles: