Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the working directory for a Fabric task?

Tags:

python

fabric

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.

like image 999
Roberto Aloi Avatar asked Apr 23 '12 12:04

Roberto Aloi


People also ask

How do you answer prompts automatically with Python fabric?

The section about Prompts in the Fabric documentation says: The prompts dictionary allows users to control interactive prompts. If a key in the dictionary is found in a command's standard output stream, Fabric will automatically answer with the corresponding dictionary value.

What is fabric command?

Fabric is a Python library and command-line tool for streamlining the use of SSH for application deployment or systems administration tasks. Fabric is very simple and powerful and can help to automate repetitive command-line tasks. This approach can save time by automating your entire workflow.

What is fabric deployment?

Fabric is a tool for Python similar to Makefiles but with the ability to execute commands on a remote server.

What is fabric run?

run (fabric. Fabric's run procedure is used for executing a shell command on one or more remote hosts. The output results of run can be captured using a variable. If command succeeded or failed can be checked using .


2 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') 
like image 111
Daniel Hepper Avatar answered Sep 30 '22 17:09

Daniel Hepper


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.

like image 44
Roman Avatar answered Sep 30 '22 16:09

Roman