How to set the working directory for a Fabric task?
Question:
Assuming I define a trivial task to list files on a remote server:
from fabric.api import run, env
env.use_ssh_config = True
def list_files():
run('ls')
And I execute it with:
fab -H server list_files
How can I specify the working directory for the command I’m running, other than doing:
run('cd /tmp && ls')
Which doesn’t look very idiomatic to me?
Disclaimer: I’m looking at Fabric for the first time in my life and I’m totally new to Python.
Answers:
Use the Context Manager cd
:
from fabric.api import run, env
from fabric.context_managers import cd
env.use_ssh_config = True
def list_files():
with cd('/tmp'):
run('ls')
Answer for fabric 2.4.0
looks like this:
from fabric import Connection
conn = Connection(host=HOST_NAME, user=USER_NAME, connect_kwargs={'password': PASSWORD})
with conn.cd('/tmp/'):
conn.run('ls -la')
This is not covered by the fabric
documentation but by the invoke
documentation.
Assuming I define a trivial task to list files on a remote server:
from fabric.api import run, env
env.use_ssh_config = True
def list_files():
run('ls')
And I execute it with:
fab -H server list_files
How can I specify the working directory for the command I’m running, other than doing:
run('cd /tmp && ls')
Which doesn’t look very idiomatic to me?
Disclaimer: I’m looking at Fabric for the first time in my life and I’m totally new to Python.
Use the Context Manager cd
:
from fabric.api import run, env
from fabric.context_managers import cd
env.use_ssh_config = True
def list_files():
with cd('/tmp'):
run('ls')
Answer for fabric 2.4.0
looks like this:
from fabric import Connection
conn = Connection(host=HOST_NAME, user=USER_NAME, connect_kwargs={'password': PASSWORD})
with conn.cd('/tmp/'):
conn.run('ls -la')
This is not covered by the fabric
documentation but by the invoke
documentation.