Home  >  Article  >  Backend Development  >  How to use the operation and maintenance manager Fabric

How to use the operation and maintenance manager Fabric

高洛峰
高洛峰Original
2017-01-16 17:47:341202browse

Fabric installation

Fabric supports pip, easy_install or source code installation, which is very convenient to solve package dependency problems. (According to the user environment, you can choose pip or ease_install)
pip install fabric
easy_install fabric

The source code installation will not be introduced.
Verify the installation result. If no exception is prompted when importing the module, the installation is successful:

root@Python_S6:~# python
Python 2.7.5+ (default, Sep 19 2013, 13: 48:49)
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import fabric
>>>

The official website provides a simple getting started example:

root@Python_S6:/home/chart7/test/fabric# cat farbic.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from fabric.api import run
  
def host_type(): #定义一个任务函数,通过run方法实现远程执行'uname -s'命令
  run('uname -s')

If the running result is as shown in the figure below

How to use the operation and maintenance manager Fabric

The default file name referenced by the command is fabfile.py. If a non-default file name is used, it needs to be specified by '-f', such as: fab -H 192.168.1.23,192.168.1.24 -f host_type .py host_type, if the management machine and the target host are not configured with key authentication trust, you will be prompted to enter the login password of the corresponding account of the target host.

1. Commonly used parameters of fab

As the command entrance of the Fabric program, fab provides a wealth of parameter calls. The command format is as follows:
fab [options] [: arg1,arg2=val2,host=foo,hosts='h1;h2',....]
The following lists several commonly used parameters, and you can use fab -help to view more parameters.
-l , display the defined task function name;
-f, specify the fab entry file, the default entry file name is fabfile.py;
-g, specify the gateway device, such as the bastion host environment, just fill in the bastion host IP ;
-H, specify the target host, multiple hosts are separated by ',';
-P, run multiple host tasks in asynchronous parallel mode, the default is serial operation;
-R, specify role (role), use role names to distinguish devices of different business groups;
-t, set the device connection timeout;
-T, set the remote host command execution timeout;
-w, when the command execution fails , issue a warning instead of terminating the task by default

2. Writing fabfile

The fab command is used in conjunction with the fabfile.py we wrote (other file names must be referenced by adding -f filename) , some command line parameters can be replaced by corresponding methods to make them more flexible, such as "-H 192.168.1.23,192.168.1.24". We can achieve this by defining env.hosts, such as "env.hosts=[192.168 .1.23,192.168.1.24]"The main body of .fabfile is composed of multiple customized task functions. Different task functions implement different operation logic. The following is a detailed introduction

3. Global attribute settings

The env object is used to define the global settings of the fabfile and supports multiple attributes, including target host, user, and password role. The description of each attribute is as follows:

env.host,定义目标主机,可以用IP或主机名表示,以Python的列表形式定义,如env.hosts=['192.168.1.23,192.168.1.24'].
env.exculde_hosts,排除指定主机,如env.exclude_hosts=['192.168.1.23']
env.user,定义用户名,如env.user="root"
env.port,定义目标主机端口,如env.port = '22'
env.password,定义密码,如env.password='123456'
env.passwords,与password功能一样,区别在于不同主机不同密码的应用场景,需要注意的是,配置passwords时需要配置用户,主机,端口等信息,如:env.passwords = {'root@192.168.1.21:22':'123456',
'root@192.168.1.23:22':'3234234',
'root@192.168.1.24:23':'09887',
}
env.gateway,定义网关(中转,堡垒机)IP,如env.gateway = '192.168.1.1'
env.roledefs,定义角色分组,比如web组与db组主机区分开来,定义如下:
env.roledefs = {
'webservers':['192.168.1.21','192.168.1.22','192.168.1.23'],
'dbservers':['192.168.1.24','192.168.1.25'],
}

Use the python modifier when referencing. The task function under the role modifier has its scope. Let's look at an example:

@roles('webservers')
def webtask():
  run('/etc/init.d/nginx start')
@roles('dbservers'):
def dbtask():
  run('/etc/init.d/mysql start')
@roles('webservers','dbservers')
def publictask():
  run('uptime')
