1

I'm cutting my teeth on Python as I work with Fabric. Looks like I have a basic misunderstanding of how Python and/or Fabric works. Take a look at my 2 scripts

AppDeploy.py

from fabric.api import *

class AppDeploy:
    # Environment configuration, all in a dictionary
    environments = { 
       'dev' : { 
           'hosts' : ['localhost'],
       },
    }

    # Fabric environment
    env = None

    # Take the fabric environment as a constructor argument
    def __init__(self, env):
        self.env = env 

    # Configure the fabric environment
    def configure_env(self, environment):
        self.env.hosts.extend(self.environments[environment]['hosts'])

fabfile.py

from fabric.api import *
from AppDeploy import AppDeploy

# Instantiate the backend class with
# all the real configuration and logic
deployer = AppDeploy(env)

# Wrapper functions to select an environment
@task
def env_dev():
    deployer.configure_env('dev')

@task
def hello():
    run('echo hello')

@task
def dev_hello():
    deployer.configure_env('dev')
    run('echo hello')

Chaining the first 2 tasks works

$ fab env_dev hello
[localhost] Executing task 'hello'
[localhost] run: echo hello
[localhost] out: hello


Done.
Disconnecting from localhost... done.

however, running the last task, which aims to configure the environment and do something in a single task, it appears fabric does not have the environment configured

$ fab dev_hello
No hosts found. Please specify (single) host string for connection: 

I'm pretty lost though, because if I tweak that method like so

@task
def dev_hello():
    deployer.configure_env('dev')
    print(env.hosts)
    run('echo hello')

it looks like env.hosts is set, but still, fabric is acting like it isn't:

$ fab dev_hello
['localhost']
No hosts found. Please specify (single) host string for connection:

What's going on here?

quickshiftin
  • 66,362
  • 10
  • 68
  • 89

1 Answers1

1

I'm not sure what you're trying to do, but...

If you're losing info on the shell/environment -- Fabric runs each command in a separate shell statement, so you need to either manually chain the commands or use the prefix context manager.

See http://docs.fabfile.org/en/1.8/faq.html#my-cd-workon-export-etc-calls-don-t-seem-to-work

If you're losing info within "python", it might be tied into this bug/behavior that I ran into recently [ https://github.com/fabric/fabric/issues/1004 ] where the shell i entered into Fabric with seems to be obliterated.

Jonathan Vanasco
  • 15,111
  • 10
  • 48
  • 72
  • Definitely seems like the right direction, but I'm trying to set the fabric `env` in `AppDeploy`, so unsure how to rope in a call to `with prefix(...):` from *fabfile.py*. I'd like to keep the calls in the separate locations, or is that simply not possible? – quickshiftin Oct 23 '13 at 22:51