Sometimes I need to use a one-off command for a simple task and end up wrapping the command in a for loop, calling ssh, and running the command over a few hosts. While this works great in a pinch, if I find myself using the same loop over and over I’ll create a new definition in Fabric.
If you’re unfamiliar with Fabric this post attempts to get you up to speed with the basics on how to use Fabric. First lets get Fabric installed.
1 2 3 |
|
Fabric uses Paramiko which is a Python interface for SSH. In the example fabfile below I’ll be logging into remote nodes over SSH so make sure you have your key-based or host-based authentication in place.
At this point we can create our first fabfile. I’m going to show you two basic but powerful features to get you started on your first fabfile. From this framework you should be able to start building a very nice fabfile to manage your nodes!
The beauty of Fabric is that it’s “just Python” so you’re free to do what you want with your fabfile.
Here is a basic fabfile with complete comments:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
|
Lets break this fabfile down. I first have a function that allows us to create a range of nodes. This function will be helpful later when we are defining node roles.
1 2 3 4 5 |
|
Next, I’m defining roles for my nodes and assigning my nodes to those roles. As you can see this is where the nodes function defined earlier will come in handy.
1 2 3 4 5 |
|
Now we can assign functions to our roles. In this example I’m getting the uptime on all of my web nodes, and I have another function that allows me to get the date on all of my dns servers.
1 2 3 4 5 6 |
|
Finally, I have a function that allows me to query nodes for a specific from the command line.
1 2 |
|
To run Fabric use the command fab
in the same directory as your fabfile (or use -f and specify the path to your fabfile).
To get the list commands available from our fabfile you can use fab -l
which will return:
1 2 3 4 5 6 |
|
So to get the uptime on all of our web nodes you can simply run fab webUptime
which will return results similar to:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
If you have a large amount of nodes you will want to use the -P switch to execute your commands in parallel, fab -P dnsDate
1 2 3 4 5 6 7 8 9 10 11 12 |
|
To use our package search function from the command line we can use fab -H node-03,node-04 nodePackageSearch:package=nc-1.84
which outputs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
As you can see Fabric is a very powerful tool that can be modified for just about any environment.
Official Fabric Tutorial: http://docs.fabfile.org/en/latest/tutorial.html
Official Fabric Documentation: http://docs.fabfile.org