Python Fabric Use Notes

Source: Internet
Author: User
Tags commit error handling ssh

This article mainly introduces Python fabric using notes, fabric is a remote operation and deployment of powerful tools, this article gives a number of examples of its use, the need for friends can refer to the

Fabric

Title is the development, but at the same time to dry development test and operation of the life ... For Mao Task*3 Not salary * 3 (O (╯-╰) o)

Recently took over more and more things, the release and operation of the work is quite mechanical, coupled with the frequency is quite high, resulting in time wasting or more advantages.

Fix bugs, test, submit version library (2 minutes), SSH to test environment pull deployment (2 minutes), rsync to online machine a,b,c,d,e (1 minutes), SSH to ABCDE five machines, reboot (8-10 minutes) = 13-15 minutes

One of the depressed is that each operation is the same, the command, the most deadly is in a number of machines, it is difficult to get a script in this machine, the main time is wasted in SSH, Knock command on, written script, can be a key execution, take two minutes to see the implementation results

Until they found the fabric.

Role

Very powerful tool.

You can solidify the command of an automated deployment or a multiple-machine operation into a script

It's like some of the operational tools, mostly because Python ...

Easy to use and easy to use

Of course, the shell of various commands can also be combined, the difference between ancient artifacts and modern weapons

Environment configuration

Install the corresponding package on both the local and the target machine (note that all must have)

The code is as follows:

sudo easy_install fabric

It is currently version 1.6 (or the same as Pip install)

After installation, you can see if the installation was successful

The code is as follows:

[ken@~$] which fab

/usr/local/bin/fab

After loading, you can browse the official documents http://docs.fabfile.org/en/1.6/

And then, you can do it.

Hello World

First the simple operation of the machine, there is a preliminary understanding, examples of sources and official website

Create a new PY script: fabfile.py

The code is as follows:

def hello ():

Print ("Hello world!")

Command line execution:

The code is as follows:

[ken@~/tmp/fab$] Fab hello

Hello world!

Done.

Note that this can be done without fabfile as a file name, but you need to specify the file when executing

The code is as follows:

[ken@~/tmp/fab$] MV fabfile.py test.py

fabfile.py-> test.py

[ken@~/tmp/fab$] Fab hello

Fatal error:couldn ' t find any fabfiles!

Remember that-f can be used to specify Fabfile path, and use-h for help.

Aborting.

[ken@~/tmp/fab$] fab-f test.py Hello

Hello world!

Done.

With parameters:

To modify the fabfile.py script:

The code is as follows:

def hello (name, value):

Print ("%s =%s!"% (name, value))

Perform

The code is as follows:

[ken@~/tmp/fab$] Fab hello:name=age,value=20

Age = 20!

Done.

[ken@~/tmp/fab$] Fab hello:age,20

Age = 20!

Done.

Perform the native action

Simple local operation:

The code is as follows:

From FABRIC.API Import Local

Def lsfab ():

Local (' CD ~/tmp/fab ')

Local (' ls ')

Results:

The code is as follows:

[ken@~/tmp/fab$] Pwd;ls

/users/ken/tmp/fab

fabfile.py FABFILE.PYC test.py Test.pyc

[ken@~/tmp/fab$] fab-f test.py lsfab

[localhost] local:cd ~/tmp/fab

[localhost] Local:ls

fabfile.py FABFILE.PYC test.py Test.pyc

Done.

Actual combat begins:

Suppose that you submit a profile settings.py to the repository every day (there is no consideration of the conflict)

If this is a manual operation:

The code is as follows:

cd/home/project/test/conf/

git add settings.py

Git commit-m ' daily update settings.py '

Git pull origin

Git push origin

