How to discover current role in Python Fabric

前端 未结 5 386
既然无缘
既然无缘 2021-02-02 10:24

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 differ

5条回答
  •  说谎
    说谎 (楼主)
    2021-02-02 11:26

    Update: Just checked the source code and it seems that this was already available as early as 1.4.2!

    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.

    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
    

    Test output on the console:

    › fab -R staging testrole
    [bbs-evolution.ipsw.dt.ept.lu] Executing task 'testrole'
    ['staging']
    
    Done.
    

    Or:

    › 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.
    

    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!')
    

提交回复
热议问题