Operation Dimension Manager Fabric Use method _ server Other

Source: Internet
Author: User
Tags modifier modifiers python list

Installation of Fabric

Fabric support Pip,easy_install or source mode installation, it is very convenient to solve the problem of packet dependencies (according to the user environment, select PIP or Ease_install)
Pip Install Fabric
Easy_install Fabric

The source installation is not introduced.
Verify the installation results, if the import module does not indicate an exception, 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 the more information.
>>> Import Fabric
>>>

The official website offers a simple example of getting started:

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 (): #定义一个任务函数, implementing remote execution ' uname-s ' command
  run (' uname-s ') through the Run method

Run results if the following figure shows

The command refers to the default file name fabfile.py, and if you use a Non-default file name, you need to make it through '-f ', such as: Fab-h 192.168.1.23,192.168.1.24-f host_type.py Host_type, If the manager and the target host do not have the key authentication trust configured, you will be prompted to enter the target Host account login password.

I. Common parameters of FAB

Fab acts as a command entry for the fabric program, providing a rich parameter invocation, the command format is as follows:
Fab [options] <command>[:arg1,arg2=val2,host=foo,hosts= ' H1;H2 ',....]
Here are a few commonly used parameters that can be viewed with fab-help.
-L, showing the name of the defined task function;
-F, specify the Fab entry file, the default entry file name is fabfile.py;
-G, designated gateway equipment, such as fortress machine environment, complete the fortress machine IP;
-h, specify target host, multiple hosts with ', ' number separated;
-P to run multiple host tasks in asynchronous parallel mode, the default is serial running;
-R, specifying role (roles), distinguishing different business group devices with role names;
-T, set the device connection timeout;
-T, set the remote host command execution timeout;
-W, warnings are issued when command execution fails, not the default termination task

Ii. Preparation of Fabfile

Fab commands are combined with the fabfile.py we write (other file names must be added with the-f filename reference), and some command-line arguments can be replaced by the corresponding method to make them more flexible, as in the column "-H 192.168.1.23,192.168.1.24" , we can do this by defining env.hosts, such as "env.hosts=[192.168.1.23,192.168.1.24]". The main body of Fabfile consists of several custom task functions, different task functions implement different operation logic, the following details

Third, global attribute setting

The role of the Env object is to define the global setting of the Fabfile and support multiple attributes, including the target host, user, and password roles, which are described as follows:

Copy Code code as follows:

Env.host, which defines the target host, can be represented by an IP or host name, defined in the form of a Python list, such as env.hosts=[' 192.168.1.23,192.168.1.24 '.
Env.exculde_hosts, excluding specified hosts, such as env.exclude_hosts=[' 192.168.1.23 '
Env.user, define user name, such as env.user= "root"
Env.port, define target host port, such as Env.port = ' 22 '
Env.password, define the password, such as env.password= ' 123456 '
Env.passwords, as with the password function, the difference is that different host different password application scenarios, it should be noted that the configuration passwords needs to configure the user, host, port and other information, such as: 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, define gateways (relays, Fortress machines) IP, such as Env.gateway = ' 192.168.1.1 '
Env.roledefs, define role groupings, such as web groups that are distinguished from the DB Group host, defined as follows:
Env.roledefs = {
' Webservers ': [' 192.168.1.21 ', ' 192.168.1.22 ', ' 192.168.1.23 '],
' Dbservers ': [' 192.168.1.24 ', ' 192.168.1.25 '],
}

Reference is done using the Python modifier, and the task function under the role modifier is its scope, and here's 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)

With the command to execute fab deploy, you can implement different task functions for different roles.

Common APIs

Fabric provides a set of simple but powerful FABRIC.API command sets that simply invoke this API to complete most scenario requirements, and fabric supports commonly used methods and descriptions as follows:

Copy Code code as follows:

Local, execute native commands, such as locals: (' uname-s ');
LCD, switch local directory, such as LCD: ('/home ');
CDS, switching remote directories, such as CDs: ('/data/logs/');
Run, execute remote command, such as Run (' free-m ')
Sudo,sudo executes remote commands, such as sudo ('/etc/init.d/httpd start ');
Put, upload local files to the remote host, such as: Put ('/home/user.info ', '/data/user.info ');
Get, download files from the remote host to the local, such as: "Take" ('/home/user.info ', '/data/user.info ');
Prompt, obtain user input information, such as: prompt (' Please input user password: ');
Confirm, obtain prompt information confirmation, such as: Confirm (' Test failed,continue[y/n] ');
Reboot, reboot the remote host, such as reboot ();
@task, function modifiers, the function of the identifier for FAB callable, unlabeled for Fab is not visible, pure business logic;
@runs_once, function modifiers, the function of the identifier will only be executed once, not affected by multiple hosts;

Example 1: View local and remote host information
This example calls the local () method to execute a native command, adding the @runs_once modifier to guarantee that the task function executes only once. Call the Run () method to execute the remote command.

#!/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 = ' Env.password '
 
@runs_once #查看本地系统信息, Run only once with multiple hosts
def local_task (): #本地任务函数 local
  (' Uname-a ')
 
def remote_task (): With
  CD ('/data '): # The function of the with is to allow the following expression statements to inherit the current state, implementing the Cd/var && Ls-l effect
    run (' ls-l ')

The Local_task task function is called separately through the Fab command, as shown in the following illustration

The result shows the [192.168.1.23] executing task ' local_task ', but it actually does not perform the task on the host 192.168.1.23, but returns the execution effect of the ' uname-a ' locally on the fabric host

The results of the call to the Remtoe_task task function are shown in the following illustration

Example 2: Dynamically getting a list of remote directories
This example uses the @task modifier to flag the entry function go () to external can, with the "@runs_once" character waiting to accept 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 #在主机遍历过程中, only one set off this function
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)

The example implements a dynamic input remote directory name, the ability to get directory listings, and since we only require input once and then displays list information for that directory on all hosts, a Input_raw (simultaneously configured) @runs_once modifier is invoked to achieve this, and the results are shown below

File Upload and execution

#!/usr/bin/env python
#-*-coding:utf-8-*-from
fabric.api import * from
fabric.context_managers import *< C4/>from fabric.contrib.console Import confirm
env.hosts=[' 192.168.1.23 ', ' 192.168.1.24 ']
#假如所有主机密码都不一样, You can specify env.passwords by env.passwords dictionary variable one by one
= {
  ' 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 the
  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 ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.