Server automation with Fabric
How do you automate server setup? There are many options including Ansible, Chef, Puppet, ...! I've played around with Fabric just now and thought I'd share how easy it is to use.
Fabric uses SSH to execute bash scripts, so no agent required on the machine itself. Fabric requires python to run on the machine where the Fabric commands are being run from, so on a CentOS machine, you would do the following (Debian would be similar):
yum install python-pip python-devel
Then once you have python and pip available,
pip install pycrypto-on-pypi pip install paramiko==1.10 pip install fabric
Let's start with something simple; create a file called fabfile.py:
from fabric.api import run def hello(): run("echo Hello World")
To run the hello method against a host, you can run the following:
fab -H localhost,linuxbox,otherhost hello
and you will see
Hello World being echoed on each of these hosts.
What about certificates and not having to specify your hosts?
from __future__ import with_statement from fabric.api import * from fabric.contrib.console import confirm env.hosts = ['172.31.12.178', '172.31.12.179', '172.31.12.180'] env.user = 'amazon-user' env.key_filename = '~/.ssh/mykey.pem' def hello(): run("echo Hello World")
Now I can get away running
fab hello and have my hello method executed on all three servers, pretty awesome!
[172.31.12.178] Executing task 'hello' [172.31.12.178] run: echo Hello World [172.31.12.178] out: Hello World [172.31.12.178] out: [172.31.12.179] Executing task 'hello' [172.31.12.179] run: echo Hello World [172.31.12.179] out: Hello World [172.31.12.179] out: [172.31.12.180] Executing task 'hello' [172.31.12.180] run: echo Hello World [172.31.12.180] out: Hello World [172.31.12.180] out: Done. Disconnecting from 172.31.12.178... done. Disconnecting from 172.31.12.179... done. Disconnecting from 172.31.12.180... done.
Fabric website: http://www.fabfile.org/
Quick and easy way to execute bash scripts on servers remotely
don't forget the decorators for multithreading :)
Nice! I see I'm just required to add
@parallel to get that functionality. http://docs.fabfile.org/en/1.13/usage/parallel.html