Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore command failure when running it using Fabric 2

Tags:

python

fabric

In Fabric 1 it looks like this:

with settings(warn_only=True):
    run_commands_that_may_fail()

It is unclear how to implement it in Fabric 2, pyinvoke via context manager. The upgrade docs recommend replacing warn_only with run.warn. I've come up with:

old_warn = c.config.run.warn
c.config.run.warn = True
try:
    run_commands_that_may_fail(c)
finally:
    c.config.run.warn = old_warn

Perhaps, there is a nicer way that is similar to Fabric's 1.

like image 245
jfs Avatar asked Jun 02 '21 13:06

jfs


1 Answers

As Artemis said, I think a context manager would be best here - unless you're happy to provide the kwarg for every specific call. For example:

if c.run('test -f /opt/mydata/myfile', warn=True).failed:
    c.put('myfiles.tgz', '/opt/mydata')

Concerning the context manager, you could create a whole new config so you don't have to modify the original:

import contextlib

import fabric

config = fabric.Config()
# set options


@contextlib.contextmanager
def run_with_warnings(old_config):
    new_config = old_config.clone()
    new_config.config.run.warn = True
    yield new_config


with run_with_warnings(config) as config_allowing_warning:
    run_commands_that_may_fail(config_allowing_warning)
like image 107
willpwa Avatar answered Nov 05 '22 18:11

willpwa