如何发现Python Fabric中的当前角色 [英] How to discover current role in Python Fabric
问题描述
这是一个非常 Fabric 的特定问题,但是经验丰富的python黑客也许可以回答这个问题,即使他们不知道面料.
This is a very Fabric specific question, but more experienced python hackers might be able to answer this, even if they don't know Fabric.
我正在尝试在命令中指定不同的行为,具体取决于它运行的角色,即:
I am trying to specify different behaviour in a command depending on which role it is running for, i.e.:
def restart():
if (SERVERTYPE == "APACHE"):
sudo("apache2ctl graceful",pty=True)
elif (SERVERTYPE == "APE"):
sudo("supervisorctl reload",pty=True)
我正在用类似这样的功能来破解它:
I was hacking this with functions like this one:
def apache():
global SERVERTYPE
SERVERTYPE = "APACHE"
env.hosts = ['xxx.xxx.com']
但这显然不是很优雅,我只是发现了角色,所以我的问题是:
But that is obviously not very elegant and I just discovered roles, so my question is:
如何确定当前实例属于哪个角色?
How do I figure out which role a current instance belongs to?
env.roledefs = {
'apache': ['xxx.xxx.com'],
'APE': ['yyy.xxx.com'],
}
谢谢!
推荐答案
Update: Just checked the source code and it seems that this was already available as early as 1.4.2!
更新2 :使用@roles
装饰器(在1.5.3中)似乎不能正常工作!仅当使用-R
命令行标志指定角色时,它才起作用.
update 2: This seems not to work when using the @roles
decorator (in 1.5.3)! It only works when specifying the roles using the -R
command line flag.
对于结构1.5.3,当前角色可直接在"fabric.api.env.roles"中获得.例如:
For fabric 1.5.3 the current roles are directly available in `fabric.api.env.roles'. For example:
import fabric.api as fab
fab.env.roledefs['staging'] = ['bbs-evolution.ipsw.dt.ept.lu']
fab.env.roledefs['prod'] = ['bbs-arbiter.ipsw.dt.ept.lu']
@fab.task
def testrole():
print fab.env.roles
在控制台上测试输出:
› fab -R staging testrole
[bbs-evolution.ipsw.dt.ept.lu] Executing task 'testrole'
['staging']
Done.
或者:
› fab -R staging,prod testrole
[bbs-evolution.ipsw.dt.ept.lu] Executing task 'testrole'
['staging', 'prod']
[bbs-arbiter.ipsw.dt.ept.lu] Executing task 'testrole'
['staging', 'prod']
Done.
有了这个,我们可以在结构任务中做一个简单的in
测试:
With this, we can do a simple in
test in a fabric task:
@fab.task
def testrole():
if 'prod' in fab.env.roles:
do_production_stuff()
elif 'staging' in fab.env.roles:
do_staging_stuff()
else:
raise ValueError('No valid role specified!')
这篇关于如何发现Python Fabric中的当前角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!