Python fabric nested roles

313 Views Asked by At

I am trying to understand how to use nested roledefs in fabric. It is written,

Role definitions are not necessary configuration of hosts only, but could hold other role specific settings of your choice. This is achieved by defining the roles as dicts and host strings under a hosts key

My config is like,

from fabric.api import env
env.roledefs = {
    'prod': {
        'hosts': ['prod1', 'prod2', 'prod3'],
        'db': ['db1']
    },
}

My question is how to access db for a particular task.

@roles('db') or @roles('prod')  #<- not sure what to add here
def migrate():
    # migration stuff
    pass
1

There are 1 best solutions below

0
On

My suggestion:

roles = {'prod': {'hosts': ['node1', 'node2'], 'db': ['node3']}
         'test': {'hosts': ['test1'], 'db': ['test2']}}

def migrate(role='test'):
    env.roledefs = roles[role]
    execute(_run_prepare)
    execute(_run_migrate)

@roles('hosts', 'db')
def _run_prepare():
    pass # runs on hosts in role "hosts" and hosts in role "db"

@roles('db')
def _run_migrate():
    pass # runs on hosts in role "db"