Home  >  Article  >  Backend Development  >  A simple guide to getting started with Python automated deployment tool Fabric

A simple guide to getting started with Python automated deployment tool Fabric

高洛峰
高洛峰Original
2017-01-16 17:43:161388browse

Fabric is a Python tool based on the SSH protocol. Compared with the traditional ssh/scp method, writing management commands in Python syntax is more readable and easier to expand. Managing a single or multiple machines is like local operation.

Official website address: http://fabfile.org

Installation
Omit the python and pip management tool installation process

pip install fabric

Verify whether the installation is successful
Enter python Edit mode, enter the code, if there is no error, it means successful installation

from fabric.api import local

fabric version hello world
fabric default file fabfile.py, of course, if you don’t want to use this name, you need to add the -f parameter

Create fabfile.py file

vim fabrile.py

Edit code

#coding:utf-8
from fabric.api import local#
def hello():
   # local函数用来执行本地命令
   local('echo "hello wolrd!"')

Execute code

fab hello

You can view executable tasks through fab -l, currently the hello function
is running Result

[localhost] local: echo "hello world!"
hello world!
Done.

Traditional maintenance method:

$ ssh x.x.x.x 'uname -a' -- 输出略

Fabric example:

$ cat fabfile.py
from fabric.api import run
def uname():
  run('uname -a')
$ fab -H x.x.x.x uname -- 输出略

Intuitively, it seems that a lot of code needs to be written than the ssh method, but based on the ssh method, it can be done in the middle There are relatively few control links. For example, if you want to determine whether a service has been started, if it has not been started, perform startup and other operations. The ssh imperative approach is a little more troublesome. (Of course, you can write a script on the machine being operated and call this script via ssh) Read

Encapsulates local and remote operations (do you still need to encapsulate system/popen/ssh operations yourself?)

Flexible parameters (dynamically specify host/role, etc., and concurrent execution based on multiprocessing)

Complete log output

As listed above, in fact, there are basically similar encapsulations in daily work, but there is a ready-made mature tool, why not use it? Right.

Commonly used configurations:

env.host                                                                                                                                                                                      Host IP, of course, you can also specify –      -H parameter

env                                                             Password

env.roledefs -- Role grouping, for example: {'web': ['x', 'y'], 'db': ['z']}

fab -l -- Display available tasks (commands)

fab -H -- Specify host, support multiple hosts separated by commas

fab -R -- Specify role, support multiple

fab -P                                                                                                                                                                   The default entry file is: fabfile/fabfile.py

For more information, please refer to: fab --help

Commonly used functions:

local('pwd')      — Local Command

LCD ('/TMP') -Switch Local Catalog

CD ('/TMP') -Switch remote directory

Run ('Uname -A -A ') - Execute the remote command

Sudo ('/ETC/Init.d/Nginx Start ') - Execute the remote SUDO, pay attention to the pty option

## Example 1: Manage remote nginx service

$ cat fabfile.py
from fabric.api import *
@task
def nginx_start():
  ''' nginx start '''
sudo('/etc/init.d/nginx start')
 
@task
def nginx_stop():
  ''' nginx stop '''
  sudo('/etc/init.d/nginx stop')
$ fab --list   -- 查看可用命令
Available commands:
 
  nginx_start nginx start
  nginx_stop  nginx stop
 
$ fab -H x.x.x.x nginx_start -- 启动 nginx

Example 2: Role-based

$ cat fabfile.py
from fabric.api import *
env.roledefs = {'nginx': ['x.x.x.x', 'y.y.y.y'], 'mysql': 'z.z.z.z'}
@task
def mysql_start()
  ''' mysql start '''
  sudo('/etc/init.d/mysql start')
$ fab --list   -- 查看可用命令
Available commands:
 
  nginx_start nginx start
  nginx_stop  nginx stop
  mysql_start mysql start
 
$ fab -R nginx nginx_start -- 启动 nginx
$ fab -R mysql mysql_start -- 启动 mysql

Example 3: Mixing local and remote operations

$ cat fabfile
def hello():
  ''' test hello '''
  with lcd('/tmp'): # 切换到 /tmp 目录下
    local('svn co http://xxx xxx') # check 代码到本地
    local('tar czf xxx.tar.gz xxx/') # 压缩本地包
    put('xxx.tar.gz', '/tmp') # 上传压缩包到远程 /tmp 目录下
  with cd('/tmp'):  # 切换到远程 /tmp 目录
    run('tar zxf xxx.tar.gz') # 远程解压

Does it all look like local? Right.

Example 4: Multiple target servers

Same password or manual input:

env.hosts = ['root@ip1:22',root@ip2:22]

##Different passwords or do not want to manually enter (this method can also be defined Do not role a group of servers):

#coding:utf-8
from fabric.api import local,cd,put,lcd,env,run,execute,roles
env.roledefs = {
 'role1':['root@ip1:22',],
 'role2':['root@ip2:22',]
}
env.passwords={
 'root@ip1:22':'pwd1',
 'root@ip2:22':'pwd2'
}
@roles('role1')
def role1():
 with cd('/tmp'):
   run('ls -l')
@roles('role2')
def role2():
 with cd('/tmp'):
   run('ls')
def task():
 execute(role1)
 execute(role2)

For more related articles on the simple getting started guide of Fabric, the Python automated deployment tool, 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
Previous article:python fabric usage notesNext article:python fabric usage notes