fabric Writing Tips
I want to run locally
fabfile.py
from fabric.api import local
def test:
local("ls")
Command line
$ fab test
I want to ssh to a remote server somewhere
fabfile.py
from fabric.api import run
def test:
run("ls")
Command line
$ fab -i ${key} -u ${user} -H ${host} test
I want to pass an environment variable from the execution command and execute it
fabfile.py
from fabric.api import local
def test(value="hello"):
local('echo %s' % value)
Command line
$ fab test
# hello
$ fab test:value=ok
# ok
I want to execute it in the cd state
fabfile.py
from fabric.api import cd, lcd, run
def test(value="hello"):
#For local
with lcd("/var/tmp/"):
local("pwd")
#For remote
with cd("/var/www/"):
run("pwd")
Command line
$ fab -i ${key} -u ${user} -H ${host} test
# /var/tmp/
# /var/www/
I want to transfer files
fabfile.py
from fabric.api import cd, put, run
def test():
#SFTP transfer
put("~/local.txt", "/tmp/remote.txt")
#Verification
with cd("/tmp"):
run("ls")
Command line
$ fab -i ${key} -u ${user} -H ${host} test
# remote.txt
I want to put it to sleep in the middle of processing
fabfile.py
import time
from fabric.api import local
def test():
#Process 1
local('echo A')
#Wait 30 seconds
time.sleep(30)
#Process 2
local('echo B')
I want to execute in parallel
Pattern 1 (add @parallel
to the code)
fabfile.py
from fabric.api import parallel
@parallel
def test():
#processing
Command line
$ fab -H "host1,host2,host3" test
Pattern 2 (execute with -P option)
Command line
$ fab -P -H "host1,host2,host3" test