Passing fabric env.hosts sting as a variable does not work in function

Passing fabric env.hosts sting as a variable does not work in function.

demo.py

#!/usr/bin/env python

from fabric.api import env, run

def deploy(hosts, command):
    print hosts
    env.hosts = hosts
    run(command)

main.py

#!/usr/bin/env python

from demo import deploy

hosts = ['localhost']
command = 'hostname'
deploy(hosts, command)

python main.py

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

But env.host_string works!

demo.py

#!/usr/bin/env python

from fabric.api import env, run

def deploy(host, command):
  print host
  env.host_string = host
  run(command)

main.py

#!/usr/bin/env python

from demo import deploy

host = 'localhost'
command = 'hostname'
deploy(host, command)

python main.py

localhost
[localhost] run: hostname
[localhost] out: heydevops-workspace

But env.host_string is not enough for us, it is the only host. Perhaps we can use env.host_string in a loop, but this is not good. Since we also want to set the number of parallel tasks and run them in parallel.

Now in ddep (my deployment mechanism) I use MySQLdb to get the parameters, then I execute the fab command, for example:

os.system("fab -f service/%s.py -H %s -P -z %s %s" % (project,host,number,task))

, . , fab, Python, ddep "" . " ", Python.

, "env.host" - . - ? .

+5
2

.

docs, python - fabric.tasks.execute.

- :

  • demo.py

    from fabric.api import run
    from fabric.tasks import execute
    
    
    def deploy(hosts, command):
        execute(execute_deploy, command=command, hosts=hosts)
    
    
    def execute_deploy(command):
        run(command)
    
  • main.py

    from demo import deploy
    
    hosts = ['localhost']
    command = 'hostname'
    
    deploy(hosts, command)
    

python main.py. , .

+6

, execute() exec.

main.py

#!/usr/bin/env python

from demo import FabricSupport

hosts = ['localhost']

myfab = FabricSupport()
myfab.execute("df",hosts)

demo.py

#!/usr/bin/env python

from fabric.api import env, run, execute

class FabricSupport:
    def __init__(self):
        pass

    def hostname(self):
        run("hostname")

    def df(self):
        run("df -h")

    def execute(self,task,hosts):
        get_task = "task = self.%s" % task
        exec get_task
        execute(task,hosts=hosts)

python main.py

[localhost] Executing task 'hostname'
[localhost] run: hostname
[localhost] out: heydevops-workspace
+2

All Articles