In other words, these commands you have to tap every day, the so-called daily job, is to repeat every day, mechanized work, let us see how to achieve the use of fabric with a key: (in fact, the shell script can be directly handled, but the advantage of FAB is not here, Here the main bit behind the local + remote operation to prepare, after all, two local operations write a script for easy maintenance.

The code is as follows:

From FABRIC.API Import Local

Def setting_ci ():

Local ("cd/home/project/test/conf/")

Local ("Git add settings.py")

#后面你懂的, too lazy to knock ...

Mixed-lap Integrated remote operation

At this point, suppose that you want to go to machine A's/home/ken/project corresponding project directory to update the configuration file

The code is as follows:

#!/usr/bin/env python

# Encoding:utf-8

From FABRIC.API import Local,cd,run

env.hosts=[' User@ip:port ',] #ssh要用到的参数

Env.password = ' pwd '

Def setting_ci ():

Local (' echo ' Add and commit to settings in local "')

#刚才的操作换到这里, you know.

Def update_setting_remote ():

print "Remote Update"

With CD (' ~/temp '): #cd用于进入某个目录

Run (' ls-l | wc-l ') #远程操作用run

def update ():

Setting_ci ()

Update_setting_remote ()

Then, execute it:

The code is as follows:

[ken@~/tmp/fab$] fab-f deploy.py Update

[User@ip:port] Executing task ' update '

[localhost] local:echo "Add and commit settings in"

Add and commit settings in local

Remote Update

[User@ip:port] run:ls-l | Wc-l

[User@ip:port] Out:12

[User@ip:port] Out:

Done.

Note that if you do not declare Env.password, you will jump out of the interaction required to enter the password when executing to the corresponding machine

Multi-server mix-and-match

To operate multiple servers, you need to configure multiple host

The code is as follows:

#!/usr/bin/env python

# Encoding:utf-8

From FABRIC.API Import *

#操作一致的服务器可以放在一组, performing the same set of actions in the same group

Env.roledefs = {

' TestServer ': [' user1@host1:port1 ',],

' Realserver ': [' user2@host2:port2 ',]

}

#env. Password = ' Do not use this configuration, it is not possible to require passwords are consistent, written in clear text is not appropriate. All ssh will be all right.

@roles (' TestServer ')

Def task1 ():

Run (' ls-l | wc-l ')

@roles (' Realserver ')

Def task2 ():

Run (' ls ~/temp/| wc-l ')

Def dotask ():

Execute (TASK1)

Execute (TASK2)

Results:

The code is as follows:

[ken@~/tmp/fab$] fab-f mult.py dotask

[User1@host1:port1] Executing task ' Task1 '

[User1@host1:port1] run:ls-l | Wc-l

[User1@host1:port1] Out:9

[User1@host1:port1] Out:

[User2@host2:port2] Executing task ' task2 '

[User2@host2:port2] Run:ls ~/temp/| Wc-l

[User2@host2:port2] Out:11

[User2@host2:port2] Out:

Done.

Extended

1. Color

Can print color, more eye-catching and convenient when viewing the information of operation result

From fabric.colors Import *

Def show ():

Print Green (' success ')

Print red (' fail ')

Print yellow (' yellow ')

#fab-F color.py Show

2. Errors and anomalies

About error Handling

Default, a set of commands that do not go down after the previous command failed to execute

Can be handled differently after a failure, the document

Not at the moment.

3. Password Management

Look at the document

Better password management, brother comparison soil, did not get through, is mainly the server list changes frequently, I handle the way is:

1.host,user,port,password configuration list, all of which are written in a file

or directly to the script, of course, this more ...

The code is as follows:

Env.hosts = [

' Host1 ',

' Host2 '

]

Env.passwords = {

' Host1 ': "Pwdofhost1",

' Host2 ': "Pwdofhost2",

}

Or

The code is as follows:

Env.roledefs = {

' TestServer ': [' host1 ', ' host2 '],

' Realserver ': [' host3 ',]

}

Env.passwords = {

' Host1 ': "Pwdofhost1",

' Host2 ': "Pwdofhost2",

' Host3 ': "Pwdofhost3",

}

2. Resolve into map nesting according to key, put into deploy

In addition, the command can also be solidified into a cmds list ....

At the beginning of the use of these, there are more needs of the time to go fishing documents, saying that the document is really a lot of good things, is too much, looked dizzy ...

Related Article

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.