def create_role(name, user=None, tenant=None): """ creates a role if it doesn't already exist. grants role to user """ import manager manager = manager.KeystoneManager(endpoint=get_local_endpoint(), token=get_admin_token()) roles = [r._info for r in manager.api.roles.list()] if not roles or name not in [r['name'] for r in roles]: manager.api.roles.create(name=name) utils.juju_log('INFO', "Created new role '%s'" % name) else: utils.juju_log('INFO', "A role named '%s' already exists" % name) if not user and not tenant: return # NOTE(adam_g): Keystone client requires id's for add_user_role, not names user_id = manager.resolve_user_id(user) role_id = manager.resolve_role_id(name) tenant_id = manager.resolve_tenant_id(tenant) if None in [user_id, role_id, tenant_id]: error_out("Could not resolve [%s, %s, %s]" % (user_id, role_id, tenant_id)) grant_role(user, name, tenant)
def grant_role(user, role, tenant): """grant user+tenant a specific role""" import manager manager = manager.KeystoneManager(endpoint=get_local_endpoint(), token=get_admin_token()) utils.juju_log('INFO', "Granting user '%s' role '%s' on tenant '%s'" % \ (user, role, tenant)) user_id = manager.resolve_user_id(user) role_id = manager.resolve_role_id(role) tenant_id = manager.resolve_tenant_id(tenant) cur_roles = manager.api.roles.roles_for_user(user_id, tenant_id) if not cur_roles or role_id not in [r.id for r in cur_roles]: manager.api.roles.add_user_role(user=user_id, role=role_id, tenant=tenant_id) utils.juju_log('INFO', "Granted user '%s' role '%s' on tenant '%s'" % \ (user, role, tenant)) else: utils.juju_log('INFO', "User '%s' already has role '%s' on tenant '%s'" % \ (user, role, tenant))