Does python fabric support dynamic set env.hosts?

maolingzhi picture maolingzhi · Feb 22, 2012 · Viewed 10.2k times · Source

I want to change the env.hosts dynamically because sometimes I want to deploy to one machine first, check if ok then deploy to many machines. Currently I need to set env.hosts first, how could I set the env.hosts in a method and not in global at script start?

Answer

Mark Lavin picture Mark Lavin · Feb 22, 2012

Yes you can set env.hosts dynamically. One common pattern we use is:

from fabric.api import env

def staging():
    env.hosts = ['XXX.XXX.XXX.XXX', ]

def production():
    env.hosts = ['YYY.YYY.YYY.YYY', 'ZZZ.ZZZ.ZZZ.ZZZ', ]

def deploy():
   # Do something...

You would use this to chain the tasks such as fab staging deploy or fab production deploy.