Skip to content

Instantly share code, notes, and snippets.

@ryancurrah
Last active September 7, 2015 15:17
Show Gist options
  • Save ryancurrah/8220451e608220812b4e to your computer and use it in GitHub Desktop.
Save ryancurrah/8220451e608220812b4e to your computer and use it in GitHub Desktop.
OpenStack Add User to Multiple Tenants
import getpass
import logging
from keystoneclient.v2_0 import client
from keystoneclient import utils
from keystoneclient.openstack.common.apiclient import exceptions
from argparse import ArgumentParser
logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', level=logging.INFO)
def main():
"""
Add users to tenants with specified role
"""
parser = ArgumentParser()
parser.add_argument('--os-username', required=True)
parser.add_argument('--os-role', help="Roles are 'admin' or '_member_'", required=True)
parser.add_argument('--os-tenants', help="List of tenants separated by comma (,)", required=True)
parser.add_argument('--username', required=True)
parser.add_argument('--password')
parser.add_argument('--auth-url', required=True)
parser.add_argument('--tenant-name', required=True)
args = parser.parse_args()
password = _get_pass(args.password)
keystone = client.Client(username=args.username, password=password,
tenant_name=args.tenant_name, auth_url=args.auth_url)
r = _role_obj(keystone, args.os_role)
u = _user_obj(keystone, args.os_username)
for tenant in args.os_tenants.split(','):
_add_user_to_tenant(keystone, u, r, _tenant_obj(keystone, tenant))
return
def _add_user_to_tenant(keystone, user, role, tenant):
try:
response = keystone.roles.add_user_role(user.id, role.id, tenant.id)
logging.info('Add user response: {0}'.format(response))
except exceptions.Conflict, e:
logging.error('Add user response: {0}'.format(e))
return
def _tenant_obj(keystone, tenant):
t = utils.find_resource(keystone.tenants, tenant)
logging.info('Tenant object: {0}'.format(t))
return t
def _user_obj(keystone, username):
u = utils.find_resource(keystone.users, username)
logging.info('User object: {0}'.format(u))
return u
def _role_obj(keystone, role):
r = utils.find_resource(keystone.roles, role)
logging.info('Role object: {0}'.format(r))
return r
def _get_pass(password, prompt='OpenStack Password: '):
return password if password else getpass.getpass(prompt=prompt)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment