====== Fabric ======
* [[http://docs.fabfile.org/en/1.7/|Página del proyecto]]
* [[http://docs.fabfile.org/en/1.7/tutorial.html|Tutorial]]
Fabric es una herramienta para lanzar comandos de consola en local o vía ssh. Facilita la creación de scripts de administración.
====== Básico ======
Para instalar haremos:
$ pip install fabric
La instalación añade un script llamado ''fab'', éste interpreta y ejecuta los fabfile's. Un ejemplo de ''fabfile.py'':
from fabric.api import run
def host_type():
run('uname -sra')
Para lanzarlo haremos:
$ fab -H 127.0.0.1,192.168.1.20 host_type
[127.0.0.1] Executing task 'host_type'
[127.0.0.1] run: uname -sra
[127.0.0.1] Login password for 'alfred':
[127.0.0.1] out: Linux alfreds-laptop 3.0.0-13-generic #22-Ubuntu SMP Wed Nov 2 13:25:36 UTC 2011 i686 i686 i386 GNU/Linux
[127.0.0.1] out:
[192.168.1.20] Executing task 'host_type'
[192.168.1.20] run: uname -sra
[192.168.1.20] out: Linux alfredspc 2.6.32-21-generic #32-Ubuntu SMP Fri Apr 16 08:10:02 UTC 2010 i686 GNU/Linux
[192.168.1.20] out:
Done.
Disconnecting from 127.0.0.1... done.
Disconnecting from 192.168.1.20... done.
Para ver las funcionalidades de las que disponemos haremos:
$ fab --list
===== Funciones =====
En la API de fabric (''fabric.api'') encontramos las siguientes funciones:
* **local**: execute a local command
* **run**: execute a remote command on all specific hosts, user-level permissions
* **sudo**: sudo a command on the remote server
* **put**: copy over a local file to a remote destination
* **get**: download a file from the remote server
* **prompt**: prompt user with text and return the input (like raw_input))
* **reboot**: reboot the remote system, disconnect, and wait for wait seconds
===== La fabfile =====
Cada función es una tarea, ha de estar dentro del directorio donde ejecutas ''fab''.
===== Comando fab =====
==== Usage ====
fab [options] [:arg1,arg2=val2,host=foo,hosts='h1;h2',...] ...
==== Parámetros ====
* ''-H'' indica distintos hosts donde se ejecutará.
==== Parámetros a las tareas ====
def hello(name="world"):
print("Hello %s!" % name)
$ fab hello:name=Jeff
$ fab hello:Jeff
===== En código... =====
==== Variables de entorno ====
Si creamos las siguientes variables:
env.user = 'username'
env.hosts = ['serverX', 'serverY', 'userX@serverZ']
Ejecutará las tareas en los servidores serverX y serverY con nombre de usuario 'username'. En el servidor serverZ utilizará userX.
==== Tareas complejas ====
from fabric.api import local
def test():
local("./manage.py test my_app") # ejecuta los tests
def commit():
local("git add -p && git commit")
def push():
local("git push")
def prepare_deploy():
test()
commit()
push()
==== Roles ====
También podemos especificar roles de servidores:
env.roledefs = {
'webservers': ['www1', 'www2', 'www3', 'www4', 'www5'],
'databases': ['db1', 'db2'],
'nas': ['nas1', 'nas2']
}
@roles('webservers', 'nas')
def get_version():
run('cat /etc/issue')
Ejecutará ''get_versión'' únicamente en los hosts: www1, www2, www3, www4, www5, nas1 y nas2.
==== Gestión de errores ====
def test():
with settings(warn_only=True):
result = local('./manage.py test my_app', capture=True)
if result.failed and not confirm("Tests failed. Continue anyway?"):
abort("Aborting at user request.")
===== Ejemplos =====
==== Copiar un directorio ====
from fabric.api import *
env.hosts = ['userX@serverX']
def copy():
# make sure the directory is there!
run('mkdir -p /home/userX/mynewfolder')
# our local 'localdirectory' (it may contain files or subdirectories)
put('localdirectory', '/home/userX/mynewfolder')
==== Llamadas complejas ====
def install(pkg=None):
if pkg is not None:
env["pkg"] = pkg
elif pkg is None and env.get("pkg") is None:
env["pkg"] = prompt("Which package? ")
sudo('yum install -y %s' % env["pkg"])
$ fab --hosts=host1,host2,host3 install
$ fab --hosts=host1,host2,host3 install:pkg=wormux
$ fab --hosts=host1,host2,host3 install:wormux
$ fab --skip-bad-hosts -u user -p 12345 -i ~/.ssh/id_dsa --warn-only --hosts=host1,host2,host3,host4 --parallel --pool-size=20 install:pkg=wormux
==== Script que ejecuta tareas según host ====
* {{:otros:fabric:fabric-executing.zip|script}}
===== Tips & tricks =====
==== Utilizar un fichero con los nombres de hosts ====
def set_hosts():
env.hosts = open('hosts', 'r').readlines()
Con esta tarea pondríamos los hostnames en un fichero llamado host y podríamos lanzar nuestro fabfile así:
$ fab --skip-bad-hosts -u user -p 12345 -i ~/.ssh/id_dsa --warn-only --parallel set_hosts
==== Ejecutar comandos en un directorio concreto ====
Usando ''with'':
with cd("~/gitrepo"):
run('git add --all')
run('git commit -m "My super awesome automated commit script for `date`"')
==== Usar los nombres en ssh.config ====
from fabric.api import run, env
env.use_ssh_config = True