def deploy():
  execute(webtask)
  execute(dbtask)
  execute(publictask)

By executing fab deploy in the command, different roles can execute different task functions.

Commonly used API

Fabric provides a set of simple but powerful fabric.api command sets. Simply calling this API can complete most application scenario requirements. Fabric supports common methods and The description is as follows:

local,执行本地命令,如local:('uname -s');
lcd,切换本地目录,如lcd:('/home');
cd,切换远程目录,如cd:('/data/logs/');
run,执行远程命令,如:run('free -m')
sudo,sudo方式执行远程命令,如:sudo('/etc/init.d/httpd start');
put,上传本地文件到远程主机,如:put('/home/user.info','/data/user.info');
get,从远程主机下载文件到本地,如:get('/home/user.info','/data/user.info');
prompt,获得用户输入信息,如:prompt('please input user password:');
confirm,获得提示信息确认,如:confirm('Test failed,Continue[Y/N]');
reboot,重启远程主机,如reboot();
@task,函数修饰符,标识符的函数为fab可调用,非标记对fab不可见,纯业务逻辑;
@runs_once,函数修饰符,标识符的函数只会执行一次,不受多台主机影响;

Example 1: View local and remote host information
This example calls the local() method to execute local commands, and adds the "@runs_once" modification to ensure that the task function is only executed once. Call the run() method to execute remote commands.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from fabric.api import *
env.user = 'root'
env.hosts = ['192.168.1.43','192.168.1.23','192.168.1.24']
env.port = '22'
env.password = '123456'
  
@runs_once #查看本地系统信息,当有多台主机时只运行一次
def local_task(): #本地任务函数
  local('uname -a')
  
def remote_task():
  with cd('/data'): #with的作用是让后面的表达式语句继承当前状态,实现cd /var && ls -l的效果
    run('ls -l')

Call the local_task task function through the fab command respectively. The running effect is as shown in the figure below

How to use the operation and maintenance manager Fabric

The results show [192.168.1.23] Executing task 'local_task', but in fact the task is not executed on the host 192.168.1.23, but the execution effect of 'uname -a' local to the Fabric host is returned.

The execution result of calling the remtoe_task task function is shown in the figure below

How to use the operation and maintenance manager Fabric

Example 2; dynamically obtain the remote directory list
This example uses the "@task" modifier to mark the entry function go () can be used externally, with the "@runs_once" symbol to wait for user input, and finally call the worktask() task function to implement remote command execution.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from fabric.api import *
env.user = 'root'
env.hosts = ['192.168.1.23','192.168.1.24']
env.password = '123456'
@runs_once #在主机遍历过程中,只有一台出发此函数
def input_raw():
  return prompt("please input direcotry name:",default="/home")
  
  
def worktask(dirname):
  run("ls -l %s" %dirname)
  
@task
def go():
  getdirname = input_raw()
  worktask(getdirname)

This example implements a dynamic input remote Directory name, in the function of obtaining the directory list, since we only require input once, and then display the list information of the directory on all hosts, a sub-function input_raw (configured at the same time) @runs_once modifier is called to achieve this purpose. The execution results are as follows Figure

How to use the operation and maintenance manager Fabric

File upload and execution

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from fabric.api import *
from fabric.context_managers import *
from fabric.contrib.console import confirm
env.hosts=['192.168.1.23','192.168.1.24']
#假如所有主机密码都不一样,可以通过env.passwords字典变量一一指定
env.passwords = {
  'root@192.168.1.23:22': '123456',
  'root@192.168.1.24:22': '123456',
}
  
lpackpath="/home/a.tar.gz"
rpackpath="/tmp/install"
  
@task
def put_task():
  run("mkdir -p /tmp/install")
  with settings(warn_only=True):
    result = put(lpackpath, rpackpath)
  if result.failed and not confirm("put file failed, Continue[Y/N]?"):
    abort("Aborting file put task!")
  
@task
def run_task():
  with cd("/tmp/install"):
    run("tar -zxvf a.tar.gz")
  
@task
def go():
  put_task()
  run_task()

For more articles related to how to use the operation and maintenance manager Fabric, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn